Merge branch 'for-linus' into raid56-experimental
[deliverable/linux.git] / fs / btrfs / volumes.c
CommitLineData
0b86a832
CM
1/*
2 * Copyright (C) 2007 Oracle. All rights reserved.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
17 */
18#include <linux/sched.h>
19#include <linux/bio.h>
5a0e3ad6 20#include <linux/slab.h>
8a4b83cc 21#include <linux/buffer_head.h>
f2d8d74d 22#include <linux/blkdev.h>
788f20eb 23#include <linux/random.h>
b765ead5 24#include <linux/iocontext.h>
6f88a440 25#include <linux/capability.h>
442a4f63 26#include <linux/ratelimit.h>
59641015 27#include <linux/kthread.h>
53b381b3
DW
28#include <linux/raid/pq.h>
29#include <asm/div64.h>
4b4e25f2 30#include "compat.h"
0b86a832
CM
31#include "ctree.h"
32#include "extent_map.h"
33#include "disk-io.h"
34#include "transaction.h"
35#include "print-tree.h"
36#include "volumes.h"
53b381b3 37#include "raid56.h"
8b712842 38#include "async-thread.h"
21adbd5c 39#include "check-integrity.h"
606686ee 40#include "rcu-string.h"
3fed40cc 41#include "math.h"
8dabb742 42#include "dev-replace.h"
0b86a832 43
2b82032c
YZ
44static int init_first_rw_device(struct btrfs_trans_handle *trans,
45 struct btrfs_root *root,
46 struct btrfs_device *device);
47static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
733f4fbb
SB
48static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
49static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
2b82032c 50
8a4b83cc
CM
51static DEFINE_MUTEX(uuid_mutex);
52static LIST_HEAD(fs_uuids);
53
7d9eb12c
CM
54static void lock_chunks(struct btrfs_root *root)
55{
7d9eb12c
CM
56 mutex_lock(&root->fs_info->chunk_mutex);
57}
58
59static void unlock_chunks(struct btrfs_root *root)
60{
7d9eb12c
CM
61 mutex_unlock(&root->fs_info->chunk_mutex);
62}
63
e4404d6e
YZ
64static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
65{
66 struct btrfs_device *device;
67 WARN_ON(fs_devices->opened);
68 while (!list_empty(&fs_devices->devices)) {
69 device = list_entry(fs_devices->devices.next,
70 struct btrfs_device, dev_list);
71 list_del(&device->dev_list);
606686ee 72 rcu_string_free(device->name);
e4404d6e
YZ
73 kfree(device);
74 }
75 kfree(fs_devices);
76}
77
b8b8ff59
LC
78static void btrfs_kobject_uevent(struct block_device *bdev,
79 enum kobject_action action)
80{
81 int ret;
82
83 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
84 if (ret)
85 pr_warn("Sending event '%d' to kobject: '%s' (%p): failed\n",
86 action,
87 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
88 &disk_to_dev(bdev->bd_disk)->kobj);
89}
90
143bede5 91void btrfs_cleanup_fs_uuids(void)
8a4b83cc
CM
92{
93 struct btrfs_fs_devices *fs_devices;
8a4b83cc 94
2b82032c
YZ
95 while (!list_empty(&fs_uuids)) {
96 fs_devices = list_entry(fs_uuids.next,
97 struct btrfs_fs_devices, list);
98 list_del(&fs_devices->list);
e4404d6e 99 free_fs_devices(fs_devices);
8a4b83cc 100 }
8a4b83cc
CM
101}
102
a1b32a59
CM
103static noinline struct btrfs_device *__find_device(struct list_head *head,
104 u64 devid, u8 *uuid)
8a4b83cc
CM
105{
106 struct btrfs_device *dev;
8a4b83cc 107
c6e30871 108 list_for_each_entry(dev, head, dev_list) {
a443755f 109 if (dev->devid == devid &&
8f18cf13 110 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
8a4b83cc 111 return dev;
a443755f 112 }
8a4b83cc
CM
113 }
114 return NULL;
115}
116
a1b32a59 117static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
8a4b83cc 118{
8a4b83cc
CM
119 struct btrfs_fs_devices *fs_devices;
120
c6e30871 121 list_for_each_entry(fs_devices, &fs_uuids, list) {
8a4b83cc
CM
122 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
123 return fs_devices;
124 }
125 return NULL;
126}
127
beaf8ab3
SB
128static int
129btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
130 int flush, struct block_device **bdev,
131 struct buffer_head **bh)
132{
133 int ret;
134
135 *bdev = blkdev_get_by_path(device_path, flags, holder);
136
137 if (IS_ERR(*bdev)) {
138 ret = PTR_ERR(*bdev);
139 printk(KERN_INFO "btrfs: open %s failed\n", device_path);
140 goto error;
141 }
142
143 if (flush)
144 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
145 ret = set_blocksize(*bdev, 4096);
146 if (ret) {
147 blkdev_put(*bdev, flags);
148 goto error;
149 }
150 invalidate_bdev(*bdev);
151 *bh = btrfs_read_dev_super(*bdev);
152 if (!*bh) {
153 ret = -EINVAL;
154 blkdev_put(*bdev, flags);
155 goto error;
156 }
157
158 return 0;
159
160error:
161 *bdev = NULL;
162 *bh = NULL;
163 return ret;
164}
165
ffbd517d
CM
166static void requeue_list(struct btrfs_pending_bios *pending_bios,
167 struct bio *head, struct bio *tail)
168{
169
170 struct bio *old_head;
171
172 old_head = pending_bios->head;
173 pending_bios->head = head;
174 if (pending_bios->tail)
175 tail->bi_next = old_head;
176 else
177 pending_bios->tail = tail;
178}
179
8b712842
CM
180/*
181 * we try to collect pending bios for a device so we don't get a large
182 * number of procs sending bios down to the same device. This greatly
183 * improves the schedulers ability to collect and merge the bios.
184 *
185 * But, it also turns into a long list of bios to process and that is sure
186 * to eventually make the worker thread block. The solution here is to
187 * make some progress and then put this work struct back at the end of
188 * the list if the block device is congested. This way, multiple devices
189 * can make progress from a single worker thread.
190 */
143bede5 191static noinline void run_scheduled_bios(struct btrfs_device *device)
8b712842
CM
192{
193 struct bio *pending;
194 struct backing_dev_info *bdi;
b64a2851 195 struct btrfs_fs_info *fs_info;
ffbd517d 196 struct btrfs_pending_bios *pending_bios;
8b712842
CM
197 struct bio *tail;
198 struct bio *cur;
199 int again = 0;
ffbd517d 200 unsigned long num_run;
d644d8a1 201 unsigned long batch_run = 0;
b64a2851 202 unsigned long limit;
b765ead5 203 unsigned long last_waited = 0;
d84275c9 204 int force_reg = 0;
0e588859 205 int sync_pending = 0;
211588ad
CM
206 struct blk_plug plug;
207
208 /*
209 * this function runs all the bios we've collected for
210 * a particular device. We don't want to wander off to
211 * another device without first sending all of these down.
212 * So, setup a plug here and finish it off before we return
213 */
214 blk_start_plug(&plug);
8b712842 215
bedf762b 216 bdi = blk_get_backing_dev_info(device->bdev);
b64a2851
CM
217 fs_info = device->dev_root->fs_info;
218 limit = btrfs_async_submit_limit(fs_info);
219 limit = limit * 2 / 3;
220
8b712842
CM
221loop:
222 spin_lock(&device->io_lock);
223
a6837051 224loop_lock:
d84275c9 225 num_run = 0;
ffbd517d 226
8b712842
CM
227 /* take all the bios off the list at once and process them
228 * later on (without the lock held). But, remember the
229 * tail and other pointers so the bios can be properly reinserted
230 * into the list if we hit congestion
231 */
d84275c9 232 if (!force_reg && device->pending_sync_bios.head) {
ffbd517d 233 pending_bios = &device->pending_sync_bios;
d84275c9
CM
234 force_reg = 1;
235 } else {
ffbd517d 236 pending_bios = &device->pending_bios;
d84275c9
CM
237 force_reg = 0;
238 }
ffbd517d
CM
239
240 pending = pending_bios->head;
241 tail = pending_bios->tail;
8b712842 242 WARN_ON(pending && !tail);
8b712842
CM
243
244 /*
245 * if pending was null this time around, no bios need processing
246 * at all and we can stop. Otherwise it'll loop back up again
247 * and do an additional check so no bios are missed.
248 *
249 * device->running_pending is used to synchronize with the
250 * schedule_bio code.
251 */
ffbd517d
CM
252 if (device->pending_sync_bios.head == NULL &&
253 device->pending_bios.head == NULL) {
8b712842
CM
254 again = 0;
255 device->running_pending = 0;
ffbd517d
CM
256 } else {
257 again = 1;
258 device->running_pending = 1;
8b712842 259 }
ffbd517d
CM
260
261 pending_bios->head = NULL;
262 pending_bios->tail = NULL;
263
8b712842
CM
264 spin_unlock(&device->io_lock);
265
d397712b 266 while (pending) {
ffbd517d
CM
267
268 rmb();
d84275c9
CM
269 /* we want to work on both lists, but do more bios on the
270 * sync list than the regular list
271 */
272 if ((num_run > 32 &&
273 pending_bios != &device->pending_sync_bios &&
274 device->pending_sync_bios.head) ||
275 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
276 device->pending_bios.head)) {
ffbd517d
CM
277 spin_lock(&device->io_lock);
278 requeue_list(pending_bios, pending, tail);
279 goto loop_lock;
280 }
281
8b712842
CM
282 cur = pending;
283 pending = pending->bi_next;
284 cur->bi_next = NULL;
b64a2851 285
66657b31 286 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
b64a2851
CM
287 waitqueue_active(&fs_info->async_submit_wait))
288 wake_up(&fs_info->async_submit_wait);
492bb6de
CM
289
290 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
d644d8a1 291
2ab1ba68
CM
292 /*
293 * if we're doing the sync list, record that our
294 * plug has some sync requests on it
295 *
296 * If we're doing the regular list and there are
297 * sync requests sitting around, unplug before
298 * we add more
299 */
300 if (pending_bios == &device->pending_sync_bios) {
301 sync_pending = 1;
302 } else if (sync_pending) {
303 blk_finish_plug(&plug);
304 blk_start_plug(&plug);
305 sync_pending = 0;
306 }
307
21adbd5c 308 btrfsic_submit_bio(cur->bi_rw, cur);
5ff7ba3a
CM
309 num_run++;
310 batch_run++;
7eaceacc 311 if (need_resched())
ffbd517d 312 cond_resched();
8b712842
CM
313
314 /*
315 * we made progress, there is more work to do and the bdi
316 * is now congested. Back off and let other work structs
317 * run instead
318 */
57fd5a5f 319 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
5f2cc086 320 fs_info->fs_devices->open_devices > 1) {
b765ead5 321 struct io_context *ioc;
8b712842 322
b765ead5
CM
323 ioc = current->io_context;
324
325 /*
326 * the main goal here is that we don't want to
327 * block if we're going to be able to submit
328 * more requests without blocking.
329 *
330 * This code does two great things, it pokes into
331 * the elevator code from a filesystem _and_
332 * it makes assumptions about how batching works.
333 */
334 if (ioc && ioc->nr_batch_requests > 0 &&
335 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
336 (last_waited == 0 ||
337 ioc->last_waited == last_waited)) {
338 /*
339 * we want to go through our batch of
340 * requests and stop. So, we copy out
341 * the ioc->last_waited time and test
342 * against it before looping
343 */
344 last_waited = ioc->last_waited;
7eaceacc 345 if (need_resched())
ffbd517d 346 cond_resched();
b765ead5
CM
347 continue;
348 }
8b712842 349 spin_lock(&device->io_lock);
ffbd517d 350 requeue_list(pending_bios, pending, tail);
a6837051 351 device->running_pending = 1;
8b712842
CM
352
353 spin_unlock(&device->io_lock);
354 btrfs_requeue_work(&device->work);
355 goto done;
356 }
d85c8a6f
CM
357 /* unplug every 64 requests just for good measure */
358 if (batch_run % 64 == 0) {
359 blk_finish_plug(&plug);
360 blk_start_plug(&plug);
361 sync_pending = 0;
362 }
8b712842 363 }
ffbd517d 364
51684082
CM
365 cond_resched();
366 if (again)
367 goto loop;
368
369 spin_lock(&device->io_lock);
370 if (device->pending_bios.head || device->pending_sync_bios.head)
371 goto loop_lock;
372 spin_unlock(&device->io_lock);
373
8b712842 374done:
211588ad 375 blk_finish_plug(&plug);
8b712842
CM
376}
377
b2950863 378static void pending_bios_fn(struct btrfs_work *work)
8b712842
CM
379{
380 struct btrfs_device *device;
381
382 device = container_of(work, struct btrfs_device, work);
383 run_scheduled_bios(device);
384}
385
a1b32a59 386static noinline int device_list_add(const char *path,
8a4b83cc
CM
387 struct btrfs_super_block *disk_super,
388 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
389{
390 struct btrfs_device *device;
391 struct btrfs_fs_devices *fs_devices;
606686ee 392 struct rcu_string *name;
8a4b83cc
CM
393 u64 found_transid = btrfs_super_generation(disk_super);
394
395 fs_devices = find_fsid(disk_super->fsid);
396 if (!fs_devices) {
515dc322 397 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
8a4b83cc
CM
398 if (!fs_devices)
399 return -ENOMEM;
400 INIT_LIST_HEAD(&fs_devices->devices);
b3075717 401 INIT_LIST_HEAD(&fs_devices->alloc_list);
8a4b83cc
CM
402 list_add(&fs_devices->list, &fs_uuids);
403 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
404 fs_devices->latest_devid = devid;
405 fs_devices->latest_trans = found_transid;
e5e9a520 406 mutex_init(&fs_devices->device_list_mutex);
8a4b83cc
CM
407 device = NULL;
408 } else {
a443755f
CM
409 device = __find_device(&fs_devices->devices, devid,
410 disk_super->dev_item.uuid);
8a4b83cc
CM
411 }
412 if (!device) {
2b82032c
YZ
413 if (fs_devices->opened)
414 return -EBUSY;
415
8a4b83cc
CM
416 device = kzalloc(sizeof(*device), GFP_NOFS);
417 if (!device) {
418 /* we can safely leave the fs_devices entry around */
419 return -ENOMEM;
420 }
421 device->devid = devid;
733f4fbb 422 device->dev_stats_valid = 0;
8b712842 423 device->work.func = pending_bios_fn;
a443755f
CM
424 memcpy(device->uuid, disk_super->dev_item.uuid,
425 BTRFS_UUID_SIZE);
b248a415 426 spin_lock_init(&device->io_lock);
606686ee
JB
427
428 name = rcu_string_strdup(path, GFP_NOFS);
429 if (!name) {
8a4b83cc
CM
430 kfree(device);
431 return -ENOMEM;
432 }
606686ee 433 rcu_assign_pointer(device->name, name);
2b82032c 434 INIT_LIST_HEAD(&device->dev_alloc_list);
e5e9a520 435
90519d66
AJ
436 /* init readahead state */
437 spin_lock_init(&device->reada_lock);
438 device->reada_curr_zone = NULL;
439 atomic_set(&device->reada_in_flight, 0);
440 device->reada_next = 0;
441 INIT_RADIX_TREE(&device->reada_zones, GFP_NOFS & ~__GFP_WAIT);
442 INIT_RADIX_TREE(&device->reada_extents, GFP_NOFS & ~__GFP_WAIT);
443
e5e9a520 444 mutex_lock(&fs_devices->device_list_mutex);
1f78160c 445 list_add_rcu(&device->dev_list, &fs_devices->devices);
e5e9a520
CM
446 mutex_unlock(&fs_devices->device_list_mutex);
447
2b82032c 448 device->fs_devices = fs_devices;
8a4b83cc 449 fs_devices->num_devices++;
606686ee
JB
450 } else if (!device->name || strcmp(device->name->str, path)) {
451 name = rcu_string_strdup(path, GFP_NOFS);
3a0524dc
TH
452 if (!name)
453 return -ENOMEM;
606686ee
JB
454 rcu_string_free(device->name);
455 rcu_assign_pointer(device->name, name);
cd02dca5
CM
456 if (device->missing) {
457 fs_devices->missing_devices--;
458 device->missing = 0;
459 }
8a4b83cc
CM
460 }
461
462 if (found_transid > fs_devices->latest_trans) {
463 fs_devices->latest_devid = devid;
464 fs_devices->latest_trans = found_transid;
465 }
8a4b83cc
CM
466 *fs_devices_ret = fs_devices;
467 return 0;
468}
469
e4404d6e
YZ
470static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
471{
472 struct btrfs_fs_devices *fs_devices;
473 struct btrfs_device *device;
474 struct btrfs_device *orig_dev;
475
476 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
477 if (!fs_devices)
478 return ERR_PTR(-ENOMEM);
479
480 INIT_LIST_HEAD(&fs_devices->devices);
481 INIT_LIST_HEAD(&fs_devices->alloc_list);
482 INIT_LIST_HEAD(&fs_devices->list);
e5e9a520 483 mutex_init(&fs_devices->device_list_mutex);
e4404d6e
YZ
484 fs_devices->latest_devid = orig->latest_devid;
485 fs_devices->latest_trans = orig->latest_trans;
02db0844 486 fs_devices->total_devices = orig->total_devices;
e4404d6e
YZ
487 memcpy(fs_devices->fsid, orig->fsid, sizeof(fs_devices->fsid));
488
46224705 489 /* We have held the volume lock, it is safe to get the devices. */
e4404d6e 490 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
606686ee
JB
491 struct rcu_string *name;
492
e4404d6e
YZ
493 device = kzalloc(sizeof(*device), GFP_NOFS);
494 if (!device)
495 goto error;
496
606686ee
JB
497 /*
498 * This is ok to do without rcu read locked because we hold the
499 * uuid mutex so nothing we touch in here is going to disappear.
500 */
501 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
502 if (!name) {
fd2696f3 503 kfree(device);
e4404d6e 504 goto error;
fd2696f3 505 }
606686ee 506 rcu_assign_pointer(device->name, name);
e4404d6e
YZ
507
508 device->devid = orig_dev->devid;
509 device->work.func = pending_bios_fn;
510 memcpy(device->uuid, orig_dev->uuid, sizeof(device->uuid));
e4404d6e
YZ
511 spin_lock_init(&device->io_lock);
512 INIT_LIST_HEAD(&device->dev_list);
513 INIT_LIST_HEAD(&device->dev_alloc_list);
514
515 list_add(&device->dev_list, &fs_devices->devices);
516 device->fs_devices = fs_devices;
517 fs_devices->num_devices++;
518 }
519 return fs_devices;
520error:
521 free_fs_devices(fs_devices);
522 return ERR_PTR(-ENOMEM);
523}
524
8dabb742
SB
525void btrfs_close_extra_devices(struct btrfs_fs_info *fs_info,
526 struct btrfs_fs_devices *fs_devices, int step)
dfe25020 527{
c6e30871 528 struct btrfs_device *device, *next;
dfe25020 529
a6b0d5c8
CM
530 struct block_device *latest_bdev = NULL;
531 u64 latest_devid = 0;
532 u64 latest_transid = 0;
533
dfe25020
CM
534 mutex_lock(&uuid_mutex);
535again:
46224705 536 /* This is the initialized path, it is safe to release the devices. */
c6e30871 537 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
a6b0d5c8 538 if (device->in_fs_metadata) {
63a212ab
SB
539 if (!device->is_tgtdev_for_dev_replace &&
540 (!latest_transid ||
541 device->generation > latest_transid)) {
a6b0d5c8
CM
542 latest_devid = device->devid;
543 latest_transid = device->generation;
544 latest_bdev = device->bdev;
545 }
2b82032c 546 continue;
a6b0d5c8 547 }
2b82032c 548
8dabb742
SB
549 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
550 /*
551 * In the first step, keep the device which has
552 * the correct fsid and the devid that is used
553 * for the dev_replace procedure.
554 * In the second step, the dev_replace state is
555 * read from the device tree and it is known
556 * whether the procedure is really active or
557 * not, which means whether this device is
558 * used or whether it should be removed.
559 */
560 if (step == 0 || device->is_tgtdev_for_dev_replace) {
561 continue;
562 }
563 }
2b82032c 564 if (device->bdev) {
d4d77629 565 blkdev_put(device->bdev, device->mode);
2b82032c
YZ
566 device->bdev = NULL;
567 fs_devices->open_devices--;
568 }
569 if (device->writeable) {
570 list_del_init(&device->dev_alloc_list);
571 device->writeable = 0;
8dabb742
SB
572 if (!device->is_tgtdev_for_dev_replace)
573 fs_devices->rw_devices--;
2b82032c 574 }
e4404d6e
YZ
575 list_del_init(&device->dev_list);
576 fs_devices->num_devices--;
606686ee 577 rcu_string_free(device->name);
e4404d6e 578 kfree(device);
dfe25020 579 }
2b82032c
YZ
580
581 if (fs_devices->seed) {
582 fs_devices = fs_devices->seed;
2b82032c
YZ
583 goto again;
584 }
585
a6b0d5c8
CM
586 fs_devices->latest_bdev = latest_bdev;
587 fs_devices->latest_devid = latest_devid;
588 fs_devices->latest_trans = latest_transid;
589
dfe25020 590 mutex_unlock(&uuid_mutex);
dfe25020 591}
a0af469b 592
1f78160c
XG
593static void __free_device(struct work_struct *work)
594{
595 struct btrfs_device *device;
596
597 device = container_of(work, struct btrfs_device, rcu_work);
598
599 if (device->bdev)
600 blkdev_put(device->bdev, device->mode);
601
606686ee 602 rcu_string_free(device->name);
1f78160c
XG
603 kfree(device);
604}
605
606static void free_device(struct rcu_head *head)
607{
608 struct btrfs_device *device;
609
610 device = container_of(head, struct btrfs_device, rcu);
611
612 INIT_WORK(&device->rcu_work, __free_device);
613 schedule_work(&device->rcu_work);
614}
615
2b82032c 616static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
8a4b83cc 617{
8a4b83cc 618 struct btrfs_device *device;
e4404d6e 619
2b82032c
YZ
620 if (--fs_devices->opened > 0)
621 return 0;
8a4b83cc 622
c9513edb 623 mutex_lock(&fs_devices->device_list_mutex);
c6e30871 624 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1f78160c 625 struct btrfs_device *new_device;
606686ee 626 struct rcu_string *name;
1f78160c
XG
627
628 if (device->bdev)
a0af469b 629 fs_devices->open_devices--;
1f78160c 630
8dabb742 631 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
2b82032c
YZ
632 list_del_init(&device->dev_alloc_list);
633 fs_devices->rw_devices--;
634 }
635
d5e2003c
JB
636 if (device->can_discard)
637 fs_devices->num_can_discard--;
638
1f78160c 639 new_device = kmalloc(sizeof(*new_device), GFP_NOFS);
79787eaa 640 BUG_ON(!new_device); /* -ENOMEM */
1f78160c 641 memcpy(new_device, device, sizeof(*new_device));
606686ee
JB
642
643 /* Safe because we are under uuid_mutex */
99f5944b
JB
644 if (device->name) {
645 name = rcu_string_strdup(device->name->str, GFP_NOFS);
646 BUG_ON(device->name && !name); /* -ENOMEM */
647 rcu_assign_pointer(new_device->name, name);
648 }
1f78160c
XG
649 new_device->bdev = NULL;
650 new_device->writeable = 0;
651 new_device->in_fs_metadata = 0;
d5e2003c 652 new_device->can_discard = 0;
1f78160c
XG
653 list_replace_rcu(&device->dev_list, &new_device->dev_list);
654
655 call_rcu(&device->rcu, free_device);
8a4b83cc 656 }
c9513edb
XG
657 mutex_unlock(&fs_devices->device_list_mutex);
658
e4404d6e
YZ
659 WARN_ON(fs_devices->open_devices);
660 WARN_ON(fs_devices->rw_devices);
2b82032c
YZ
661 fs_devices->opened = 0;
662 fs_devices->seeding = 0;
2b82032c 663
8a4b83cc
CM
664 return 0;
665}
666
2b82032c
YZ
667int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
668{
e4404d6e 669 struct btrfs_fs_devices *seed_devices = NULL;
2b82032c
YZ
670 int ret;
671
672 mutex_lock(&uuid_mutex);
673 ret = __btrfs_close_devices(fs_devices);
e4404d6e
YZ
674 if (!fs_devices->opened) {
675 seed_devices = fs_devices->seed;
676 fs_devices->seed = NULL;
677 }
2b82032c 678 mutex_unlock(&uuid_mutex);
e4404d6e
YZ
679
680 while (seed_devices) {
681 fs_devices = seed_devices;
682 seed_devices = fs_devices->seed;
683 __btrfs_close_devices(fs_devices);
684 free_fs_devices(fs_devices);
685 }
2b82032c
YZ
686 return ret;
687}
688
e4404d6e
YZ
689static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
690 fmode_t flags, void *holder)
8a4b83cc 691{
d5e2003c 692 struct request_queue *q;
8a4b83cc
CM
693 struct block_device *bdev;
694 struct list_head *head = &fs_devices->devices;
8a4b83cc 695 struct btrfs_device *device;
a0af469b
CM
696 struct block_device *latest_bdev = NULL;
697 struct buffer_head *bh;
698 struct btrfs_super_block *disk_super;
699 u64 latest_devid = 0;
700 u64 latest_transid = 0;
a0af469b 701 u64 devid;
2b82032c 702 int seeding = 1;
a0af469b 703 int ret = 0;
8a4b83cc 704
d4d77629
TH
705 flags |= FMODE_EXCL;
706
c6e30871 707 list_for_each_entry(device, head, dev_list) {
c1c4d91c
CM
708 if (device->bdev)
709 continue;
dfe25020
CM
710 if (!device->name)
711 continue;
712
beaf8ab3
SB
713 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
714 &bdev, &bh);
715 if (ret)
716 continue;
a0af469b
CM
717
718 disk_super = (struct btrfs_super_block *)bh->b_data;
a343832f 719 devid = btrfs_stack_device_id(&disk_super->dev_item);
a0af469b
CM
720 if (devid != device->devid)
721 goto error_brelse;
722
2b82032c
YZ
723 if (memcmp(device->uuid, disk_super->dev_item.uuid,
724 BTRFS_UUID_SIZE))
725 goto error_brelse;
726
727 device->generation = btrfs_super_generation(disk_super);
728 if (!latest_transid || device->generation > latest_transid) {
a0af469b 729 latest_devid = devid;
2b82032c 730 latest_transid = device->generation;
a0af469b
CM
731 latest_bdev = bdev;
732 }
733
2b82032c
YZ
734 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
735 device->writeable = 0;
736 } else {
737 device->writeable = !bdev_read_only(bdev);
738 seeding = 0;
739 }
740
d5e2003c
JB
741 q = bdev_get_queue(bdev);
742 if (blk_queue_discard(q)) {
743 device->can_discard = 1;
744 fs_devices->num_can_discard++;
745 }
746
8a4b83cc 747 device->bdev = bdev;
dfe25020 748 device->in_fs_metadata = 0;
15916de8
CM
749 device->mode = flags;
750
c289811c
CM
751 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
752 fs_devices->rotating = 1;
753
a0af469b 754 fs_devices->open_devices++;
8dabb742 755 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
2b82032c
YZ
756 fs_devices->rw_devices++;
757 list_add(&device->dev_alloc_list,
758 &fs_devices->alloc_list);
759 }
4f6c9328 760 brelse(bh);
a0af469b 761 continue;
a061fc8d 762
a0af469b
CM
763error_brelse:
764 brelse(bh);
d4d77629 765 blkdev_put(bdev, flags);
a0af469b 766 continue;
8a4b83cc 767 }
a0af469b 768 if (fs_devices->open_devices == 0) {
20bcd649 769 ret = -EINVAL;
a0af469b
CM
770 goto out;
771 }
2b82032c
YZ
772 fs_devices->seeding = seeding;
773 fs_devices->opened = 1;
a0af469b
CM
774 fs_devices->latest_bdev = latest_bdev;
775 fs_devices->latest_devid = latest_devid;
776 fs_devices->latest_trans = latest_transid;
2b82032c 777 fs_devices->total_rw_bytes = 0;
a0af469b 778out:
2b82032c
YZ
779 return ret;
780}
781
782int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
97288f2c 783 fmode_t flags, void *holder)
2b82032c
YZ
784{
785 int ret;
786
787 mutex_lock(&uuid_mutex);
788 if (fs_devices->opened) {
e4404d6e
YZ
789 fs_devices->opened++;
790 ret = 0;
2b82032c 791 } else {
15916de8 792 ret = __btrfs_open_devices(fs_devices, flags, holder);
2b82032c 793 }
8a4b83cc 794 mutex_unlock(&uuid_mutex);
8a4b83cc
CM
795 return ret;
796}
797
97288f2c 798int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
8a4b83cc
CM
799 struct btrfs_fs_devices **fs_devices_ret)
800{
801 struct btrfs_super_block *disk_super;
802 struct block_device *bdev;
803 struct buffer_head *bh;
804 int ret;
805 u64 devid;
f2984462 806 u64 transid;
02db0844 807 u64 total_devices;
8a4b83cc 808
d4d77629 809 flags |= FMODE_EXCL;
10f6327b 810 mutex_lock(&uuid_mutex);
beaf8ab3 811 ret = btrfs_get_bdev_and_sb(path, flags, holder, 0, &bdev, &bh);
8a4b83cc 812 if (ret)
beaf8ab3 813 goto error;
8a4b83cc 814 disk_super = (struct btrfs_super_block *)bh->b_data;
a343832f 815 devid = btrfs_stack_device_id(&disk_super->dev_item);
f2984462 816 transid = btrfs_super_generation(disk_super);
02db0844 817 total_devices = btrfs_super_num_devices(disk_super);
d03f918a
SB
818 if (disk_super->label[0]) {
819 if (disk_super->label[BTRFS_LABEL_SIZE - 1])
820 disk_super->label[BTRFS_LABEL_SIZE - 1] = '\0';
d397712b 821 printk(KERN_INFO "device label %s ", disk_super->label);
d03f918a 822 } else {
22b63a29 823 printk(KERN_INFO "device fsid %pU ", disk_super->fsid);
d03f918a 824 }
119e10cf 825 printk(KERN_CONT "devid %llu transid %llu %s\n",
d397712b 826 (unsigned long long)devid, (unsigned long long)transid, path);
8a4b83cc 827 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
02db0844
JB
828 if (!ret && fs_devices_ret)
829 (*fs_devices_ret)->total_devices = total_devices;
8a4b83cc 830 brelse(bh);
d4d77629 831 blkdev_put(bdev, flags);
8a4b83cc 832error:
beaf8ab3 833 mutex_unlock(&uuid_mutex);
8a4b83cc
CM
834 return ret;
835}
0b86a832 836
6d07bcec
MX
837/* helper to account the used device space in the range */
838int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
839 u64 end, u64 *length)
840{
841 struct btrfs_key key;
842 struct btrfs_root *root = device->dev_root;
843 struct btrfs_dev_extent *dev_extent;
844 struct btrfs_path *path;
845 u64 extent_end;
846 int ret;
847 int slot;
848 struct extent_buffer *l;
849
850 *length = 0;
851
63a212ab 852 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
6d07bcec
MX
853 return 0;
854
855 path = btrfs_alloc_path();
856 if (!path)
857 return -ENOMEM;
858 path->reada = 2;
859
860 key.objectid = device->devid;
861 key.offset = start;
862 key.type = BTRFS_DEV_EXTENT_KEY;
863
864 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
865 if (ret < 0)
866 goto out;
867 if (ret > 0) {
868 ret = btrfs_previous_item(root, path, key.objectid, key.type);
869 if (ret < 0)
870 goto out;
871 }
872
873 while (1) {
874 l = path->nodes[0];
875 slot = path->slots[0];
876 if (slot >= btrfs_header_nritems(l)) {
877 ret = btrfs_next_leaf(root, path);
878 if (ret == 0)
879 continue;
880 if (ret < 0)
881 goto out;
882
883 break;
884 }
885 btrfs_item_key_to_cpu(l, &key, slot);
886
887 if (key.objectid < device->devid)
888 goto next;
889
890 if (key.objectid > device->devid)
891 break;
892
893 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
894 goto next;
895
896 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
897 extent_end = key.offset + btrfs_dev_extent_length(l,
898 dev_extent);
899 if (key.offset <= start && extent_end > end) {
900 *length = end - start + 1;
901 break;
902 } else if (key.offset <= start && extent_end > start)
903 *length += extent_end - start;
904 else if (key.offset > start && extent_end <= end)
905 *length += extent_end - key.offset;
906 else if (key.offset > start && key.offset <= end) {
907 *length += end - key.offset + 1;
908 break;
909 } else if (key.offset > end)
910 break;
911
912next:
913 path->slots[0]++;
914 }
915 ret = 0;
916out:
917 btrfs_free_path(path);
918 return ret;
919}
920
0b86a832 921/*
7bfc837d 922 * find_free_dev_extent - find free space in the specified device
7bfc837d
MX
923 * @device: the device which we search the free space in
924 * @num_bytes: the size of the free space that we need
925 * @start: store the start of the free space.
926 * @len: the size of the free space. that we find, or the size of the max
927 * free space if we don't find suitable free space
928 *
0b86a832
CM
929 * this uses a pretty simple search, the expectation is that it is
930 * called very infrequently and that a given device has a small number
931 * of extents
7bfc837d
MX
932 *
933 * @start is used to store the start of the free space if we find. But if we
934 * don't find suitable free space, it will be used to store the start position
935 * of the max free space.
936 *
937 * @len is used to store the size of the free space that we find.
938 * But if we don't find suitable free space, it is used to store the size of
939 * the max free space.
0b86a832 940 */
125ccb0a 941int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
7bfc837d 942 u64 *start, u64 *len)
0b86a832
CM
943{
944 struct btrfs_key key;
945 struct btrfs_root *root = device->dev_root;
7bfc837d 946 struct btrfs_dev_extent *dev_extent;
2b82032c 947 struct btrfs_path *path;
7bfc837d
MX
948 u64 hole_size;
949 u64 max_hole_start;
950 u64 max_hole_size;
951 u64 extent_end;
952 u64 search_start;
0b86a832
CM
953 u64 search_end = device->total_bytes;
954 int ret;
7bfc837d 955 int slot;
0b86a832
CM
956 struct extent_buffer *l;
957
0b86a832
CM
958 /* FIXME use last free of some kind */
959
8a4b83cc
CM
960 /* we don't want to overwrite the superblock on the drive,
961 * so we make sure to start at an offset of at least 1MB
962 */
a9c9bf68 963 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
8f18cf13 964
7bfc837d
MX
965 max_hole_start = search_start;
966 max_hole_size = 0;
38c01b96 967 hole_size = 0;
7bfc837d 968
63a212ab 969 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
7bfc837d
MX
970 ret = -ENOSPC;
971 goto error;
972 }
973
974 path = btrfs_alloc_path();
975 if (!path) {
976 ret = -ENOMEM;
977 goto error;
978 }
979 path->reada = 2;
980
0b86a832
CM
981 key.objectid = device->devid;
982 key.offset = search_start;
983 key.type = BTRFS_DEV_EXTENT_KEY;
7bfc837d 984
125ccb0a 985 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
0b86a832 986 if (ret < 0)
7bfc837d 987 goto out;
1fcbac58
YZ
988 if (ret > 0) {
989 ret = btrfs_previous_item(root, path, key.objectid, key.type);
990 if (ret < 0)
7bfc837d 991 goto out;
1fcbac58 992 }
7bfc837d 993
0b86a832
CM
994 while (1) {
995 l = path->nodes[0];
996 slot = path->slots[0];
997 if (slot >= btrfs_header_nritems(l)) {
998 ret = btrfs_next_leaf(root, path);
999 if (ret == 0)
1000 continue;
1001 if (ret < 0)
7bfc837d
MX
1002 goto out;
1003
1004 break;
0b86a832
CM
1005 }
1006 btrfs_item_key_to_cpu(l, &key, slot);
1007
1008 if (key.objectid < device->devid)
1009 goto next;
1010
1011 if (key.objectid > device->devid)
7bfc837d 1012 break;
0b86a832 1013
7bfc837d
MX
1014 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
1015 goto next;
9779b72f 1016
7bfc837d
MX
1017 if (key.offset > search_start) {
1018 hole_size = key.offset - search_start;
9779b72f 1019
7bfc837d
MX
1020 if (hole_size > max_hole_size) {
1021 max_hole_start = search_start;
1022 max_hole_size = hole_size;
1023 }
9779b72f 1024
7bfc837d
MX
1025 /*
1026 * If this free space is greater than which we need,
1027 * it must be the max free space that we have found
1028 * until now, so max_hole_start must point to the start
1029 * of this free space and the length of this free space
1030 * is stored in max_hole_size. Thus, we return
1031 * max_hole_start and max_hole_size and go back to the
1032 * caller.
1033 */
1034 if (hole_size >= num_bytes) {
1035 ret = 0;
1036 goto out;
0b86a832
CM
1037 }
1038 }
0b86a832 1039
0b86a832 1040 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
7bfc837d
MX
1041 extent_end = key.offset + btrfs_dev_extent_length(l,
1042 dev_extent);
1043 if (extent_end > search_start)
1044 search_start = extent_end;
0b86a832
CM
1045next:
1046 path->slots[0]++;
1047 cond_resched();
1048 }
0b86a832 1049
38c01b96 1050 /*
1051 * At this point, search_start should be the end of
1052 * allocated dev extents, and when shrinking the device,
1053 * search_end may be smaller than search_start.
1054 */
1055 if (search_end > search_start)
1056 hole_size = search_end - search_start;
1057
7bfc837d
MX
1058 if (hole_size > max_hole_size) {
1059 max_hole_start = search_start;
1060 max_hole_size = hole_size;
0b86a832 1061 }
0b86a832 1062
7bfc837d
MX
1063 /* See above. */
1064 if (hole_size < num_bytes)
1065 ret = -ENOSPC;
1066 else
1067 ret = 0;
1068
1069out:
2b82032c 1070 btrfs_free_path(path);
7bfc837d
MX
1071error:
1072 *start = max_hole_start;
b2117a39 1073 if (len)
7bfc837d 1074 *len = max_hole_size;
0b86a832
CM
1075 return ret;
1076}
1077
b2950863 1078static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
8f18cf13
CM
1079 struct btrfs_device *device,
1080 u64 start)
1081{
1082 int ret;
1083 struct btrfs_path *path;
1084 struct btrfs_root *root = device->dev_root;
1085 struct btrfs_key key;
a061fc8d
CM
1086 struct btrfs_key found_key;
1087 struct extent_buffer *leaf = NULL;
1088 struct btrfs_dev_extent *extent = NULL;
8f18cf13
CM
1089
1090 path = btrfs_alloc_path();
1091 if (!path)
1092 return -ENOMEM;
1093
1094 key.objectid = device->devid;
1095 key.offset = start;
1096 key.type = BTRFS_DEV_EXTENT_KEY;
924cd8fb 1097again:
8f18cf13 1098 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
a061fc8d
CM
1099 if (ret > 0) {
1100 ret = btrfs_previous_item(root, path, key.objectid,
1101 BTRFS_DEV_EXTENT_KEY);
b0b802d7
TI
1102 if (ret)
1103 goto out;
a061fc8d
CM
1104 leaf = path->nodes[0];
1105 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1106 extent = btrfs_item_ptr(leaf, path->slots[0],
1107 struct btrfs_dev_extent);
1108 BUG_ON(found_key.offset > start || found_key.offset +
1109 btrfs_dev_extent_length(leaf, extent) < start);
924cd8fb
MX
1110 key = found_key;
1111 btrfs_release_path(path);
1112 goto again;
a061fc8d
CM
1113 } else if (ret == 0) {
1114 leaf = path->nodes[0];
1115 extent = btrfs_item_ptr(leaf, path->slots[0],
1116 struct btrfs_dev_extent);
79787eaa
JM
1117 } else {
1118 btrfs_error(root->fs_info, ret, "Slot search failed");
1119 goto out;
a061fc8d 1120 }
8f18cf13 1121
2bf64758
JB
1122 if (device->bytes_used > 0) {
1123 u64 len = btrfs_dev_extent_length(leaf, extent);
1124 device->bytes_used -= len;
1125 spin_lock(&root->fs_info->free_chunk_lock);
1126 root->fs_info->free_chunk_space += len;
1127 spin_unlock(&root->fs_info->free_chunk_lock);
1128 }
8f18cf13 1129 ret = btrfs_del_item(trans, root, path);
79787eaa
JM
1130 if (ret) {
1131 btrfs_error(root->fs_info, ret,
1132 "Failed to remove dev extent item");
1133 }
b0b802d7 1134out:
8f18cf13
CM
1135 btrfs_free_path(path);
1136 return ret;
1137}
1138
2b82032c 1139int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
0b86a832 1140 struct btrfs_device *device,
e17cade2 1141 u64 chunk_tree, u64 chunk_objectid,
2b82032c 1142 u64 chunk_offset, u64 start, u64 num_bytes)
0b86a832
CM
1143{
1144 int ret;
1145 struct btrfs_path *path;
1146 struct btrfs_root *root = device->dev_root;
1147 struct btrfs_dev_extent *extent;
1148 struct extent_buffer *leaf;
1149 struct btrfs_key key;
1150
dfe25020 1151 WARN_ON(!device->in_fs_metadata);
63a212ab 1152 WARN_ON(device->is_tgtdev_for_dev_replace);
0b86a832
CM
1153 path = btrfs_alloc_path();
1154 if (!path)
1155 return -ENOMEM;
1156
0b86a832 1157 key.objectid = device->devid;
2b82032c 1158 key.offset = start;
0b86a832
CM
1159 key.type = BTRFS_DEV_EXTENT_KEY;
1160 ret = btrfs_insert_empty_item(trans, root, path, &key,
1161 sizeof(*extent));
2cdcecbc
MF
1162 if (ret)
1163 goto out;
0b86a832
CM
1164
1165 leaf = path->nodes[0];
1166 extent = btrfs_item_ptr(leaf, path->slots[0],
1167 struct btrfs_dev_extent);
e17cade2
CM
1168 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1169 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1170 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1171
1172 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1173 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
1174 BTRFS_UUID_SIZE);
1175
0b86a832
CM
1176 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1177 btrfs_mark_buffer_dirty(leaf);
2cdcecbc 1178out:
0b86a832
CM
1179 btrfs_free_path(path);
1180 return ret;
1181}
1182
a1b32a59
CM
1183static noinline int find_next_chunk(struct btrfs_root *root,
1184 u64 objectid, u64 *offset)
0b86a832
CM
1185{
1186 struct btrfs_path *path;
1187 int ret;
1188 struct btrfs_key key;
e17cade2 1189 struct btrfs_chunk *chunk;
0b86a832
CM
1190 struct btrfs_key found_key;
1191
1192 path = btrfs_alloc_path();
92b8e897
MF
1193 if (!path)
1194 return -ENOMEM;
0b86a832 1195
e17cade2 1196 key.objectid = objectid;
0b86a832
CM
1197 key.offset = (u64)-1;
1198 key.type = BTRFS_CHUNK_ITEM_KEY;
1199
1200 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1201 if (ret < 0)
1202 goto error;
1203
79787eaa 1204 BUG_ON(ret == 0); /* Corruption */
0b86a832
CM
1205
1206 ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
1207 if (ret) {
e17cade2 1208 *offset = 0;
0b86a832
CM
1209 } else {
1210 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1211 path->slots[0]);
e17cade2
CM
1212 if (found_key.objectid != objectid)
1213 *offset = 0;
1214 else {
1215 chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
1216 struct btrfs_chunk);
1217 *offset = found_key.offset +
1218 btrfs_chunk_length(path->nodes[0], chunk);
1219 }
0b86a832
CM
1220 }
1221 ret = 0;
1222error:
1223 btrfs_free_path(path);
1224 return ret;
1225}
1226
2b82032c 1227static noinline int find_next_devid(struct btrfs_root *root, u64 *objectid)
0b86a832
CM
1228{
1229 int ret;
1230 struct btrfs_key key;
1231 struct btrfs_key found_key;
2b82032c
YZ
1232 struct btrfs_path *path;
1233
1234 root = root->fs_info->chunk_root;
1235
1236 path = btrfs_alloc_path();
1237 if (!path)
1238 return -ENOMEM;
0b86a832
CM
1239
1240 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1241 key.type = BTRFS_DEV_ITEM_KEY;
1242 key.offset = (u64)-1;
1243
1244 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1245 if (ret < 0)
1246 goto error;
1247
79787eaa 1248 BUG_ON(ret == 0); /* Corruption */
0b86a832
CM
1249
1250 ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
1251 BTRFS_DEV_ITEM_KEY);
1252 if (ret) {
1253 *objectid = 1;
1254 } else {
1255 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1256 path->slots[0]);
1257 *objectid = found_key.offset + 1;
1258 }
1259 ret = 0;
1260error:
2b82032c 1261 btrfs_free_path(path);
0b86a832
CM
1262 return ret;
1263}
1264
1265/*
1266 * the device information is stored in the chunk root
1267 * the btrfs_device struct should be fully filled in
1268 */
1269int btrfs_add_device(struct btrfs_trans_handle *trans,
1270 struct btrfs_root *root,
1271 struct btrfs_device *device)
1272{
1273 int ret;
1274 struct btrfs_path *path;
1275 struct btrfs_dev_item *dev_item;
1276 struct extent_buffer *leaf;
1277 struct btrfs_key key;
1278 unsigned long ptr;
0b86a832
CM
1279
1280 root = root->fs_info->chunk_root;
1281
1282 path = btrfs_alloc_path();
1283 if (!path)
1284 return -ENOMEM;
1285
0b86a832
CM
1286 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1287 key.type = BTRFS_DEV_ITEM_KEY;
2b82032c 1288 key.offset = device->devid;
0b86a832
CM
1289
1290 ret = btrfs_insert_empty_item(trans, root, path, &key,
0d81ba5d 1291 sizeof(*dev_item));
0b86a832
CM
1292 if (ret)
1293 goto out;
1294
1295 leaf = path->nodes[0];
1296 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1297
1298 btrfs_set_device_id(leaf, dev_item, device->devid);
2b82032c 1299 btrfs_set_device_generation(leaf, dev_item, 0);
0b86a832
CM
1300 btrfs_set_device_type(leaf, dev_item, device->type);
1301 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1302 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1303 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
0b86a832
CM
1304 btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1305 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
e17cade2
CM
1306 btrfs_set_device_group(leaf, dev_item, 0);
1307 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1308 btrfs_set_device_bandwidth(leaf, dev_item, 0);
c3027eb5 1309 btrfs_set_device_start_offset(leaf, dev_item, 0);
0b86a832 1310
0b86a832 1311 ptr = (unsigned long)btrfs_device_uuid(dev_item);
e17cade2 1312 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
2b82032c
YZ
1313 ptr = (unsigned long)btrfs_device_fsid(dev_item);
1314 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
0b86a832 1315 btrfs_mark_buffer_dirty(leaf);
0b86a832 1316
2b82032c 1317 ret = 0;
0b86a832
CM
1318out:
1319 btrfs_free_path(path);
1320 return ret;
1321}
8f18cf13 1322
a061fc8d
CM
1323static int btrfs_rm_dev_item(struct btrfs_root *root,
1324 struct btrfs_device *device)
1325{
1326 int ret;
1327 struct btrfs_path *path;
a061fc8d 1328 struct btrfs_key key;
a061fc8d
CM
1329 struct btrfs_trans_handle *trans;
1330
1331 root = root->fs_info->chunk_root;
1332
1333 path = btrfs_alloc_path();
1334 if (!path)
1335 return -ENOMEM;
1336
a22285a6 1337 trans = btrfs_start_transaction(root, 0);
98d5dc13
TI
1338 if (IS_ERR(trans)) {
1339 btrfs_free_path(path);
1340 return PTR_ERR(trans);
1341 }
a061fc8d
CM
1342 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1343 key.type = BTRFS_DEV_ITEM_KEY;
1344 key.offset = device->devid;
7d9eb12c 1345 lock_chunks(root);
a061fc8d
CM
1346
1347 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1348 if (ret < 0)
1349 goto out;
1350
1351 if (ret > 0) {
1352 ret = -ENOENT;
1353 goto out;
1354 }
1355
1356 ret = btrfs_del_item(trans, root, path);
1357 if (ret)
1358 goto out;
a061fc8d
CM
1359out:
1360 btrfs_free_path(path);
7d9eb12c 1361 unlock_chunks(root);
a061fc8d
CM
1362 btrfs_commit_transaction(trans, root);
1363 return ret;
1364}
1365
1366int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1367{
1368 struct btrfs_device *device;
2b82032c 1369 struct btrfs_device *next_device;
a061fc8d 1370 struct block_device *bdev;
dfe25020 1371 struct buffer_head *bh = NULL;
a061fc8d 1372 struct btrfs_super_block *disk_super;
1f78160c 1373 struct btrfs_fs_devices *cur_devices;
a061fc8d
CM
1374 u64 all_avail;
1375 u64 devid;
2b82032c
YZ
1376 u64 num_devices;
1377 u8 *dev_uuid;
a061fc8d 1378 int ret = 0;
1f78160c 1379 bool clear_super = false;
a061fc8d 1380
a061fc8d
CM
1381 mutex_lock(&uuid_mutex);
1382
1383 all_avail = root->fs_info->avail_data_alloc_bits |
1384 root->fs_info->avail_system_alloc_bits |
1385 root->fs_info->avail_metadata_alloc_bits;
1386
8dabb742
SB
1387 num_devices = root->fs_info->fs_devices->num_devices;
1388 btrfs_dev_replace_lock(&root->fs_info->dev_replace);
1389 if (btrfs_dev_replace_is_ongoing(&root->fs_info->dev_replace)) {
1390 WARN_ON(num_devices < 1);
1391 num_devices--;
1392 }
1393 btrfs_dev_replace_unlock(&root->fs_info->dev_replace);
1394
1395 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
d397712b
CM
1396 printk(KERN_ERR "btrfs: unable to go below four devices "
1397 "on raid10\n");
a061fc8d
CM
1398 ret = -EINVAL;
1399 goto out;
1400 }
1401
8dabb742 1402 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
d397712b
CM
1403 printk(KERN_ERR "btrfs: unable to go below two "
1404 "devices on raid1\n");
a061fc8d
CM
1405 ret = -EINVAL;
1406 goto out;
1407 }
1408
53b381b3
DW
1409 if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1410 root->fs_info->fs_devices->rw_devices <= 2) {
1411 printk(KERN_ERR "btrfs: unable to go below two "
1412 "devices on raid5\n");
1413 ret = -EINVAL;
1414 goto out;
1415 }
1416 if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1417 root->fs_info->fs_devices->rw_devices <= 3) {
1418 printk(KERN_ERR "btrfs: unable to go below three "
1419 "devices on raid6\n");
1420 ret = -EINVAL;
1421 goto out;
1422 }
1423
dfe25020 1424 if (strcmp(device_path, "missing") == 0) {
dfe25020
CM
1425 struct list_head *devices;
1426 struct btrfs_device *tmp;
a061fc8d 1427
dfe25020
CM
1428 device = NULL;
1429 devices = &root->fs_info->fs_devices->devices;
46224705
XG
1430 /*
1431 * It is safe to read the devices since the volume_mutex
1432 * is held.
1433 */
c6e30871 1434 list_for_each_entry(tmp, devices, dev_list) {
63a212ab
SB
1435 if (tmp->in_fs_metadata &&
1436 !tmp->is_tgtdev_for_dev_replace &&
1437 !tmp->bdev) {
dfe25020
CM
1438 device = tmp;
1439 break;
1440 }
1441 }
1442 bdev = NULL;
1443 bh = NULL;
1444 disk_super = NULL;
1445 if (!device) {
d397712b
CM
1446 printk(KERN_ERR "btrfs: no missing devices found to "
1447 "remove\n");
dfe25020
CM
1448 goto out;
1449 }
dfe25020 1450 } else {
beaf8ab3 1451 ret = btrfs_get_bdev_and_sb(device_path,
cc975eb4 1452 FMODE_WRITE | FMODE_EXCL,
beaf8ab3
SB
1453 root->fs_info->bdev_holder, 0,
1454 &bdev, &bh);
1455 if (ret)
dfe25020 1456 goto out;
dfe25020 1457 disk_super = (struct btrfs_super_block *)bh->b_data;
a343832f 1458 devid = btrfs_stack_device_id(&disk_super->dev_item);
2b82032c 1459 dev_uuid = disk_super->dev_item.uuid;
aa1b8cd4 1460 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2b82032c 1461 disk_super->fsid);
dfe25020
CM
1462 if (!device) {
1463 ret = -ENOENT;
1464 goto error_brelse;
1465 }
2b82032c 1466 }
dfe25020 1467
63a212ab
SB
1468 if (device->is_tgtdev_for_dev_replace) {
1469 pr_err("btrfs: unable to remove the dev_replace target dev\n");
1470 ret = -EINVAL;
1471 goto error_brelse;
1472 }
1473
2b82032c 1474 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
d397712b
CM
1475 printk(KERN_ERR "btrfs: unable to remove the only writeable "
1476 "device\n");
2b82032c
YZ
1477 ret = -EINVAL;
1478 goto error_brelse;
1479 }
1480
1481 if (device->writeable) {
0c1daee0 1482 lock_chunks(root);
2b82032c 1483 list_del_init(&device->dev_alloc_list);
0c1daee0 1484 unlock_chunks(root);
2b82032c 1485 root->fs_info->fs_devices->rw_devices--;
1f78160c 1486 clear_super = true;
dfe25020 1487 }
a061fc8d
CM
1488
1489 ret = btrfs_shrink_device(device, 0);
1490 if (ret)
9b3517e9 1491 goto error_undo;
a061fc8d 1492
63a212ab
SB
1493 /*
1494 * TODO: the superblock still includes this device in its num_devices
1495 * counter although write_all_supers() is not locked out. This
1496 * could give a filesystem state which requires a degraded mount.
1497 */
a061fc8d
CM
1498 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1499 if (ret)
9b3517e9 1500 goto error_undo;
a061fc8d 1501
2bf64758
JB
1502 spin_lock(&root->fs_info->free_chunk_lock);
1503 root->fs_info->free_chunk_space = device->total_bytes -
1504 device->bytes_used;
1505 spin_unlock(&root->fs_info->free_chunk_lock);
1506
2b82032c 1507 device->in_fs_metadata = 0;
aa1b8cd4 1508 btrfs_scrub_cancel_dev(root->fs_info, device);
e5e9a520
CM
1509
1510 /*
1511 * the device list mutex makes sure that we don't change
1512 * the device list while someone else is writing out all
1513 * the device supers.
1514 */
1f78160c
XG
1515
1516 cur_devices = device->fs_devices;
e5e9a520 1517 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1f78160c 1518 list_del_rcu(&device->dev_list);
e5e9a520 1519
e4404d6e 1520 device->fs_devices->num_devices--;
02db0844 1521 device->fs_devices->total_devices--;
2b82032c 1522
cd02dca5
CM
1523 if (device->missing)
1524 root->fs_info->fs_devices->missing_devices--;
1525
2b82032c
YZ
1526 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1527 struct btrfs_device, dev_list);
1528 if (device->bdev == root->fs_info->sb->s_bdev)
1529 root->fs_info->sb->s_bdev = next_device->bdev;
1530 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1531 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1532
1f78160c 1533 if (device->bdev)
e4404d6e 1534 device->fs_devices->open_devices--;
1f78160c
XG
1535
1536 call_rcu(&device->rcu, free_device);
1537 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
e4404d6e 1538
6c41761f
DS
1539 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1540 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
2b82032c 1541
1f78160c 1542 if (cur_devices->open_devices == 0) {
e4404d6e
YZ
1543 struct btrfs_fs_devices *fs_devices;
1544 fs_devices = root->fs_info->fs_devices;
1545 while (fs_devices) {
1f78160c 1546 if (fs_devices->seed == cur_devices)
e4404d6e
YZ
1547 break;
1548 fs_devices = fs_devices->seed;
2b82032c 1549 }
1f78160c
XG
1550 fs_devices->seed = cur_devices->seed;
1551 cur_devices->seed = NULL;
0c1daee0 1552 lock_chunks(root);
1f78160c 1553 __btrfs_close_devices(cur_devices);
0c1daee0 1554 unlock_chunks(root);
1f78160c 1555 free_fs_devices(cur_devices);
2b82032c
YZ
1556 }
1557
5af3e8cc
SB
1558 root->fs_info->num_tolerated_disk_barrier_failures =
1559 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1560
2b82032c
YZ
1561 /*
1562 * at this point, the device is zero sized. We want to
1563 * remove it from the devices list and zero out the old super
1564 */
aa1b8cd4 1565 if (clear_super && disk_super) {
dfe25020
CM
1566 /* make sure this device isn't detected as part of
1567 * the FS anymore
1568 */
1569 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1570 set_buffer_dirty(bh);
1571 sync_dirty_buffer(bh);
dfe25020 1572 }
a061fc8d 1573
a061fc8d 1574 ret = 0;
a061fc8d 1575
b8b8ff59 1576 /* Notify udev that device has changed */
3c911608
ES
1577 if (bdev)
1578 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
b8b8ff59 1579
a061fc8d
CM
1580error_brelse:
1581 brelse(bh);
dfe25020 1582 if (bdev)
e525fd89 1583 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
a061fc8d
CM
1584out:
1585 mutex_unlock(&uuid_mutex);
a061fc8d 1586 return ret;
9b3517e9
ID
1587error_undo:
1588 if (device->writeable) {
0c1daee0 1589 lock_chunks(root);
9b3517e9
ID
1590 list_add(&device->dev_alloc_list,
1591 &root->fs_info->fs_devices->alloc_list);
0c1daee0 1592 unlock_chunks(root);
9b3517e9
ID
1593 root->fs_info->fs_devices->rw_devices++;
1594 }
1595 goto error_brelse;
a061fc8d
CM
1596}
1597
e93c89c1
SB
1598void btrfs_rm_dev_replace_srcdev(struct btrfs_fs_info *fs_info,
1599 struct btrfs_device *srcdev)
1600{
1601 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1602 list_del_rcu(&srcdev->dev_list);
1603 list_del_rcu(&srcdev->dev_alloc_list);
1604 fs_info->fs_devices->num_devices--;
1605 if (srcdev->missing) {
1606 fs_info->fs_devices->missing_devices--;
1607 fs_info->fs_devices->rw_devices++;
1608 }
1609 if (srcdev->can_discard)
1610 fs_info->fs_devices->num_can_discard--;
1611 if (srcdev->bdev)
1612 fs_info->fs_devices->open_devices--;
1613
1614 call_rcu(&srcdev->rcu, free_device);
1615}
1616
1617void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
1618 struct btrfs_device *tgtdev)
1619{
1620 struct btrfs_device *next_device;
1621
1622 WARN_ON(!tgtdev);
1623 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1624 if (tgtdev->bdev) {
1625 btrfs_scratch_superblock(tgtdev);
1626 fs_info->fs_devices->open_devices--;
1627 }
1628 fs_info->fs_devices->num_devices--;
1629 if (tgtdev->can_discard)
1630 fs_info->fs_devices->num_can_discard++;
1631
1632 next_device = list_entry(fs_info->fs_devices->devices.next,
1633 struct btrfs_device, dev_list);
1634 if (tgtdev->bdev == fs_info->sb->s_bdev)
1635 fs_info->sb->s_bdev = next_device->bdev;
1636 if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
1637 fs_info->fs_devices->latest_bdev = next_device->bdev;
1638 list_del_rcu(&tgtdev->dev_list);
1639
1640 call_rcu(&tgtdev->rcu, free_device);
1641
1642 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1643}
1644
7ba15b7d
SB
1645int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
1646 struct btrfs_device **device)
1647{
1648 int ret = 0;
1649 struct btrfs_super_block *disk_super;
1650 u64 devid;
1651 u8 *dev_uuid;
1652 struct block_device *bdev;
1653 struct buffer_head *bh;
1654
1655 *device = NULL;
1656 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
1657 root->fs_info->bdev_holder, 0, &bdev, &bh);
1658 if (ret)
1659 return ret;
1660 disk_super = (struct btrfs_super_block *)bh->b_data;
1661 devid = btrfs_stack_device_id(&disk_super->dev_item);
1662 dev_uuid = disk_super->dev_item.uuid;
aa1b8cd4 1663 *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
7ba15b7d
SB
1664 disk_super->fsid);
1665 brelse(bh);
1666 if (!*device)
1667 ret = -ENOENT;
1668 blkdev_put(bdev, FMODE_READ);
1669 return ret;
1670}
1671
1672int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
1673 char *device_path,
1674 struct btrfs_device **device)
1675{
1676 *device = NULL;
1677 if (strcmp(device_path, "missing") == 0) {
1678 struct list_head *devices;
1679 struct btrfs_device *tmp;
1680
1681 devices = &root->fs_info->fs_devices->devices;
1682 /*
1683 * It is safe to read the devices since the volume_mutex
1684 * is held by the caller.
1685 */
1686 list_for_each_entry(tmp, devices, dev_list) {
1687 if (tmp->in_fs_metadata && !tmp->bdev) {
1688 *device = tmp;
1689 break;
1690 }
1691 }
1692
1693 if (!*device) {
1694 pr_err("btrfs: no missing device found\n");
1695 return -ENOENT;
1696 }
1697
1698 return 0;
1699 } else {
1700 return btrfs_find_device_by_path(root, device_path, device);
1701 }
1702}
1703
2b82032c
YZ
1704/*
1705 * does all the dirty work required for changing file system's UUID.
1706 */
125ccb0a 1707static int btrfs_prepare_sprout(struct btrfs_root *root)
2b82032c
YZ
1708{
1709 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1710 struct btrfs_fs_devices *old_devices;
e4404d6e 1711 struct btrfs_fs_devices *seed_devices;
6c41761f 1712 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
2b82032c
YZ
1713 struct btrfs_device *device;
1714 u64 super_flags;
1715
1716 BUG_ON(!mutex_is_locked(&uuid_mutex));
e4404d6e 1717 if (!fs_devices->seeding)
2b82032c
YZ
1718 return -EINVAL;
1719
e4404d6e
YZ
1720 seed_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1721 if (!seed_devices)
2b82032c
YZ
1722 return -ENOMEM;
1723
e4404d6e
YZ
1724 old_devices = clone_fs_devices(fs_devices);
1725 if (IS_ERR(old_devices)) {
1726 kfree(seed_devices);
1727 return PTR_ERR(old_devices);
2b82032c 1728 }
e4404d6e 1729
2b82032c
YZ
1730 list_add(&old_devices->list, &fs_uuids);
1731
e4404d6e
YZ
1732 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1733 seed_devices->opened = 1;
1734 INIT_LIST_HEAD(&seed_devices->devices);
1735 INIT_LIST_HEAD(&seed_devices->alloc_list);
e5e9a520 1736 mutex_init(&seed_devices->device_list_mutex);
c9513edb
XG
1737
1738 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1f78160c
XG
1739 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1740 synchronize_rcu);
c9513edb
XG
1741 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1742
e4404d6e
YZ
1743 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1744 list_for_each_entry(device, &seed_devices->devices, dev_list) {
1745 device->fs_devices = seed_devices;
1746 }
1747
2b82032c
YZ
1748 fs_devices->seeding = 0;
1749 fs_devices->num_devices = 0;
1750 fs_devices->open_devices = 0;
02db0844 1751 fs_devices->total_devices = 0;
e4404d6e 1752 fs_devices->seed = seed_devices;
2b82032c
YZ
1753
1754 generate_random_uuid(fs_devices->fsid);
1755 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1756 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1757 super_flags = btrfs_super_flags(disk_super) &
1758 ~BTRFS_SUPER_FLAG_SEEDING;
1759 btrfs_set_super_flags(disk_super, super_flags);
1760
1761 return 0;
1762}
1763
1764/*
1765 * strore the expected generation for seed devices in device items.
1766 */
1767static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1768 struct btrfs_root *root)
1769{
1770 struct btrfs_path *path;
1771 struct extent_buffer *leaf;
1772 struct btrfs_dev_item *dev_item;
1773 struct btrfs_device *device;
1774 struct btrfs_key key;
1775 u8 fs_uuid[BTRFS_UUID_SIZE];
1776 u8 dev_uuid[BTRFS_UUID_SIZE];
1777 u64 devid;
1778 int ret;
1779
1780 path = btrfs_alloc_path();
1781 if (!path)
1782 return -ENOMEM;
1783
1784 root = root->fs_info->chunk_root;
1785 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1786 key.offset = 0;
1787 key.type = BTRFS_DEV_ITEM_KEY;
1788
1789 while (1) {
1790 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1791 if (ret < 0)
1792 goto error;
1793
1794 leaf = path->nodes[0];
1795next_slot:
1796 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1797 ret = btrfs_next_leaf(root, path);
1798 if (ret > 0)
1799 break;
1800 if (ret < 0)
1801 goto error;
1802 leaf = path->nodes[0];
1803 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
b3b4aa74 1804 btrfs_release_path(path);
2b82032c
YZ
1805 continue;
1806 }
1807
1808 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1809 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1810 key.type != BTRFS_DEV_ITEM_KEY)
1811 break;
1812
1813 dev_item = btrfs_item_ptr(leaf, path->slots[0],
1814 struct btrfs_dev_item);
1815 devid = btrfs_device_id(leaf, dev_item);
1816 read_extent_buffer(leaf, dev_uuid,
1817 (unsigned long)btrfs_device_uuid(dev_item),
1818 BTRFS_UUID_SIZE);
1819 read_extent_buffer(leaf, fs_uuid,
1820 (unsigned long)btrfs_device_fsid(dev_item),
1821 BTRFS_UUID_SIZE);
aa1b8cd4
SB
1822 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1823 fs_uuid);
79787eaa 1824 BUG_ON(!device); /* Logic error */
2b82032c
YZ
1825
1826 if (device->fs_devices->seeding) {
1827 btrfs_set_device_generation(leaf, dev_item,
1828 device->generation);
1829 btrfs_mark_buffer_dirty(leaf);
1830 }
1831
1832 path->slots[0]++;
1833 goto next_slot;
1834 }
1835 ret = 0;
1836error:
1837 btrfs_free_path(path);
1838 return ret;
1839}
1840
788f20eb
CM
1841int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1842{
d5e2003c 1843 struct request_queue *q;
788f20eb
CM
1844 struct btrfs_trans_handle *trans;
1845 struct btrfs_device *device;
1846 struct block_device *bdev;
788f20eb 1847 struct list_head *devices;
2b82032c 1848 struct super_block *sb = root->fs_info->sb;
606686ee 1849 struct rcu_string *name;
788f20eb 1850 u64 total_bytes;
2b82032c 1851 int seeding_dev = 0;
788f20eb
CM
1852 int ret = 0;
1853
2b82032c 1854 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
f8c5d0b4 1855 return -EROFS;
788f20eb 1856
a5d16333 1857 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
d4d77629 1858 root->fs_info->bdev_holder);
7f59203a
JB
1859 if (IS_ERR(bdev))
1860 return PTR_ERR(bdev);
a2135011 1861
2b82032c
YZ
1862 if (root->fs_info->fs_devices->seeding) {
1863 seeding_dev = 1;
1864 down_write(&sb->s_umount);
1865 mutex_lock(&uuid_mutex);
1866 }
1867
8c8bee1d 1868 filemap_write_and_wait(bdev->bd_inode->i_mapping);
a2135011 1869
788f20eb 1870 devices = &root->fs_info->fs_devices->devices;
d25628bd
LB
1871
1872 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
c6e30871 1873 list_for_each_entry(device, devices, dev_list) {
788f20eb
CM
1874 if (device->bdev == bdev) {
1875 ret = -EEXIST;
d25628bd
LB
1876 mutex_unlock(
1877 &root->fs_info->fs_devices->device_list_mutex);
2b82032c 1878 goto error;
788f20eb
CM
1879 }
1880 }
d25628bd 1881 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
788f20eb
CM
1882
1883 device = kzalloc(sizeof(*device), GFP_NOFS);
1884 if (!device) {
1885 /* we can safely leave the fs_devices entry around */
1886 ret = -ENOMEM;
2b82032c 1887 goto error;
788f20eb
CM
1888 }
1889
606686ee
JB
1890 name = rcu_string_strdup(device_path, GFP_NOFS);
1891 if (!name) {
788f20eb 1892 kfree(device);
2b82032c
YZ
1893 ret = -ENOMEM;
1894 goto error;
788f20eb 1895 }
606686ee 1896 rcu_assign_pointer(device->name, name);
2b82032c
YZ
1897
1898 ret = find_next_devid(root, &device->devid);
1899 if (ret) {
606686ee 1900 rcu_string_free(device->name);
2b82032c
YZ
1901 kfree(device);
1902 goto error;
1903 }
1904
a22285a6 1905 trans = btrfs_start_transaction(root, 0);
98d5dc13 1906 if (IS_ERR(trans)) {
606686ee 1907 rcu_string_free(device->name);
98d5dc13
TI
1908 kfree(device);
1909 ret = PTR_ERR(trans);
1910 goto error;
1911 }
1912
2b82032c
YZ
1913 lock_chunks(root);
1914
d5e2003c
JB
1915 q = bdev_get_queue(bdev);
1916 if (blk_queue_discard(q))
1917 device->can_discard = 1;
2b82032c
YZ
1918 device->writeable = 1;
1919 device->work.func = pending_bios_fn;
1920 generate_random_uuid(device->uuid);
1921 spin_lock_init(&device->io_lock);
1922 device->generation = trans->transid;
788f20eb
CM
1923 device->io_width = root->sectorsize;
1924 device->io_align = root->sectorsize;
1925 device->sector_size = root->sectorsize;
1926 device->total_bytes = i_size_read(bdev->bd_inode);
2cc3c559 1927 device->disk_total_bytes = device->total_bytes;
788f20eb
CM
1928 device->dev_root = root->fs_info->dev_root;
1929 device->bdev = bdev;
dfe25020 1930 device->in_fs_metadata = 1;
63a212ab 1931 device->is_tgtdev_for_dev_replace = 0;
fb01aa85 1932 device->mode = FMODE_EXCL;
2b82032c 1933 set_blocksize(device->bdev, 4096);
788f20eb 1934
2b82032c
YZ
1935 if (seeding_dev) {
1936 sb->s_flags &= ~MS_RDONLY;
125ccb0a 1937 ret = btrfs_prepare_sprout(root);
79787eaa 1938 BUG_ON(ret); /* -ENOMEM */
2b82032c 1939 }
788f20eb 1940
2b82032c 1941 device->fs_devices = root->fs_info->fs_devices;
e5e9a520 1942
e5e9a520 1943 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1f78160c 1944 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2b82032c
YZ
1945 list_add(&device->dev_alloc_list,
1946 &root->fs_info->fs_devices->alloc_list);
1947 root->fs_info->fs_devices->num_devices++;
1948 root->fs_info->fs_devices->open_devices++;
1949 root->fs_info->fs_devices->rw_devices++;
02db0844 1950 root->fs_info->fs_devices->total_devices++;
d5e2003c
JB
1951 if (device->can_discard)
1952 root->fs_info->fs_devices->num_can_discard++;
2b82032c 1953 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
325cd4ba 1954
2bf64758
JB
1955 spin_lock(&root->fs_info->free_chunk_lock);
1956 root->fs_info->free_chunk_space += device->total_bytes;
1957 spin_unlock(&root->fs_info->free_chunk_lock);
1958
c289811c
CM
1959 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
1960 root->fs_info->fs_devices->rotating = 1;
1961
6c41761f
DS
1962 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1963 btrfs_set_super_total_bytes(root->fs_info->super_copy,
788f20eb
CM
1964 total_bytes + device->total_bytes);
1965
6c41761f
DS
1966 total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
1967 btrfs_set_super_num_devices(root->fs_info->super_copy,
788f20eb 1968 total_bytes + 1);
e5e9a520 1969 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
788f20eb 1970
2b82032c
YZ
1971 if (seeding_dev) {
1972 ret = init_first_rw_device(trans, root, device);
005d6427
DS
1973 if (ret) {
1974 btrfs_abort_transaction(trans, root, ret);
79787eaa 1975 goto error_trans;
005d6427 1976 }
2b82032c 1977 ret = btrfs_finish_sprout(trans, root);
005d6427
DS
1978 if (ret) {
1979 btrfs_abort_transaction(trans, root, ret);
79787eaa 1980 goto error_trans;
005d6427 1981 }
2b82032c
YZ
1982 } else {
1983 ret = btrfs_add_device(trans, root, device);
005d6427
DS
1984 if (ret) {
1985 btrfs_abort_transaction(trans, root, ret);
79787eaa 1986 goto error_trans;
005d6427 1987 }
2b82032c
YZ
1988 }
1989
913d952e
CM
1990 /*
1991 * we've got more storage, clear any full flags on the space
1992 * infos
1993 */
1994 btrfs_clear_space_info_full(root->fs_info);
1995
7d9eb12c 1996 unlock_chunks(root);
5af3e8cc
SB
1997 root->fs_info->num_tolerated_disk_barrier_failures =
1998 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
79787eaa 1999 ret = btrfs_commit_transaction(trans, root);
a2135011 2000
2b82032c
YZ
2001 if (seeding_dev) {
2002 mutex_unlock(&uuid_mutex);
2003 up_write(&sb->s_umount);
788f20eb 2004
79787eaa
JM
2005 if (ret) /* transaction commit */
2006 return ret;
2007
2b82032c 2008 ret = btrfs_relocate_sys_chunks(root);
79787eaa
JM
2009 if (ret < 0)
2010 btrfs_error(root->fs_info, ret,
2011 "Failed to relocate sys chunks after "
2012 "device initialization. This can be fixed "
2013 "using the \"btrfs balance\" command.");
671415b7
MX
2014 trans = btrfs_attach_transaction(root);
2015 if (IS_ERR(trans)) {
2016 if (PTR_ERR(trans) == -ENOENT)
2017 return 0;
2018 return PTR_ERR(trans);
2019 }
2020 ret = btrfs_commit_transaction(trans, root);
2b82032c 2021 }
c9e9f97b 2022
2b82032c 2023 return ret;
79787eaa
JM
2024
2025error_trans:
2026 unlock_chunks(root);
79787eaa 2027 btrfs_end_transaction(trans, root);
606686ee 2028 rcu_string_free(device->name);
79787eaa 2029 kfree(device);
2b82032c 2030error:
e525fd89 2031 blkdev_put(bdev, FMODE_EXCL);
2b82032c
YZ
2032 if (seeding_dev) {
2033 mutex_unlock(&uuid_mutex);
2034 up_write(&sb->s_umount);
2035 }
c9e9f97b 2036 return ret;
788f20eb
CM
2037}
2038
e93c89c1
SB
2039int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2040 struct btrfs_device **device_out)
2041{
2042 struct request_queue *q;
2043 struct btrfs_device *device;
2044 struct block_device *bdev;
2045 struct btrfs_fs_info *fs_info = root->fs_info;
2046 struct list_head *devices;
2047 struct rcu_string *name;
2048 int ret = 0;
2049
2050 *device_out = NULL;
2051 if (fs_info->fs_devices->seeding)
2052 return -EINVAL;
2053
2054 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2055 fs_info->bdev_holder);
2056 if (IS_ERR(bdev))
2057 return PTR_ERR(bdev);
2058
2059 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2060
2061 devices = &fs_info->fs_devices->devices;
2062 list_for_each_entry(device, devices, dev_list) {
2063 if (device->bdev == bdev) {
2064 ret = -EEXIST;
2065 goto error;
2066 }
2067 }
2068
2069 device = kzalloc(sizeof(*device), GFP_NOFS);
2070 if (!device) {
2071 ret = -ENOMEM;
2072 goto error;
2073 }
2074
2075 name = rcu_string_strdup(device_path, GFP_NOFS);
2076 if (!name) {
2077 kfree(device);
2078 ret = -ENOMEM;
2079 goto error;
2080 }
2081 rcu_assign_pointer(device->name, name);
2082
2083 q = bdev_get_queue(bdev);
2084 if (blk_queue_discard(q))
2085 device->can_discard = 1;
2086 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2087 device->writeable = 1;
2088 device->work.func = pending_bios_fn;
2089 generate_random_uuid(device->uuid);
2090 device->devid = BTRFS_DEV_REPLACE_DEVID;
2091 spin_lock_init(&device->io_lock);
2092 device->generation = 0;
2093 device->io_width = root->sectorsize;
2094 device->io_align = root->sectorsize;
2095 device->sector_size = root->sectorsize;
2096 device->total_bytes = i_size_read(bdev->bd_inode);
2097 device->disk_total_bytes = device->total_bytes;
2098 device->dev_root = fs_info->dev_root;
2099 device->bdev = bdev;
2100 device->in_fs_metadata = 1;
2101 device->is_tgtdev_for_dev_replace = 1;
2102 device->mode = FMODE_EXCL;
2103 set_blocksize(device->bdev, 4096);
2104 device->fs_devices = fs_info->fs_devices;
2105 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2106 fs_info->fs_devices->num_devices++;
2107 fs_info->fs_devices->open_devices++;
2108 if (device->can_discard)
2109 fs_info->fs_devices->num_can_discard++;
2110 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2111
2112 *device_out = device;
2113 return ret;
2114
2115error:
2116 blkdev_put(bdev, FMODE_EXCL);
2117 return ret;
2118}
2119
2120void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2121 struct btrfs_device *tgtdev)
2122{
2123 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2124 tgtdev->io_width = fs_info->dev_root->sectorsize;
2125 tgtdev->io_align = fs_info->dev_root->sectorsize;
2126 tgtdev->sector_size = fs_info->dev_root->sectorsize;
2127 tgtdev->dev_root = fs_info->dev_root;
2128 tgtdev->in_fs_metadata = 1;
2129}
2130
d397712b
CM
2131static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2132 struct btrfs_device *device)
0b86a832
CM
2133{
2134 int ret;
2135 struct btrfs_path *path;
2136 struct btrfs_root *root;
2137 struct btrfs_dev_item *dev_item;
2138 struct extent_buffer *leaf;
2139 struct btrfs_key key;
2140
2141 root = device->dev_root->fs_info->chunk_root;
2142
2143 path = btrfs_alloc_path();
2144 if (!path)
2145 return -ENOMEM;
2146
2147 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2148 key.type = BTRFS_DEV_ITEM_KEY;
2149 key.offset = device->devid;
2150
2151 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2152 if (ret < 0)
2153 goto out;
2154
2155 if (ret > 0) {
2156 ret = -ENOENT;
2157 goto out;
2158 }
2159
2160 leaf = path->nodes[0];
2161 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2162
2163 btrfs_set_device_id(leaf, dev_item, device->devid);
2164 btrfs_set_device_type(leaf, dev_item, device->type);
2165 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2166 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2167 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
d6397bae 2168 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
0b86a832
CM
2169 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
2170 btrfs_mark_buffer_dirty(leaf);
2171
2172out:
2173 btrfs_free_path(path);
2174 return ret;
2175}
2176
7d9eb12c 2177static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
8f18cf13
CM
2178 struct btrfs_device *device, u64 new_size)
2179{
2180 struct btrfs_super_block *super_copy =
6c41761f 2181 device->dev_root->fs_info->super_copy;
8f18cf13
CM
2182 u64 old_total = btrfs_super_total_bytes(super_copy);
2183 u64 diff = new_size - device->total_bytes;
2184
2b82032c
YZ
2185 if (!device->writeable)
2186 return -EACCES;
63a212ab
SB
2187 if (new_size <= device->total_bytes ||
2188 device->is_tgtdev_for_dev_replace)
2b82032c
YZ
2189 return -EINVAL;
2190
8f18cf13 2191 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2b82032c
YZ
2192 device->fs_devices->total_rw_bytes += diff;
2193
2194 device->total_bytes = new_size;
9779b72f 2195 device->disk_total_bytes = new_size;
4184ea7f
CM
2196 btrfs_clear_space_info_full(device->dev_root->fs_info);
2197
8f18cf13
CM
2198 return btrfs_update_device(trans, device);
2199}
2200
7d9eb12c
CM
2201int btrfs_grow_device(struct btrfs_trans_handle *trans,
2202 struct btrfs_device *device, u64 new_size)
2203{
2204 int ret;
2205 lock_chunks(device->dev_root);
2206 ret = __btrfs_grow_device(trans, device, new_size);
2207 unlock_chunks(device->dev_root);
2208 return ret;
2209}
2210
8f18cf13
CM
2211static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2212 struct btrfs_root *root,
2213 u64 chunk_tree, u64 chunk_objectid,
2214 u64 chunk_offset)
2215{
2216 int ret;
2217 struct btrfs_path *path;
2218 struct btrfs_key key;
2219
2220 root = root->fs_info->chunk_root;
2221 path = btrfs_alloc_path();
2222 if (!path)
2223 return -ENOMEM;
2224
2225 key.objectid = chunk_objectid;
2226 key.offset = chunk_offset;
2227 key.type = BTRFS_CHUNK_ITEM_KEY;
2228
2229 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
79787eaa
JM
2230 if (ret < 0)
2231 goto out;
2232 else if (ret > 0) { /* Logic error or corruption */
2233 btrfs_error(root->fs_info, -ENOENT,
2234 "Failed lookup while freeing chunk.");
2235 ret = -ENOENT;
2236 goto out;
2237 }
8f18cf13
CM
2238
2239 ret = btrfs_del_item(trans, root, path);
79787eaa
JM
2240 if (ret < 0)
2241 btrfs_error(root->fs_info, ret,
2242 "Failed to delete chunk item.");
2243out:
8f18cf13 2244 btrfs_free_path(path);
65a246c5 2245 return ret;
8f18cf13
CM
2246}
2247
b2950863 2248static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
8f18cf13
CM
2249 chunk_offset)
2250{
6c41761f 2251 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
8f18cf13
CM
2252 struct btrfs_disk_key *disk_key;
2253 struct btrfs_chunk *chunk;
2254 u8 *ptr;
2255 int ret = 0;
2256 u32 num_stripes;
2257 u32 array_size;
2258 u32 len = 0;
2259 u32 cur;
2260 struct btrfs_key key;
2261
2262 array_size = btrfs_super_sys_array_size(super_copy);
2263
2264 ptr = super_copy->sys_chunk_array;
2265 cur = 0;
2266
2267 while (cur < array_size) {
2268 disk_key = (struct btrfs_disk_key *)ptr;
2269 btrfs_disk_key_to_cpu(&key, disk_key);
2270
2271 len = sizeof(*disk_key);
2272
2273 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2274 chunk = (struct btrfs_chunk *)(ptr + len);
2275 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2276 len += btrfs_chunk_item_size(num_stripes);
2277 } else {
2278 ret = -EIO;
2279 break;
2280 }
2281 if (key.objectid == chunk_objectid &&
2282 key.offset == chunk_offset) {
2283 memmove(ptr, ptr + len, array_size - (cur + len));
2284 array_size -= len;
2285 btrfs_set_super_sys_array_size(super_copy, array_size);
2286 } else {
2287 ptr += len;
2288 cur += len;
2289 }
2290 }
2291 return ret;
2292}
2293
b2950863 2294static int btrfs_relocate_chunk(struct btrfs_root *root,
8f18cf13
CM
2295 u64 chunk_tree, u64 chunk_objectid,
2296 u64 chunk_offset)
2297{
2298 struct extent_map_tree *em_tree;
2299 struct btrfs_root *extent_root;
2300 struct btrfs_trans_handle *trans;
2301 struct extent_map *em;
2302 struct map_lookup *map;
2303 int ret;
2304 int i;
2305
2306 root = root->fs_info->chunk_root;
2307 extent_root = root->fs_info->extent_root;
2308 em_tree = &root->fs_info->mapping_tree.map_tree;
2309
ba1bf481
JB
2310 ret = btrfs_can_relocate(extent_root, chunk_offset);
2311 if (ret)
2312 return -ENOSPC;
2313
8f18cf13 2314 /* step one, relocate all the extents inside this chunk */
1a40e23b 2315 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
a22285a6
YZ
2316 if (ret)
2317 return ret;
8f18cf13 2318
a22285a6 2319 trans = btrfs_start_transaction(root, 0);
98d5dc13 2320 BUG_ON(IS_ERR(trans));
8f18cf13 2321
7d9eb12c
CM
2322 lock_chunks(root);
2323
8f18cf13
CM
2324 /*
2325 * step two, delete the device extents and the
2326 * chunk tree entries
2327 */
890871be 2328 read_lock(&em_tree->lock);
8f18cf13 2329 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
890871be 2330 read_unlock(&em_tree->lock);
8f18cf13 2331
285190d9 2332 BUG_ON(!em || em->start > chunk_offset ||
a061fc8d 2333 em->start + em->len < chunk_offset);
8f18cf13
CM
2334 map = (struct map_lookup *)em->bdev;
2335
2336 for (i = 0; i < map->num_stripes; i++) {
2337 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
2338 map->stripes[i].physical);
2339 BUG_ON(ret);
a061fc8d 2340
dfe25020
CM
2341 if (map->stripes[i].dev) {
2342 ret = btrfs_update_device(trans, map->stripes[i].dev);
2343 BUG_ON(ret);
2344 }
8f18cf13
CM
2345 }
2346 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
2347 chunk_offset);
2348
2349 BUG_ON(ret);
2350
1abe9b8a 2351 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2352
8f18cf13
CM
2353 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2354 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2355 BUG_ON(ret);
8f18cf13
CM
2356 }
2357
2b82032c
YZ
2358 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
2359 BUG_ON(ret);
2360
890871be 2361 write_lock(&em_tree->lock);
2b82032c 2362 remove_extent_mapping(em_tree, em);
890871be 2363 write_unlock(&em_tree->lock);
2b82032c
YZ
2364
2365 kfree(map);
2366 em->bdev = NULL;
2367
2368 /* once for the tree */
2369 free_extent_map(em);
2370 /* once for us */
2371 free_extent_map(em);
2372
2373 unlock_chunks(root);
2374 btrfs_end_transaction(trans, root);
2375 return 0;
2376}
2377
2378static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2379{
2380 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2381 struct btrfs_path *path;
2382 struct extent_buffer *leaf;
2383 struct btrfs_chunk *chunk;
2384 struct btrfs_key key;
2385 struct btrfs_key found_key;
2386 u64 chunk_tree = chunk_root->root_key.objectid;
2387 u64 chunk_type;
ba1bf481
JB
2388 bool retried = false;
2389 int failed = 0;
2b82032c
YZ
2390 int ret;
2391
2392 path = btrfs_alloc_path();
2393 if (!path)
2394 return -ENOMEM;
2395
ba1bf481 2396again:
2b82032c
YZ
2397 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2398 key.offset = (u64)-1;
2399 key.type = BTRFS_CHUNK_ITEM_KEY;
2400
2401 while (1) {
2402 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2403 if (ret < 0)
2404 goto error;
79787eaa 2405 BUG_ON(ret == 0); /* Corruption */
2b82032c
YZ
2406
2407 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2408 key.type);
2409 if (ret < 0)
2410 goto error;
2411 if (ret > 0)
2412 break;
1a40e23b 2413
2b82032c
YZ
2414 leaf = path->nodes[0];
2415 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1a40e23b 2416
2b82032c
YZ
2417 chunk = btrfs_item_ptr(leaf, path->slots[0],
2418 struct btrfs_chunk);
2419 chunk_type = btrfs_chunk_type(leaf, chunk);
b3b4aa74 2420 btrfs_release_path(path);
8f18cf13 2421
2b82032c
YZ
2422 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2423 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2424 found_key.objectid,
2425 found_key.offset);
ba1bf481
JB
2426 if (ret == -ENOSPC)
2427 failed++;
2428 else if (ret)
2429 BUG();
2b82032c 2430 }
8f18cf13 2431
2b82032c
YZ
2432 if (found_key.offset == 0)
2433 break;
2434 key.offset = found_key.offset - 1;
2435 }
2436 ret = 0;
ba1bf481
JB
2437 if (failed && !retried) {
2438 failed = 0;
2439 retried = true;
2440 goto again;
2441 } else if (failed && retried) {
2442 WARN_ON(1);
2443 ret = -ENOSPC;
2444 }
2b82032c
YZ
2445error:
2446 btrfs_free_path(path);
2447 return ret;
8f18cf13
CM
2448}
2449
0940ebf6
ID
2450static int insert_balance_item(struct btrfs_root *root,
2451 struct btrfs_balance_control *bctl)
2452{
2453 struct btrfs_trans_handle *trans;
2454 struct btrfs_balance_item *item;
2455 struct btrfs_disk_balance_args disk_bargs;
2456 struct btrfs_path *path;
2457 struct extent_buffer *leaf;
2458 struct btrfs_key key;
2459 int ret, err;
2460
2461 path = btrfs_alloc_path();
2462 if (!path)
2463 return -ENOMEM;
2464
2465 trans = btrfs_start_transaction(root, 0);
2466 if (IS_ERR(trans)) {
2467 btrfs_free_path(path);
2468 return PTR_ERR(trans);
2469 }
2470
2471 key.objectid = BTRFS_BALANCE_OBJECTID;
2472 key.type = BTRFS_BALANCE_ITEM_KEY;
2473 key.offset = 0;
2474
2475 ret = btrfs_insert_empty_item(trans, root, path, &key,
2476 sizeof(*item));
2477 if (ret)
2478 goto out;
2479
2480 leaf = path->nodes[0];
2481 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2482
2483 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2484
2485 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2486 btrfs_set_balance_data(leaf, item, &disk_bargs);
2487 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2488 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2489 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2490 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2491
2492 btrfs_set_balance_flags(leaf, item, bctl->flags);
2493
2494 btrfs_mark_buffer_dirty(leaf);
2495out:
2496 btrfs_free_path(path);
2497 err = btrfs_commit_transaction(trans, root);
2498 if (err && !ret)
2499 ret = err;
2500 return ret;
2501}
2502
2503static int del_balance_item(struct btrfs_root *root)
2504{
2505 struct btrfs_trans_handle *trans;
2506 struct btrfs_path *path;
2507 struct btrfs_key key;
2508 int ret, err;
2509
2510 path = btrfs_alloc_path();
2511 if (!path)
2512 return -ENOMEM;
2513
2514 trans = btrfs_start_transaction(root, 0);
2515 if (IS_ERR(trans)) {
2516 btrfs_free_path(path);
2517 return PTR_ERR(trans);
2518 }
2519
2520 key.objectid = BTRFS_BALANCE_OBJECTID;
2521 key.type = BTRFS_BALANCE_ITEM_KEY;
2522 key.offset = 0;
2523
2524 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2525 if (ret < 0)
2526 goto out;
2527 if (ret > 0) {
2528 ret = -ENOENT;
2529 goto out;
2530 }
2531
2532 ret = btrfs_del_item(trans, root, path);
2533out:
2534 btrfs_free_path(path);
2535 err = btrfs_commit_transaction(trans, root);
2536 if (err && !ret)
2537 ret = err;
2538 return ret;
2539}
2540
59641015
ID
2541/*
2542 * This is a heuristic used to reduce the number of chunks balanced on
2543 * resume after balance was interrupted.
2544 */
2545static void update_balance_args(struct btrfs_balance_control *bctl)
2546{
2547 /*
2548 * Turn on soft mode for chunk types that were being converted.
2549 */
2550 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2551 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2552 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2553 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2554 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2555 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2556
2557 /*
2558 * Turn on usage filter if is not already used. The idea is
2559 * that chunks that we have already balanced should be
2560 * reasonably full. Don't do it for chunks that are being
2561 * converted - that will keep us from relocating unconverted
2562 * (albeit full) chunks.
2563 */
2564 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2565 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2566 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2567 bctl->data.usage = 90;
2568 }
2569 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2570 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2571 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2572 bctl->sys.usage = 90;
2573 }
2574 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2575 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2576 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2577 bctl->meta.usage = 90;
2578 }
2579}
2580
c9e9f97b
ID
2581/*
2582 * Should be called with both balance and volume mutexes held to
2583 * serialize other volume operations (add_dev/rm_dev/resize) with
2584 * restriper. Same goes for unset_balance_control.
2585 */
2586static void set_balance_control(struct btrfs_balance_control *bctl)
2587{
2588 struct btrfs_fs_info *fs_info = bctl->fs_info;
2589
2590 BUG_ON(fs_info->balance_ctl);
2591
2592 spin_lock(&fs_info->balance_lock);
2593 fs_info->balance_ctl = bctl;
2594 spin_unlock(&fs_info->balance_lock);
2595}
2596
2597static void unset_balance_control(struct btrfs_fs_info *fs_info)
2598{
2599 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2600
2601 BUG_ON(!fs_info->balance_ctl);
2602
2603 spin_lock(&fs_info->balance_lock);
2604 fs_info->balance_ctl = NULL;
2605 spin_unlock(&fs_info->balance_lock);
2606
2607 kfree(bctl);
2608}
2609
ed25e9b2
ID
2610/*
2611 * Balance filters. Return 1 if chunk should be filtered out
2612 * (should not be balanced).
2613 */
899c81ea 2614static int chunk_profiles_filter(u64 chunk_type,
ed25e9b2
ID
2615 struct btrfs_balance_args *bargs)
2616{
899c81ea
ID
2617 chunk_type = chunk_to_extended(chunk_type) &
2618 BTRFS_EXTENDED_PROFILE_MASK;
ed25e9b2 2619
899c81ea 2620 if (bargs->profiles & chunk_type)
ed25e9b2
ID
2621 return 0;
2622
2623 return 1;
2624}
2625
5ce5b3c0
ID
2626static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2627 struct btrfs_balance_args *bargs)
2628{
2629 struct btrfs_block_group_cache *cache;
2630 u64 chunk_used, user_thresh;
2631 int ret = 1;
2632
2633 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2634 chunk_used = btrfs_block_group_used(&cache->item);
2635
a105bb88
ID
2636 if (bargs->usage == 0)
2637 user_thresh = 0;
2638 else if (bargs->usage > 100)
2639 user_thresh = cache->key.offset;
2640 else
2641 user_thresh = div_factor_fine(cache->key.offset,
2642 bargs->usage);
2643
5ce5b3c0
ID
2644 if (chunk_used < user_thresh)
2645 ret = 0;
2646
2647 btrfs_put_block_group(cache);
2648 return ret;
2649}
2650
409d404b
ID
2651static int chunk_devid_filter(struct extent_buffer *leaf,
2652 struct btrfs_chunk *chunk,
2653 struct btrfs_balance_args *bargs)
2654{
2655 struct btrfs_stripe *stripe;
2656 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2657 int i;
2658
2659 for (i = 0; i < num_stripes; i++) {
2660 stripe = btrfs_stripe_nr(chunk, i);
2661 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2662 return 0;
2663 }
2664
2665 return 1;
2666}
2667
94e60d5a
ID
2668/* [pstart, pend) */
2669static int chunk_drange_filter(struct extent_buffer *leaf,
2670 struct btrfs_chunk *chunk,
2671 u64 chunk_offset,
2672 struct btrfs_balance_args *bargs)
2673{
2674 struct btrfs_stripe *stripe;
2675 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2676 u64 stripe_offset;
2677 u64 stripe_length;
2678 int factor;
2679 int i;
2680
2681 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2682 return 0;
2683
2684 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
53b381b3
DW
2685 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
2686 factor = num_stripes / 2;
2687 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
2688 factor = num_stripes - 1;
2689 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
2690 factor = num_stripes - 2;
2691 } else {
2692 factor = num_stripes;
2693 }
94e60d5a
ID
2694
2695 for (i = 0; i < num_stripes; i++) {
2696 stripe = btrfs_stripe_nr(chunk, i);
2697 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2698 continue;
2699
2700 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2701 stripe_length = btrfs_chunk_length(leaf, chunk);
2702 do_div(stripe_length, factor);
2703
2704 if (stripe_offset < bargs->pend &&
2705 stripe_offset + stripe_length > bargs->pstart)
2706 return 0;
2707 }
2708
2709 return 1;
2710}
2711
ea67176a
ID
2712/* [vstart, vend) */
2713static int chunk_vrange_filter(struct extent_buffer *leaf,
2714 struct btrfs_chunk *chunk,
2715 u64 chunk_offset,
2716 struct btrfs_balance_args *bargs)
2717{
2718 if (chunk_offset < bargs->vend &&
2719 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
2720 /* at least part of the chunk is inside this vrange */
2721 return 0;
2722
2723 return 1;
2724}
2725
899c81ea 2726static int chunk_soft_convert_filter(u64 chunk_type,
cfa4c961
ID
2727 struct btrfs_balance_args *bargs)
2728{
2729 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
2730 return 0;
2731
899c81ea
ID
2732 chunk_type = chunk_to_extended(chunk_type) &
2733 BTRFS_EXTENDED_PROFILE_MASK;
cfa4c961 2734
899c81ea 2735 if (bargs->target == chunk_type)
cfa4c961
ID
2736 return 1;
2737
2738 return 0;
2739}
2740
f43ffb60
ID
2741static int should_balance_chunk(struct btrfs_root *root,
2742 struct extent_buffer *leaf,
2743 struct btrfs_chunk *chunk, u64 chunk_offset)
2744{
2745 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2746 struct btrfs_balance_args *bargs = NULL;
2747 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
2748
2749 /* type filter */
2750 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
2751 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
2752 return 0;
2753 }
2754
2755 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
2756 bargs = &bctl->data;
2757 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
2758 bargs = &bctl->sys;
2759 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
2760 bargs = &bctl->meta;
2761
ed25e9b2
ID
2762 /* profiles filter */
2763 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
2764 chunk_profiles_filter(chunk_type, bargs)) {
2765 return 0;
5ce5b3c0
ID
2766 }
2767
2768 /* usage filter */
2769 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
2770 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
2771 return 0;
409d404b
ID
2772 }
2773
2774 /* devid filter */
2775 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
2776 chunk_devid_filter(leaf, chunk, bargs)) {
2777 return 0;
94e60d5a
ID
2778 }
2779
2780 /* drange filter, makes sense only with devid filter */
2781 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
2782 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
2783 return 0;
ea67176a
ID
2784 }
2785
2786 /* vrange filter */
2787 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
2788 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
2789 return 0;
ed25e9b2
ID
2790 }
2791
cfa4c961
ID
2792 /* soft profile changing mode */
2793 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
2794 chunk_soft_convert_filter(chunk_type, bargs)) {
2795 return 0;
2796 }
2797
f43ffb60
ID
2798 return 1;
2799}
2800
c9e9f97b 2801static int __btrfs_balance(struct btrfs_fs_info *fs_info)
ec44a35c 2802{
19a39dce 2803 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
c9e9f97b
ID
2804 struct btrfs_root *chunk_root = fs_info->chunk_root;
2805 struct btrfs_root *dev_root = fs_info->dev_root;
2806 struct list_head *devices;
ec44a35c
CM
2807 struct btrfs_device *device;
2808 u64 old_size;
2809 u64 size_to_free;
f43ffb60 2810 struct btrfs_chunk *chunk;
ec44a35c
CM
2811 struct btrfs_path *path;
2812 struct btrfs_key key;
ec44a35c 2813 struct btrfs_key found_key;
c9e9f97b 2814 struct btrfs_trans_handle *trans;
f43ffb60
ID
2815 struct extent_buffer *leaf;
2816 int slot;
c9e9f97b
ID
2817 int ret;
2818 int enospc_errors = 0;
19a39dce 2819 bool counting = true;
ec44a35c 2820
ec44a35c 2821 /* step one make some room on all the devices */
c9e9f97b 2822 devices = &fs_info->fs_devices->devices;
c6e30871 2823 list_for_each_entry(device, devices, dev_list) {
ec44a35c
CM
2824 old_size = device->total_bytes;
2825 size_to_free = div_factor(old_size, 1);
2826 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
2b82032c 2827 if (!device->writeable ||
63a212ab
SB
2828 device->total_bytes - device->bytes_used > size_to_free ||
2829 device->is_tgtdev_for_dev_replace)
ec44a35c
CM
2830 continue;
2831
2832 ret = btrfs_shrink_device(device, old_size - size_to_free);
ba1bf481
JB
2833 if (ret == -ENOSPC)
2834 break;
ec44a35c
CM
2835 BUG_ON(ret);
2836
a22285a6 2837 trans = btrfs_start_transaction(dev_root, 0);
98d5dc13 2838 BUG_ON(IS_ERR(trans));
ec44a35c
CM
2839
2840 ret = btrfs_grow_device(trans, device, old_size);
2841 BUG_ON(ret);
2842
2843 btrfs_end_transaction(trans, dev_root);
2844 }
2845
2846 /* step two, relocate all the chunks */
2847 path = btrfs_alloc_path();
17e9f796
MF
2848 if (!path) {
2849 ret = -ENOMEM;
2850 goto error;
2851 }
19a39dce
ID
2852
2853 /* zero out stat counters */
2854 spin_lock(&fs_info->balance_lock);
2855 memset(&bctl->stat, 0, sizeof(bctl->stat));
2856 spin_unlock(&fs_info->balance_lock);
2857again:
ec44a35c
CM
2858 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2859 key.offset = (u64)-1;
2860 key.type = BTRFS_CHUNK_ITEM_KEY;
2861
d397712b 2862 while (1) {
19a39dce 2863 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
a7e99c69 2864 atomic_read(&fs_info->balance_cancel_req)) {
837d5b6e
ID
2865 ret = -ECANCELED;
2866 goto error;
2867 }
2868
ec44a35c
CM
2869 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2870 if (ret < 0)
2871 goto error;
2872
2873 /*
2874 * this shouldn't happen, it means the last relocate
2875 * failed
2876 */
2877 if (ret == 0)
c9e9f97b 2878 BUG(); /* FIXME break ? */
ec44a35c
CM
2879
2880 ret = btrfs_previous_item(chunk_root, path, 0,
2881 BTRFS_CHUNK_ITEM_KEY);
c9e9f97b
ID
2882 if (ret) {
2883 ret = 0;
ec44a35c 2884 break;
c9e9f97b 2885 }
7d9eb12c 2886
f43ffb60
ID
2887 leaf = path->nodes[0];
2888 slot = path->slots[0];
2889 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7d9eb12c 2890
ec44a35c
CM
2891 if (found_key.objectid != key.objectid)
2892 break;
7d9eb12c 2893
ec44a35c 2894 /* chunk zero is special */
ba1bf481 2895 if (found_key.offset == 0)
ec44a35c
CM
2896 break;
2897
f43ffb60
ID
2898 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
2899
19a39dce
ID
2900 if (!counting) {
2901 spin_lock(&fs_info->balance_lock);
2902 bctl->stat.considered++;
2903 spin_unlock(&fs_info->balance_lock);
2904 }
2905
f43ffb60
ID
2906 ret = should_balance_chunk(chunk_root, leaf, chunk,
2907 found_key.offset);
b3b4aa74 2908 btrfs_release_path(path);
f43ffb60
ID
2909 if (!ret)
2910 goto loop;
2911
19a39dce
ID
2912 if (counting) {
2913 spin_lock(&fs_info->balance_lock);
2914 bctl->stat.expected++;
2915 spin_unlock(&fs_info->balance_lock);
2916 goto loop;
2917 }
2918
ec44a35c
CM
2919 ret = btrfs_relocate_chunk(chunk_root,
2920 chunk_root->root_key.objectid,
2921 found_key.objectid,
2922 found_key.offset);
508794eb
JB
2923 if (ret && ret != -ENOSPC)
2924 goto error;
19a39dce 2925 if (ret == -ENOSPC) {
c9e9f97b 2926 enospc_errors++;
19a39dce
ID
2927 } else {
2928 spin_lock(&fs_info->balance_lock);
2929 bctl->stat.completed++;
2930 spin_unlock(&fs_info->balance_lock);
2931 }
f43ffb60 2932loop:
ba1bf481 2933 key.offset = found_key.offset - 1;
ec44a35c 2934 }
c9e9f97b 2935
19a39dce
ID
2936 if (counting) {
2937 btrfs_release_path(path);
2938 counting = false;
2939 goto again;
2940 }
ec44a35c
CM
2941error:
2942 btrfs_free_path(path);
c9e9f97b
ID
2943 if (enospc_errors) {
2944 printk(KERN_INFO "btrfs: %d enospc errors during balance\n",
2945 enospc_errors);
2946 if (!ret)
2947 ret = -ENOSPC;
2948 }
2949
ec44a35c
CM
2950 return ret;
2951}
2952
0c460c0d
ID
2953/**
2954 * alloc_profile_is_valid - see if a given profile is valid and reduced
2955 * @flags: profile to validate
2956 * @extended: if true @flags is treated as an extended profile
2957 */
2958static int alloc_profile_is_valid(u64 flags, int extended)
2959{
2960 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
2961 BTRFS_BLOCK_GROUP_PROFILE_MASK);
2962
2963 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
2964
2965 /* 1) check that all other bits are zeroed */
2966 if (flags & ~mask)
2967 return 0;
2968
2969 /* 2) see if profile is reduced */
2970 if (flags == 0)
2971 return !extended; /* "0" is valid for usual profiles */
2972
2973 /* true if exactly one bit set */
2974 return (flags & (flags - 1)) == 0;
2975}
2976
837d5b6e
ID
2977static inline int balance_need_close(struct btrfs_fs_info *fs_info)
2978{
a7e99c69
ID
2979 /* cancel requested || normal exit path */
2980 return atomic_read(&fs_info->balance_cancel_req) ||
2981 (atomic_read(&fs_info->balance_pause_req) == 0 &&
2982 atomic_read(&fs_info->balance_cancel_req) == 0);
837d5b6e
ID
2983}
2984
c9e9f97b
ID
2985static void __cancel_balance(struct btrfs_fs_info *fs_info)
2986{
0940ebf6
ID
2987 int ret;
2988
c9e9f97b 2989 unset_balance_control(fs_info);
0940ebf6
ID
2990 ret = del_balance_item(fs_info->tree_root);
2991 BUG_ON(ret);
ed0fb78f
ID
2992
2993 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
c9e9f97b
ID
2994}
2995
19a39dce 2996void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
c9e9f97b
ID
2997 struct btrfs_ioctl_balance_args *bargs);
2998
2999/*
3000 * Should be called with both balance and volume mutexes held
3001 */
3002int btrfs_balance(struct btrfs_balance_control *bctl,
3003 struct btrfs_ioctl_balance_args *bargs)
3004{
3005 struct btrfs_fs_info *fs_info = bctl->fs_info;
f43ffb60 3006 u64 allowed;
e4837f8f 3007 int mixed = 0;
c9e9f97b 3008 int ret;
8dabb742 3009 u64 num_devices;
53b381b3 3010 int cancel = 0;
c9e9f97b 3011
837d5b6e 3012 if (btrfs_fs_closing(fs_info) ||
a7e99c69
ID
3013 atomic_read(&fs_info->balance_pause_req) ||
3014 atomic_read(&fs_info->balance_cancel_req)) {
c9e9f97b
ID
3015 ret = -EINVAL;
3016 goto out;
3017 }
3018
e4837f8f
ID
3019 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3020 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3021 mixed = 1;
3022
f43ffb60
ID
3023 /*
3024 * In case of mixed groups both data and meta should be picked,
3025 * and identical options should be given for both of them.
3026 */
e4837f8f
ID
3027 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3028 if (mixed && (bctl->flags & allowed)) {
f43ffb60
ID
3029 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3030 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3031 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3032 printk(KERN_ERR "btrfs: with mixed groups data and "
3033 "metadata balance options must be the same\n");
3034 ret = -EINVAL;
3035 goto out;
3036 }
3037 }
3038
8dabb742
SB
3039 num_devices = fs_info->fs_devices->num_devices;
3040 btrfs_dev_replace_lock(&fs_info->dev_replace);
3041 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3042 BUG_ON(num_devices < 1);
3043 num_devices--;
3044 }
3045 btrfs_dev_replace_unlock(&fs_info->dev_replace);
e4d8ec0f 3046 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
8dabb742 3047 if (num_devices == 1)
e4d8ec0f 3048 allowed |= BTRFS_BLOCK_GROUP_DUP;
8dabb742 3049 else if (num_devices < 4)
e4d8ec0f
ID
3050 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3051 else
3052 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
3053 BTRFS_BLOCK_GROUP_RAID10 |
3054 BTRFS_BLOCK_GROUP_RAID5 |
3055 BTRFS_BLOCK_GROUP_RAID6);
e4d8ec0f 3056
6728b198
ID
3057 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3058 (!alloc_profile_is_valid(bctl->data.target, 1) ||
3059 (bctl->data.target & ~allowed))) {
e4d8ec0f
ID
3060 printk(KERN_ERR "btrfs: unable to start balance with target "
3061 "data profile %llu\n",
3062 (unsigned long long)bctl->data.target);
3063 ret = -EINVAL;
3064 goto out;
3065 }
6728b198
ID
3066 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3067 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
3068 (bctl->meta.target & ~allowed))) {
e4d8ec0f
ID
3069 printk(KERN_ERR "btrfs: unable to start balance with target "
3070 "metadata profile %llu\n",
3071 (unsigned long long)bctl->meta.target);
3072 ret = -EINVAL;
3073 goto out;
3074 }
6728b198
ID
3075 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3076 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
3077 (bctl->sys.target & ~allowed))) {
e4d8ec0f
ID
3078 printk(KERN_ERR "btrfs: unable to start balance with target "
3079 "system profile %llu\n",
3080 (unsigned long long)bctl->sys.target);
3081 ret = -EINVAL;
3082 goto out;
3083 }
3084
e4837f8f
ID
3085 /* allow dup'ed data chunks only in mixed mode */
3086 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
6728b198 3087 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
e4d8ec0f
ID
3088 printk(KERN_ERR "btrfs: dup for data is not allowed\n");
3089 ret = -EINVAL;
3090 goto out;
3091 }
3092
3093 /* allow to reduce meta or sys integrity only if force set */
3094 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
3095 BTRFS_BLOCK_GROUP_RAID10 |
3096 BTRFS_BLOCK_GROUP_RAID5 |
3097 BTRFS_BLOCK_GROUP_RAID6;
3098
e4d8ec0f
ID
3099 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3100 (fs_info->avail_system_alloc_bits & allowed) &&
3101 !(bctl->sys.target & allowed)) ||
3102 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3103 (fs_info->avail_metadata_alloc_bits & allowed) &&
3104 !(bctl->meta.target & allowed))) {
3105 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3106 printk(KERN_INFO "btrfs: force reducing metadata "
3107 "integrity\n");
3108 } else {
3109 printk(KERN_ERR "btrfs: balance will reduce metadata "
3110 "integrity, use force if you want this\n");
3111 ret = -EINVAL;
3112 goto out;
3113 }
3114 }
3115
5af3e8cc
SB
3116 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3117 int num_tolerated_disk_barrier_failures;
3118 u64 target = bctl->sys.target;
3119
3120 num_tolerated_disk_barrier_failures =
3121 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3122 if (num_tolerated_disk_barrier_failures > 0 &&
3123 (target &
3124 (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3125 BTRFS_AVAIL_ALLOC_BIT_SINGLE)))
3126 num_tolerated_disk_barrier_failures = 0;
3127 else if (num_tolerated_disk_barrier_failures > 1 &&
3128 (target &
3129 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)))
3130 num_tolerated_disk_barrier_failures = 1;
3131
3132 fs_info->num_tolerated_disk_barrier_failures =
3133 num_tolerated_disk_barrier_failures;
3134 }
3135
0940ebf6 3136 ret = insert_balance_item(fs_info->tree_root, bctl);
59641015 3137 if (ret && ret != -EEXIST)
0940ebf6
ID
3138 goto out;
3139
59641015
ID
3140 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3141 BUG_ON(ret == -EEXIST);
3142 set_balance_control(bctl);
3143 } else {
3144 BUG_ON(ret != -EEXIST);
3145 spin_lock(&fs_info->balance_lock);
3146 update_balance_args(bctl);
3147 spin_unlock(&fs_info->balance_lock);
3148 }
c9e9f97b 3149
837d5b6e 3150 atomic_inc(&fs_info->balance_running);
c9e9f97b
ID
3151 mutex_unlock(&fs_info->balance_mutex);
3152
3153 ret = __btrfs_balance(fs_info);
3154
3155 mutex_lock(&fs_info->balance_mutex);
837d5b6e 3156 atomic_dec(&fs_info->balance_running);
c9e9f97b
ID
3157
3158 if (bargs) {
3159 memset(bargs, 0, sizeof(*bargs));
19a39dce 3160 update_ioctl_balance_args(fs_info, 0, bargs);
c9e9f97b
ID
3161 }
3162
837d5b6e 3163 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
53b381b3
DW
3164 balance_need_close(fs_info))
3165 cancel = 1;
837d5b6e 3166
5af3e8cc
SB
3167 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3168 fs_info->num_tolerated_disk_barrier_failures =
3169 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3170 }
3171
53b381b3
DW
3172 if (cancel)
3173 __cancel_balance(fs_info);
3174
837d5b6e 3175 wake_up(&fs_info->balance_wait_q);
c9e9f97b
ID
3176
3177 return ret;
3178out:
59641015
ID
3179 if (bctl->flags & BTRFS_BALANCE_RESUME)
3180 __cancel_balance(fs_info);
ed0fb78f 3181 else {
59641015 3182 kfree(bctl);
ed0fb78f
ID
3183 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3184 }
59641015
ID
3185 return ret;
3186}
3187
3188static int balance_kthread(void *data)
3189{
2b6ba629 3190 struct btrfs_fs_info *fs_info = data;
9555c6c1 3191 int ret = 0;
59641015
ID
3192
3193 mutex_lock(&fs_info->volume_mutex);
3194 mutex_lock(&fs_info->balance_mutex);
3195
2b6ba629 3196 if (fs_info->balance_ctl) {
9555c6c1 3197 printk(KERN_INFO "btrfs: continuing balance\n");
2b6ba629 3198 ret = btrfs_balance(fs_info->balance_ctl, NULL);
9555c6c1 3199 }
59641015
ID
3200
3201 mutex_unlock(&fs_info->balance_mutex);
3202 mutex_unlock(&fs_info->volume_mutex);
2b6ba629 3203
59641015
ID
3204 return ret;
3205}
3206
2b6ba629
ID
3207int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3208{
3209 struct task_struct *tsk;
3210
3211 spin_lock(&fs_info->balance_lock);
3212 if (!fs_info->balance_ctl) {
3213 spin_unlock(&fs_info->balance_lock);
3214 return 0;
3215 }
3216 spin_unlock(&fs_info->balance_lock);
3217
3218 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3219 printk(KERN_INFO "btrfs: force skipping balance\n");
3220 return 0;
3221 }
3222
3223 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3224 if (IS_ERR(tsk))
3225 return PTR_ERR(tsk);
3226
3227 return 0;
3228}
3229
68310a5e 3230int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
59641015 3231{
59641015
ID
3232 struct btrfs_balance_control *bctl;
3233 struct btrfs_balance_item *item;
3234 struct btrfs_disk_balance_args disk_bargs;
3235 struct btrfs_path *path;
3236 struct extent_buffer *leaf;
3237 struct btrfs_key key;
3238 int ret;
3239
3240 path = btrfs_alloc_path();
3241 if (!path)
3242 return -ENOMEM;
3243
59641015
ID
3244 key.objectid = BTRFS_BALANCE_OBJECTID;
3245 key.type = BTRFS_BALANCE_ITEM_KEY;
3246 key.offset = 0;
3247
68310a5e 3248 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
59641015 3249 if (ret < 0)
68310a5e 3250 goto out;
59641015
ID
3251 if (ret > 0) { /* ret = -ENOENT; */
3252 ret = 0;
68310a5e
ID
3253 goto out;
3254 }
3255
3256 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3257 if (!bctl) {
3258 ret = -ENOMEM;
3259 goto out;
59641015
ID
3260 }
3261
3262 leaf = path->nodes[0];
3263 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3264
68310a5e
ID
3265 bctl->fs_info = fs_info;
3266 bctl->flags = btrfs_balance_flags(leaf, item);
3267 bctl->flags |= BTRFS_BALANCE_RESUME;
59641015
ID
3268
3269 btrfs_balance_data(leaf, item, &disk_bargs);
3270 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3271 btrfs_balance_meta(leaf, item, &disk_bargs);
3272 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3273 btrfs_balance_sys(leaf, item, &disk_bargs);
3274 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3275
ed0fb78f
ID
3276 WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3277
68310a5e
ID
3278 mutex_lock(&fs_info->volume_mutex);
3279 mutex_lock(&fs_info->balance_mutex);
59641015 3280
68310a5e
ID
3281 set_balance_control(bctl);
3282
3283 mutex_unlock(&fs_info->balance_mutex);
3284 mutex_unlock(&fs_info->volume_mutex);
59641015
ID
3285out:
3286 btrfs_free_path(path);
ec44a35c
CM
3287 return ret;
3288}
3289
837d5b6e
ID
3290int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3291{
3292 int ret = 0;
3293
3294 mutex_lock(&fs_info->balance_mutex);
3295 if (!fs_info->balance_ctl) {
3296 mutex_unlock(&fs_info->balance_mutex);
3297 return -ENOTCONN;
3298 }
3299
3300 if (atomic_read(&fs_info->balance_running)) {
3301 atomic_inc(&fs_info->balance_pause_req);
3302 mutex_unlock(&fs_info->balance_mutex);
3303
3304 wait_event(fs_info->balance_wait_q,
3305 atomic_read(&fs_info->balance_running) == 0);
3306
3307 mutex_lock(&fs_info->balance_mutex);
3308 /* we are good with balance_ctl ripped off from under us */
3309 BUG_ON(atomic_read(&fs_info->balance_running));
3310 atomic_dec(&fs_info->balance_pause_req);
3311 } else {
3312 ret = -ENOTCONN;
3313 }
3314
3315 mutex_unlock(&fs_info->balance_mutex);
3316 return ret;
3317}
3318
a7e99c69
ID
3319int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3320{
3321 mutex_lock(&fs_info->balance_mutex);
3322 if (!fs_info->balance_ctl) {
3323 mutex_unlock(&fs_info->balance_mutex);
3324 return -ENOTCONN;
3325 }
3326
3327 atomic_inc(&fs_info->balance_cancel_req);
3328 /*
3329 * if we are running just wait and return, balance item is
3330 * deleted in btrfs_balance in this case
3331 */
3332 if (atomic_read(&fs_info->balance_running)) {
3333 mutex_unlock(&fs_info->balance_mutex);
3334 wait_event(fs_info->balance_wait_q,
3335 atomic_read(&fs_info->balance_running) == 0);
3336 mutex_lock(&fs_info->balance_mutex);
3337 } else {
3338 /* __cancel_balance needs volume_mutex */
3339 mutex_unlock(&fs_info->balance_mutex);
3340 mutex_lock(&fs_info->volume_mutex);
3341 mutex_lock(&fs_info->balance_mutex);
3342
3343 if (fs_info->balance_ctl)
3344 __cancel_balance(fs_info);
3345
3346 mutex_unlock(&fs_info->volume_mutex);
3347 }
3348
3349 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3350 atomic_dec(&fs_info->balance_cancel_req);
3351 mutex_unlock(&fs_info->balance_mutex);
3352 return 0;
3353}
3354
8f18cf13
CM
3355/*
3356 * shrinking a device means finding all of the device extents past
3357 * the new size, and then following the back refs to the chunks.
3358 * The chunk relocation code actually frees the device extent
3359 */
3360int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
3361{
3362 struct btrfs_trans_handle *trans;
3363 struct btrfs_root *root = device->dev_root;
3364 struct btrfs_dev_extent *dev_extent = NULL;
3365 struct btrfs_path *path;
3366 u64 length;
3367 u64 chunk_tree;
3368 u64 chunk_objectid;
3369 u64 chunk_offset;
3370 int ret;
3371 int slot;
ba1bf481
JB
3372 int failed = 0;
3373 bool retried = false;
8f18cf13
CM
3374 struct extent_buffer *l;
3375 struct btrfs_key key;
6c41761f 3376 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
8f18cf13 3377 u64 old_total = btrfs_super_total_bytes(super_copy);
ba1bf481 3378 u64 old_size = device->total_bytes;
8f18cf13
CM
3379 u64 diff = device->total_bytes - new_size;
3380
63a212ab
SB
3381 if (device->is_tgtdev_for_dev_replace)
3382 return -EINVAL;
3383
8f18cf13
CM
3384 path = btrfs_alloc_path();
3385 if (!path)
3386 return -ENOMEM;
3387
8f18cf13
CM
3388 path->reada = 2;
3389
7d9eb12c
CM
3390 lock_chunks(root);
3391
8f18cf13 3392 device->total_bytes = new_size;
2bf64758 3393 if (device->writeable) {
2b82032c 3394 device->fs_devices->total_rw_bytes -= diff;
2bf64758
JB
3395 spin_lock(&root->fs_info->free_chunk_lock);
3396 root->fs_info->free_chunk_space -= diff;
3397 spin_unlock(&root->fs_info->free_chunk_lock);
3398 }
7d9eb12c 3399 unlock_chunks(root);
8f18cf13 3400
ba1bf481 3401again:
8f18cf13
CM
3402 key.objectid = device->devid;
3403 key.offset = (u64)-1;
3404 key.type = BTRFS_DEV_EXTENT_KEY;
3405
213e64da 3406 do {
8f18cf13
CM
3407 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3408 if (ret < 0)
3409 goto done;
3410
3411 ret = btrfs_previous_item(root, path, 0, key.type);
3412 if (ret < 0)
3413 goto done;
3414 if (ret) {
3415 ret = 0;
b3b4aa74 3416 btrfs_release_path(path);
bf1fb512 3417 break;
8f18cf13
CM
3418 }
3419
3420 l = path->nodes[0];
3421 slot = path->slots[0];
3422 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
3423
ba1bf481 3424 if (key.objectid != device->devid) {
b3b4aa74 3425 btrfs_release_path(path);
bf1fb512 3426 break;
ba1bf481 3427 }
8f18cf13
CM
3428
3429 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3430 length = btrfs_dev_extent_length(l, dev_extent);
3431
ba1bf481 3432 if (key.offset + length <= new_size) {
b3b4aa74 3433 btrfs_release_path(path);
d6397bae 3434 break;
ba1bf481 3435 }
8f18cf13
CM
3436
3437 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
3438 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3439 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
b3b4aa74 3440 btrfs_release_path(path);
8f18cf13
CM
3441
3442 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
3443 chunk_offset);
ba1bf481 3444 if (ret && ret != -ENOSPC)
8f18cf13 3445 goto done;
ba1bf481
JB
3446 if (ret == -ENOSPC)
3447 failed++;
213e64da 3448 } while (key.offset-- > 0);
ba1bf481
JB
3449
3450 if (failed && !retried) {
3451 failed = 0;
3452 retried = true;
3453 goto again;
3454 } else if (failed && retried) {
3455 ret = -ENOSPC;
3456 lock_chunks(root);
3457
3458 device->total_bytes = old_size;
3459 if (device->writeable)
3460 device->fs_devices->total_rw_bytes += diff;
2bf64758
JB
3461 spin_lock(&root->fs_info->free_chunk_lock);
3462 root->fs_info->free_chunk_space += diff;
3463 spin_unlock(&root->fs_info->free_chunk_lock);
ba1bf481
JB
3464 unlock_chunks(root);
3465 goto done;
8f18cf13
CM
3466 }
3467
d6397bae 3468 /* Shrinking succeeded, else we would be at "done". */
a22285a6 3469 trans = btrfs_start_transaction(root, 0);
98d5dc13
TI
3470 if (IS_ERR(trans)) {
3471 ret = PTR_ERR(trans);
3472 goto done;
3473 }
3474
d6397bae
CB
3475 lock_chunks(root);
3476
3477 device->disk_total_bytes = new_size;
3478 /* Now btrfs_update_device() will change the on-disk size. */
3479 ret = btrfs_update_device(trans, device);
3480 if (ret) {
3481 unlock_chunks(root);
3482 btrfs_end_transaction(trans, root);
3483 goto done;
3484 }
3485 WARN_ON(diff > old_total);
3486 btrfs_set_super_total_bytes(super_copy, old_total - diff);
3487 unlock_chunks(root);
3488 btrfs_end_transaction(trans, root);
8f18cf13
CM
3489done:
3490 btrfs_free_path(path);
3491 return ret;
3492}
3493
125ccb0a 3494static int btrfs_add_system_chunk(struct btrfs_root *root,
0b86a832
CM
3495 struct btrfs_key *key,
3496 struct btrfs_chunk *chunk, int item_size)
3497{
6c41761f 3498 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
0b86a832
CM
3499 struct btrfs_disk_key disk_key;
3500 u32 array_size;
3501 u8 *ptr;
3502
3503 array_size = btrfs_super_sys_array_size(super_copy);
3504 if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
3505 return -EFBIG;
3506
3507 ptr = super_copy->sys_chunk_array + array_size;
3508 btrfs_cpu_key_to_disk(&disk_key, key);
3509 memcpy(ptr, &disk_key, sizeof(disk_key));
3510 ptr += sizeof(disk_key);
3511 memcpy(ptr, chunk, item_size);
3512 item_size += sizeof(disk_key);
3513 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
3514 return 0;
3515}
3516
73c5de00
AJ
3517/*
3518 * sort the devices in descending order by max_avail, total_avail
3519 */
3520static int btrfs_cmp_device_info(const void *a, const void *b)
9b3f68b9 3521{
73c5de00
AJ
3522 const struct btrfs_device_info *di_a = a;
3523 const struct btrfs_device_info *di_b = b;
9b3f68b9 3524
73c5de00 3525 if (di_a->max_avail > di_b->max_avail)
b2117a39 3526 return -1;
73c5de00 3527 if (di_a->max_avail < di_b->max_avail)
b2117a39 3528 return 1;
73c5de00
AJ
3529 if (di_a->total_avail > di_b->total_avail)
3530 return -1;
3531 if (di_a->total_avail < di_b->total_avail)
3532 return 1;
3533 return 0;
b2117a39 3534}
0b86a832 3535
31e50229 3536struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
53b381b3
DW
3537 /*
3538 * sub_stripes info for map,
3539 * dev_stripes -- stripes per dev, 2 for DUP, 1 other wise
3540 * devs_max -- max devices per stripe, 0 for unlimited
3541 * devs_min -- min devices per stripe
3542 * devs_increment -- ndevs must be a multiple of this
3543 * ncopies -- how many copies of the data we have
3544 */
31e50229
LB
3545 { 2, 1, 0, 4, 2, 2 /* raid10 */ },
3546 { 1, 1, 2, 2, 2, 2 /* raid1 */ },
3547 { 1, 2, 1, 1, 1, 2 /* dup */ },
3548 { 1, 1, 0, 2, 1, 1 /* raid0 */ },
c9f01bfe 3549 { 1, 1, 1, 1, 1, 1 /* single */ },
53b381b3
DW
3550 { 1, 1, 0, 2, 1, 2 /* raid5 */ },
3551 { 1, 1, 0, 3, 1, 3 /* raid6 */ },
31e50229
LB
3552};
3553
53b381b3
DW
3554static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
3555{
3556 /* TODO allow them to set a preferred stripe size */
3557 return 64 * 1024;
3558}
3559
3560static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
3561{
3562 u64 features;
3563
3564 if (!(type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)))
3565 return;
3566
3567 features = btrfs_super_incompat_flags(info->super_copy);
3568 if (features & BTRFS_FEATURE_INCOMPAT_RAID56)
3569 return;
3570
3571 features |= BTRFS_FEATURE_INCOMPAT_RAID56;
3572 btrfs_set_super_incompat_flags(info->super_copy, features);
3573 printk(KERN_INFO "btrfs: setting RAID5/6 feature flag\n");
3574}
3575
73c5de00
AJ
3576static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3577 struct btrfs_root *extent_root,
3578 struct map_lookup **map_ret,
3579 u64 *num_bytes_out, u64 *stripe_size_out,
3580 u64 start, u64 type)
b2117a39 3581{
73c5de00
AJ
3582 struct btrfs_fs_info *info = extent_root->fs_info;
3583 struct btrfs_fs_devices *fs_devices = info->fs_devices;
3584 struct list_head *cur;
3585 struct map_lookup *map = NULL;
3586 struct extent_map_tree *em_tree;
3587 struct extent_map *em;
3588 struct btrfs_device_info *devices_info = NULL;
3589 u64 total_avail;
3590 int num_stripes; /* total number of stripes to allocate */
53b381b3
DW
3591 int data_stripes; /* number of stripes that count for
3592 block group size */
73c5de00
AJ
3593 int sub_stripes; /* sub_stripes info for map */
3594 int dev_stripes; /* stripes per dev */
3595 int devs_max; /* max devs to use */
3596 int devs_min; /* min devs needed */
3597 int devs_increment; /* ndevs has to be a multiple of this */
3598 int ncopies; /* how many copies to data has */
3599 int ret;
3600 u64 max_stripe_size;
3601 u64 max_chunk_size;
3602 u64 stripe_size;
3603 u64 num_bytes;
53b381b3 3604 u64 raid_stripe_len = BTRFS_STRIPE_LEN;
73c5de00
AJ
3605 int ndevs;
3606 int i;
3607 int j;
31e50229 3608 int index;
593060d7 3609
0c460c0d 3610 BUG_ON(!alloc_profile_is_valid(type, 0));
9b3f68b9 3611
73c5de00
AJ
3612 if (list_empty(&fs_devices->alloc_list))
3613 return -ENOSPC;
b2117a39 3614
31e50229 3615 index = __get_raid_index(type);
73c5de00 3616
31e50229
LB
3617 sub_stripes = btrfs_raid_array[index].sub_stripes;
3618 dev_stripes = btrfs_raid_array[index].dev_stripes;
3619 devs_max = btrfs_raid_array[index].devs_max;
3620 devs_min = btrfs_raid_array[index].devs_min;
3621 devs_increment = btrfs_raid_array[index].devs_increment;
3622 ncopies = btrfs_raid_array[index].ncopies;
b2117a39 3623
9b3f68b9 3624 if (type & BTRFS_BLOCK_GROUP_DATA) {
73c5de00
AJ
3625 max_stripe_size = 1024 * 1024 * 1024;
3626 max_chunk_size = 10 * max_stripe_size;
9b3f68b9 3627 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
1100373f
CM
3628 /* for larger filesystems, use larger metadata chunks */
3629 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
3630 max_stripe_size = 1024 * 1024 * 1024;
3631 else
3632 max_stripe_size = 256 * 1024 * 1024;
73c5de00 3633 max_chunk_size = max_stripe_size;
a40a90a0 3634 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
96bdc7dc 3635 max_stripe_size = 32 * 1024 * 1024;
73c5de00
AJ
3636 max_chunk_size = 2 * max_stripe_size;
3637 } else {
3638 printk(KERN_ERR "btrfs: invalid chunk type 0x%llx requested\n",
3639 type);
3640 BUG_ON(1);
9b3f68b9
CM
3641 }
3642
2b82032c
YZ
3643 /* we don't want a chunk larger than 10% of writeable space */
3644 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
3645 max_chunk_size);
9b3f68b9 3646
73c5de00
AJ
3647 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
3648 GFP_NOFS);
3649 if (!devices_info)
3650 return -ENOMEM;
0cad8a11 3651
73c5de00 3652 cur = fs_devices->alloc_list.next;
9b3f68b9 3653
9f680ce0 3654 /*
73c5de00
AJ
3655 * in the first pass through the devices list, we gather information
3656 * about the available holes on each device.
9f680ce0 3657 */
73c5de00
AJ
3658 ndevs = 0;
3659 while (cur != &fs_devices->alloc_list) {
3660 struct btrfs_device *device;
3661 u64 max_avail;
3662 u64 dev_offset;
b2117a39 3663
73c5de00 3664 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
9f680ce0 3665
73c5de00 3666 cur = cur->next;
b2117a39 3667
73c5de00 3668 if (!device->writeable) {
31b1a2bd 3669 WARN(1, KERN_ERR
73c5de00 3670 "btrfs: read-only device in alloc_list\n");
73c5de00
AJ
3671 continue;
3672 }
b2117a39 3673
63a212ab
SB
3674 if (!device->in_fs_metadata ||
3675 device->is_tgtdev_for_dev_replace)
73c5de00 3676 continue;
b2117a39 3677
73c5de00
AJ
3678 if (device->total_bytes > device->bytes_used)
3679 total_avail = device->total_bytes - device->bytes_used;
3680 else
3681 total_avail = 0;
38c01b96 3682
3683 /* If there is no space on this device, skip it. */
3684 if (total_avail == 0)
3685 continue;
b2117a39 3686
125ccb0a 3687 ret = find_free_dev_extent(device,
73c5de00
AJ
3688 max_stripe_size * dev_stripes,
3689 &dev_offset, &max_avail);
3690 if (ret && ret != -ENOSPC)
3691 goto error;
b2117a39 3692
73c5de00
AJ
3693 if (ret == 0)
3694 max_avail = max_stripe_size * dev_stripes;
b2117a39 3695
73c5de00
AJ
3696 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
3697 continue;
b2117a39 3698
73c5de00
AJ
3699 devices_info[ndevs].dev_offset = dev_offset;
3700 devices_info[ndevs].max_avail = max_avail;
3701 devices_info[ndevs].total_avail = total_avail;
3702 devices_info[ndevs].dev = device;
3703 ++ndevs;
8dabb742 3704 WARN_ON(ndevs > fs_devices->rw_devices);
73c5de00 3705 }
b2117a39 3706
73c5de00
AJ
3707 /*
3708 * now sort the devices by hole size / available space
3709 */
3710 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
3711 btrfs_cmp_device_info, NULL);
b2117a39 3712
73c5de00
AJ
3713 /* round down to number of usable stripes */
3714 ndevs -= ndevs % devs_increment;
b2117a39 3715
73c5de00
AJ
3716 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
3717 ret = -ENOSPC;
3718 goto error;
b2117a39 3719 }
9f680ce0 3720
73c5de00
AJ
3721 if (devs_max && ndevs > devs_max)
3722 ndevs = devs_max;
3723 /*
3724 * the primary goal is to maximize the number of stripes, so use as many
3725 * devices as possible, even if the stripes are not maximum sized.
3726 */
3727 stripe_size = devices_info[ndevs-1].max_avail;
3728 num_stripes = ndevs * dev_stripes;
b2117a39 3729
53b381b3
DW
3730 /*
3731 * this will have to be fixed for RAID1 and RAID10 over
3732 * more drives
3733 */
3734 data_stripes = num_stripes / ncopies;
3735
37db63a4 3736 if (stripe_size * ndevs > max_chunk_size * ncopies) {
73c5de00 3737 stripe_size = max_chunk_size * ncopies;
37db63a4 3738 do_div(stripe_size, ndevs);
b2117a39 3739 }
53b381b3
DW
3740 if (type & BTRFS_BLOCK_GROUP_RAID5) {
3741 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
3742 btrfs_super_stripesize(info->super_copy));
3743 data_stripes = num_stripes - 1;
3744 }
3745 if (type & BTRFS_BLOCK_GROUP_RAID6) {
3746 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
3747 btrfs_super_stripesize(info->super_copy));
3748 data_stripes = num_stripes - 2;
3749 }
73c5de00 3750 do_div(stripe_size, dev_stripes);
37db63a4
ID
3751
3752 /* align to BTRFS_STRIPE_LEN */
53b381b3
DW
3753 do_div(stripe_size, raid_stripe_len);
3754 stripe_size *= raid_stripe_len;
b2117a39
MX
3755
3756 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
3757 if (!map) {
3758 ret = -ENOMEM;
3759 goto error;
3760 }
3761 map->num_stripes = num_stripes;
9b3f68b9 3762
73c5de00
AJ
3763 for (i = 0; i < ndevs; ++i) {
3764 for (j = 0; j < dev_stripes; ++j) {
3765 int s = i * dev_stripes + j;
3766 map->stripes[s].dev = devices_info[i].dev;
3767 map->stripes[s].physical = devices_info[i].dev_offset +
3768 j * stripe_size;
6324fbf3 3769 }
6324fbf3 3770 }
2b82032c 3771 map->sector_size = extent_root->sectorsize;
53b381b3
DW
3772 map->stripe_len = raid_stripe_len;
3773 map->io_align = raid_stripe_len;
3774 map->io_width = raid_stripe_len;
2b82032c 3775 map->type = type;
2b82032c 3776 map->sub_stripes = sub_stripes;
0b86a832 3777
2b82032c 3778 *map_ret = map;
53b381b3 3779 num_bytes = stripe_size * data_stripes;
0b86a832 3780
73c5de00
AJ
3781 *stripe_size_out = stripe_size;
3782 *num_bytes_out = num_bytes;
0b86a832 3783
73c5de00 3784 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
1abe9b8a 3785
172ddd60 3786 em = alloc_extent_map();
2b82032c 3787 if (!em) {
b2117a39
MX
3788 ret = -ENOMEM;
3789 goto error;
593060d7 3790 }
2b82032c
YZ
3791 em->bdev = (struct block_device *)map;
3792 em->start = start;
73c5de00 3793 em->len = num_bytes;
2b82032c
YZ
3794 em->block_start = 0;
3795 em->block_len = em->len;
593060d7 3796
2b82032c 3797 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
890871be 3798 write_lock(&em_tree->lock);
2b82032c 3799 ret = add_extent_mapping(em_tree, em);
890871be 3800 write_unlock(&em_tree->lock);
2b82032c 3801 free_extent_map(em);
1dd4602f
MF
3802 if (ret)
3803 goto error;
0b86a832 3804
2b82032c
YZ
3805 ret = btrfs_make_block_group(trans, extent_root, 0, type,
3806 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
73c5de00 3807 start, num_bytes);
79787eaa
JM
3808 if (ret)
3809 goto error;
611f0e00 3810
73c5de00
AJ
3811 for (i = 0; i < map->num_stripes; ++i) {
3812 struct btrfs_device *device;
3813 u64 dev_offset;
3814
3815 device = map->stripes[i].dev;
3816 dev_offset = map->stripes[i].physical;
0b86a832
CM
3817
3818 ret = btrfs_alloc_dev_extent(trans, device,
2b82032c
YZ
3819 info->chunk_root->root_key.objectid,
3820 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
73c5de00 3821 start, dev_offset, stripe_size);
79787eaa
JM
3822 if (ret) {
3823 btrfs_abort_transaction(trans, extent_root, ret);
3824 goto error;
3825 }
2b82032c
YZ
3826 }
3827
53b381b3
DW
3828 check_raid56_incompat_flag(extent_root->fs_info, type);
3829
b2117a39 3830 kfree(devices_info);
2b82032c 3831 return 0;
b2117a39
MX
3832
3833error:
3834 kfree(map);
3835 kfree(devices_info);
3836 return ret;
2b82032c
YZ
3837}
3838
3839static int __finish_chunk_alloc(struct btrfs_trans_handle *trans,
3840 struct btrfs_root *extent_root,
3841 struct map_lookup *map, u64 chunk_offset,
3842 u64 chunk_size, u64 stripe_size)
3843{
3844 u64 dev_offset;
3845 struct btrfs_key key;
3846 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
3847 struct btrfs_device *device;
3848 struct btrfs_chunk *chunk;
3849 struct btrfs_stripe *stripe;
3850 size_t item_size = btrfs_chunk_item_size(map->num_stripes);
3851 int index = 0;
3852 int ret;
3853
3854 chunk = kzalloc(item_size, GFP_NOFS);
3855 if (!chunk)
3856 return -ENOMEM;
3857
3858 index = 0;
3859 while (index < map->num_stripes) {
3860 device = map->stripes[index].dev;
3861 device->bytes_used += stripe_size;
0b86a832 3862 ret = btrfs_update_device(trans, device);
3acd3953
MF
3863 if (ret)
3864 goto out_free;
2b82032c
YZ
3865 index++;
3866 }
3867
2bf64758
JB
3868 spin_lock(&extent_root->fs_info->free_chunk_lock);
3869 extent_root->fs_info->free_chunk_space -= (stripe_size *
3870 map->num_stripes);
3871 spin_unlock(&extent_root->fs_info->free_chunk_lock);
3872
2b82032c
YZ
3873 index = 0;
3874 stripe = &chunk->stripe;
3875 while (index < map->num_stripes) {
3876 device = map->stripes[index].dev;
3877 dev_offset = map->stripes[index].physical;
0b86a832 3878
e17cade2
CM
3879 btrfs_set_stack_stripe_devid(stripe, device->devid);
3880 btrfs_set_stack_stripe_offset(stripe, dev_offset);
3881 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
2b82032c 3882 stripe++;
0b86a832
CM
3883 index++;
3884 }
3885
2b82032c 3886 btrfs_set_stack_chunk_length(chunk, chunk_size);
0b86a832 3887 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
2b82032c
YZ
3888 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
3889 btrfs_set_stack_chunk_type(chunk, map->type);
3890 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
3891 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
3892 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
0b86a832 3893 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
2b82032c 3894 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
0b86a832 3895
2b82032c
YZ
3896 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3897 key.type = BTRFS_CHUNK_ITEM_KEY;
3898 key.offset = chunk_offset;
0b86a832 3899
2b82032c 3900 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
0b86a832 3901
4ed1d16e
MF
3902 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3903 /*
3904 * TODO: Cleanup of inserted chunk root in case of
3905 * failure.
3906 */
125ccb0a 3907 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
2b82032c 3908 item_size);
8f18cf13 3909 }
1abe9b8a 3910
3acd3953 3911out_free:
0b86a832 3912 kfree(chunk);
4ed1d16e 3913 return ret;
2b82032c 3914}
0b86a832 3915
2b82032c
YZ
3916/*
3917 * Chunk allocation falls into two parts. The first part does works
3918 * that make the new allocated chunk useable, but not do any operation
3919 * that modifies the chunk tree. The second part does the works that
3920 * require modifying the chunk tree. This division is important for the
3921 * bootstrap process of adding storage to a seed btrfs.
3922 */
3923int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3924 struct btrfs_root *extent_root, u64 type)
3925{
3926 u64 chunk_offset;
3927 u64 chunk_size;
3928 u64 stripe_size;
3929 struct map_lookup *map;
3930 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
3931 int ret;
3932
3933 ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
3934 &chunk_offset);
3935 if (ret)
3936 return ret;
3937
3938 ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
3939 &stripe_size, chunk_offset, type);
3940 if (ret)
3941 return ret;
3942
3943 ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
3944 chunk_size, stripe_size);
79787eaa
JM
3945 if (ret)
3946 return ret;
2b82032c
YZ
3947 return 0;
3948}
3949
d397712b 3950static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
2b82032c
YZ
3951 struct btrfs_root *root,
3952 struct btrfs_device *device)
3953{
3954 u64 chunk_offset;
3955 u64 sys_chunk_offset;
3956 u64 chunk_size;
3957 u64 sys_chunk_size;
3958 u64 stripe_size;
3959 u64 sys_stripe_size;
3960 u64 alloc_profile;
3961 struct map_lookup *map;
3962 struct map_lookup *sys_map;
3963 struct btrfs_fs_info *fs_info = root->fs_info;
3964 struct btrfs_root *extent_root = fs_info->extent_root;
3965 int ret;
3966
3967 ret = find_next_chunk(fs_info->chunk_root,
3968 BTRFS_FIRST_CHUNK_TREE_OBJECTID, &chunk_offset);
92b8e897
MF
3969 if (ret)
3970 return ret;
2b82032c
YZ
3971
3972 alloc_profile = BTRFS_BLOCK_GROUP_METADATA |
6fef8df1 3973 fs_info->avail_metadata_alloc_bits;
2b82032c
YZ
3974 alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
3975
3976 ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
3977 &stripe_size, chunk_offset, alloc_profile);
79787eaa
JM
3978 if (ret)
3979 return ret;
2b82032c
YZ
3980
3981 sys_chunk_offset = chunk_offset + chunk_size;
3982
3983 alloc_profile = BTRFS_BLOCK_GROUP_SYSTEM |
6fef8df1 3984 fs_info->avail_system_alloc_bits;
2b82032c
YZ
3985 alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
3986
3987 ret = __btrfs_alloc_chunk(trans, extent_root, &sys_map,
3988 &sys_chunk_size, &sys_stripe_size,
3989 sys_chunk_offset, alloc_profile);
005d6427
DS
3990 if (ret) {
3991 btrfs_abort_transaction(trans, root, ret);
3992 goto out;
3993 }
2b82032c
YZ
3994
3995 ret = btrfs_add_device(trans, fs_info->chunk_root, device);
005d6427
DS
3996 if (ret) {
3997 btrfs_abort_transaction(trans, root, ret);
3998 goto out;
3999 }
2b82032c
YZ
4000
4001 /*
4002 * Modifying chunk tree needs allocating new blocks from both
4003 * system block group and metadata block group. So we only can
4004 * do operations require modifying the chunk tree after both
4005 * block groups were created.
4006 */
4007 ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
4008 chunk_size, stripe_size);
005d6427
DS
4009 if (ret) {
4010 btrfs_abort_transaction(trans, root, ret);
4011 goto out;
4012 }
2b82032c
YZ
4013
4014 ret = __finish_chunk_alloc(trans, extent_root, sys_map,
4015 sys_chunk_offset, sys_chunk_size,
4016 sys_stripe_size);
79787eaa 4017 if (ret)
005d6427 4018 btrfs_abort_transaction(trans, root, ret);
79787eaa 4019
005d6427 4020out:
79787eaa 4021
79787eaa 4022 return ret;
2b82032c
YZ
4023}
4024
4025int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4026{
4027 struct extent_map *em;
4028 struct map_lookup *map;
4029 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4030 int readonly = 0;
4031 int i;
4032
890871be 4033 read_lock(&map_tree->map_tree.lock);
2b82032c 4034 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
890871be 4035 read_unlock(&map_tree->map_tree.lock);
2b82032c
YZ
4036 if (!em)
4037 return 1;
4038
f48b9075
JB
4039 if (btrfs_test_opt(root, DEGRADED)) {
4040 free_extent_map(em);
4041 return 0;
4042 }
4043
2b82032c
YZ
4044 map = (struct map_lookup *)em->bdev;
4045 for (i = 0; i < map->num_stripes; i++) {
4046 if (!map->stripes[i].dev->writeable) {
4047 readonly = 1;
4048 break;
4049 }
4050 }
0b86a832 4051 free_extent_map(em);
2b82032c 4052 return readonly;
0b86a832
CM
4053}
4054
4055void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
4056{
a8067e02 4057 extent_map_tree_init(&tree->map_tree);
0b86a832
CM
4058}
4059
4060void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
4061{
4062 struct extent_map *em;
4063
d397712b 4064 while (1) {
890871be 4065 write_lock(&tree->map_tree.lock);
0b86a832
CM
4066 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
4067 if (em)
4068 remove_extent_mapping(&tree->map_tree, em);
890871be 4069 write_unlock(&tree->map_tree.lock);
0b86a832
CM
4070 if (!em)
4071 break;
4072 kfree(em->bdev);
4073 /* once for us */
4074 free_extent_map(em);
4075 /* once for the tree */
4076 free_extent_map(em);
4077 }
4078}
4079
5d964051 4080int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
f188591e 4081{
5d964051 4082 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
f188591e
CM
4083 struct extent_map *em;
4084 struct map_lookup *map;
4085 struct extent_map_tree *em_tree = &map_tree->map_tree;
4086 int ret;
4087
890871be 4088 read_lock(&em_tree->lock);
f188591e 4089 em = lookup_extent_mapping(em_tree, logical, len);
890871be 4090 read_unlock(&em_tree->lock);
f188591e
CM
4091 BUG_ON(!em);
4092
4093 BUG_ON(em->start > logical || em->start + em->len < logical);
4094 map = (struct map_lookup *)em->bdev;
4095 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
4096 ret = map->num_stripes;
321aecc6
CM
4097 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4098 ret = map->sub_stripes;
53b381b3
DW
4099 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
4100 ret = 2;
4101 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4102 ret = 3;
f188591e
CM
4103 else
4104 ret = 1;
4105 free_extent_map(em);
ad6d620e
SB
4106
4107 btrfs_dev_replace_lock(&fs_info->dev_replace);
4108 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
4109 ret++;
4110 btrfs_dev_replace_unlock(&fs_info->dev_replace);
4111
f188591e
CM
4112 return ret;
4113}
4114
53b381b3
DW
4115unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
4116 struct btrfs_mapping_tree *map_tree,
4117 u64 logical)
4118{
4119 struct extent_map *em;
4120 struct map_lookup *map;
4121 struct extent_map_tree *em_tree = &map_tree->map_tree;
4122 unsigned long len = root->sectorsize;
4123
4124 read_lock(&em_tree->lock);
4125 em = lookup_extent_mapping(em_tree, logical, len);
4126 read_unlock(&em_tree->lock);
4127 BUG_ON(!em);
4128
4129 BUG_ON(em->start > logical || em->start + em->len < logical);
4130 map = (struct map_lookup *)em->bdev;
4131 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4132 BTRFS_BLOCK_GROUP_RAID6)) {
4133 len = map->stripe_len * nr_data_stripes(map);
4134 }
4135 free_extent_map(em);
4136 return len;
4137}
4138
4139int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
4140 u64 logical, u64 len, int mirror_num)
4141{
4142 struct extent_map *em;
4143 struct map_lookup *map;
4144 struct extent_map_tree *em_tree = &map_tree->map_tree;
4145 int ret = 0;
4146
4147 read_lock(&em_tree->lock);
4148 em = lookup_extent_mapping(em_tree, logical, len);
4149 read_unlock(&em_tree->lock);
4150 BUG_ON(!em);
4151
4152 BUG_ON(em->start > logical || em->start + em->len < logical);
4153 map = (struct map_lookup *)em->bdev;
4154 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4155 BTRFS_BLOCK_GROUP_RAID6))
4156 ret = 1;
4157 free_extent_map(em);
4158 return ret;
4159}
4160
30d9861f
SB
4161static int find_live_mirror(struct btrfs_fs_info *fs_info,
4162 struct map_lookup *map, int first, int num,
4163 int optimal, int dev_replace_is_ongoing)
dfe25020
CM
4164{
4165 int i;
30d9861f
SB
4166 int tolerance;
4167 struct btrfs_device *srcdev;
4168
4169 if (dev_replace_is_ongoing &&
4170 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
4171 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
4172 srcdev = fs_info->dev_replace.srcdev;
4173 else
4174 srcdev = NULL;
4175
4176 /*
4177 * try to avoid the drive that is the source drive for a
4178 * dev-replace procedure, only choose it if no other non-missing
4179 * mirror is available
4180 */
4181 for (tolerance = 0; tolerance < 2; tolerance++) {
4182 if (map->stripes[optimal].dev->bdev &&
4183 (tolerance || map->stripes[optimal].dev != srcdev))
4184 return optimal;
4185 for (i = first; i < first + num; i++) {
4186 if (map->stripes[i].dev->bdev &&
4187 (tolerance || map->stripes[i].dev != srcdev))
4188 return i;
4189 }
dfe25020 4190 }
30d9861f 4191
dfe25020
CM
4192 /* we couldn't find one that doesn't fail. Just return something
4193 * and the io error handling code will clean up eventually
4194 */
4195 return optimal;
4196}
4197
53b381b3
DW
4198static inline int parity_smaller(u64 a, u64 b)
4199{
4200 return a > b;
4201}
4202
4203/* Bubble-sort the stripe set to put the parity/syndrome stripes last */
4204static void sort_parity_stripes(struct btrfs_bio *bbio, u64 *raid_map)
4205{
4206 struct btrfs_bio_stripe s;
4207 int i;
4208 u64 l;
4209 int again = 1;
4210
4211 while (again) {
4212 again = 0;
4213 for (i = 0; i < bbio->num_stripes - 1; i++) {
4214 if (parity_smaller(raid_map[i], raid_map[i+1])) {
4215 s = bbio->stripes[i];
4216 l = raid_map[i];
4217 bbio->stripes[i] = bbio->stripes[i+1];
4218 raid_map[i] = raid_map[i+1];
4219 bbio->stripes[i+1] = s;
4220 raid_map[i+1] = l;
4221 again = 1;
4222 }
4223 }
4224 }
4225}
4226
3ec706c8 4227static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
f2d8d74d 4228 u64 logical, u64 *length,
a1d3c478 4229 struct btrfs_bio **bbio_ret,
53b381b3 4230 int mirror_num, u64 **raid_map_ret)
0b86a832
CM
4231{
4232 struct extent_map *em;
4233 struct map_lookup *map;
3ec706c8 4234 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
0b86a832
CM
4235 struct extent_map_tree *em_tree = &map_tree->map_tree;
4236 u64 offset;
593060d7 4237 u64 stripe_offset;
fce3bb9a 4238 u64 stripe_end_offset;
593060d7 4239 u64 stripe_nr;
fce3bb9a
LD
4240 u64 stripe_nr_orig;
4241 u64 stripe_nr_end;
53b381b3
DW
4242 u64 stripe_len;
4243 u64 *raid_map = NULL;
593060d7 4244 int stripe_index;
cea9e445 4245 int i;
de11cc12 4246 int ret = 0;
f2d8d74d 4247 int num_stripes;
a236aed1 4248 int max_errors = 0;
a1d3c478 4249 struct btrfs_bio *bbio = NULL;
472262f3
SB
4250 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
4251 int dev_replace_is_ongoing = 0;
4252 int num_alloc_stripes;
ad6d620e
SB
4253 int patch_the_first_stripe_for_dev_replace = 0;
4254 u64 physical_to_patch_in_first_stripe = 0;
53b381b3 4255 u64 raid56_full_stripe_start = (u64)-1;
0b86a832 4256
890871be 4257 read_lock(&em_tree->lock);
0b86a832 4258 em = lookup_extent_mapping(em_tree, logical, *length);
890871be 4259 read_unlock(&em_tree->lock);
f2d8d74d 4260
3b951516 4261 if (!em) {
48940662 4262 printk(KERN_CRIT "btrfs: unable to find logical %llu len %llu\n",
d397712b
CM
4263 (unsigned long long)logical,
4264 (unsigned long long)*length);
f2d8d74d 4265 BUG();
3b951516 4266 }
0b86a832
CM
4267
4268 BUG_ON(em->start > logical || em->start + em->len < logical);
4269 map = (struct map_lookup *)em->bdev;
4270 offset = logical - em->start;
593060d7 4271
53b381b3
DW
4272 if (mirror_num > map->num_stripes)
4273 mirror_num = 0;
4274
4275 stripe_len = map->stripe_len;
593060d7
CM
4276 stripe_nr = offset;
4277 /*
4278 * stripe_nr counts the total number of stripes we have to stride
4279 * to get to this block
4280 */
53b381b3 4281 do_div(stripe_nr, stripe_len);
593060d7 4282
53b381b3 4283 stripe_offset = stripe_nr * stripe_len;
593060d7
CM
4284 BUG_ON(offset < stripe_offset);
4285
4286 /* stripe_offset is the offset of this block in its stripe*/
4287 stripe_offset = offset - stripe_offset;
4288
53b381b3
DW
4289 /* if we're here for raid56, we need to know the stripe aligned start */
4290 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4291 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
4292 raid56_full_stripe_start = offset;
4293
4294 /* allow a write of a full stripe, but make sure we don't
4295 * allow straddling of stripes
4296 */
4297 do_div(raid56_full_stripe_start, full_stripe_len);
4298 raid56_full_stripe_start *= full_stripe_len;
4299 }
4300
4301 if (rw & REQ_DISCARD) {
4302 /* we don't discard raid56 yet */
4303 if (map->type &
4304 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4305 ret = -EOPNOTSUPP;
4306 goto out;
4307 }
fce3bb9a 4308 *length = min_t(u64, em->len - offset, *length);
53b381b3
DW
4309 } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
4310 u64 max_len;
4311 /* For writes to RAID[56], allow a full stripeset across all disks.
4312 For other RAID types and for RAID[56] reads, just allow a single
4313 stripe (on a single disk). */
4314 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6) &&
4315 (rw & REQ_WRITE)) {
4316 max_len = stripe_len * nr_data_stripes(map) -
4317 (offset - raid56_full_stripe_start);
4318 } else {
4319 /* we limit the length of each bio to what fits in a stripe */
4320 max_len = stripe_len - stripe_offset;
4321 }
4322 *length = min_t(u64, em->len - offset, max_len);
cea9e445
CM
4323 } else {
4324 *length = em->len - offset;
4325 }
f2d8d74d 4326
53b381b3
DW
4327 /* This is for when we're called from btrfs_merge_bio_hook() and all
4328 it cares about is the length */
a1d3c478 4329 if (!bbio_ret)
cea9e445
CM
4330 goto out;
4331
472262f3
SB
4332 btrfs_dev_replace_lock(dev_replace);
4333 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
4334 if (!dev_replace_is_ongoing)
4335 btrfs_dev_replace_unlock(dev_replace);
4336
ad6d620e
SB
4337 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
4338 !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
4339 dev_replace->tgtdev != NULL) {
4340 /*
4341 * in dev-replace case, for repair case (that's the only
4342 * case where the mirror is selected explicitly when
4343 * calling btrfs_map_block), blocks left of the left cursor
4344 * can also be read from the target drive.
4345 * For REQ_GET_READ_MIRRORS, the target drive is added as
4346 * the last one to the array of stripes. For READ, it also
4347 * needs to be supported using the same mirror number.
4348 * If the requested block is not left of the left cursor,
4349 * EIO is returned. This can happen because btrfs_num_copies()
4350 * returns one more in the dev-replace case.
4351 */
4352 u64 tmp_length = *length;
4353 struct btrfs_bio *tmp_bbio = NULL;
4354 int tmp_num_stripes;
4355 u64 srcdev_devid = dev_replace->srcdev->devid;
4356 int index_srcdev = 0;
4357 int found = 0;
4358 u64 physical_of_found = 0;
4359
4360 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
53b381b3 4361 logical, &tmp_length, &tmp_bbio, 0, NULL);
ad6d620e
SB
4362 if (ret) {
4363 WARN_ON(tmp_bbio != NULL);
4364 goto out;
4365 }
4366
4367 tmp_num_stripes = tmp_bbio->num_stripes;
4368 if (mirror_num > tmp_num_stripes) {
4369 /*
4370 * REQ_GET_READ_MIRRORS does not contain this
4371 * mirror, that means that the requested area
4372 * is not left of the left cursor
4373 */
4374 ret = -EIO;
4375 kfree(tmp_bbio);
4376 goto out;
4377 }
4378
4379 /*
4380 * process the rest of the function using the mirror_num
4381 * of the source drive. Therefore look it up first.
4382 * At the end, patch the device pointer to the one of the
4383 * target drive.
4384 */
4385 for (i = 0; i < tmp_num_stripes; i++) {
4386 if (tmp_bbio->stripes[i].dev->devid == srcdev_devid) {
4387 /*
4388 * In case of DUP, in order to keep it
4389 * simple, only add the mirror with the
4390 * lowest physical address
4391 */
4392 if (found &&
4393 physical_of_found <=
4394 tmp_bbio->stripes[i].physical)
4395 continue;
4396 index_srcdev = i;
4397 found = 1;
4398 physical_of_found =
4399 tmp_bbio->stripes[i].physical;
4400 }
4401 }
4402
4403 if (found) {
4404 mirror_num = index_srcdev + 1;
4405 patch_the_first_stripe_for_dev_replace = 1;
4406 physical_to_patch_in_first_stripe = physical_of_found;
4407 } else {
4408 WARN_ON(1);
4409 ret = -EIO;
4410 kfree(tmp_bbio);
4411 goto out;
4412 }
4413
4414 kfree(tmp_bbio);
4415 } else if (mirror_num > map->num_stripes) {
4416 mirror_num = 0;
4417 }
4418
f2d8d74d 4419 num_stripes = 1;
cea9e445 4420 stripe_index = 0;
fce3bb9a
LD
4421 stripe_nr_orig = stripe_nr;
4422 stripe_nr_end = (offset + *length + map->stripe_len - 1) &
4423 (~(map->stripe_len - 1));
4424 do_div(stripe_nr_end, map->stripe_len);
4425 stripe_end_offset = stripe_nr_end * map->stripe_len -
4426 (offset + *length);
53b381b3 4427
fce3bb9a
LD
4428 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
4429 if (rw & REQ_DISCARD)
4430 num_stripes = min_t(u64, map->num_stripes,
4431 stripe_nr_end - stripe_nr_orig);
4432 stripe_index = do_div(stripe_nr, map->num_stripes);
4433 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
29a8d9a0 4434 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
f2d8d74d 4435 num_stripes = map->num_stripes;
2fff734f 4436 else if (mirror_num)
f188591e 4437 stripe_index = mirror_num - 1;
dfe25020 4438 else {
30d9861f 4439 stripe_index = find_live_mirror(fs_info, map, 0,
dfe25020 4440 map->num_stripes,
30d9861f
SB
4441 current->pid % map->num_stripes,
4442 dev_replace_is_ongoing);
a1d3c478 4443 mirror_num = stripe_index + 1;
dfe25020 4444 }
2fff734f 4445
611f0e00 4446 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
29a8d9a0 4447 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
f2d8d74d 4448 num_stripes = map->num_stripes;
a1d3c478 4449 } else if (mirror_num) {
f188591e 4450 stripe_index = mirror_num - 1;
a1d3c478
JS
4451 } else {
4452 mirror_num = 1;
4453 }
2fff734f 4454
321aecc6
CM
4455 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
4456 int factor = map->num_stripes / map->sub_stripes;
321aecc6
CM
4457
4458 stripe_index = do_div(stripe_nr, factor);
4459 stripe_index *= map->sub_stripes;
4460
29a8d9a0 4461 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
f2d8d74d 4462 num_stripes = map->sub_stripes;
fce3bb9a
LD
4463 else if (rw & REQ_DISCARD)
4464 num_stripes = min_t(u64, map->sub_stripes *
4465 (stripe_nr_end - stripe_nr_orig),
4466 map->num_stripes);
321aecc6
CM
4467 else if (mirror_num)
4468 stripe_index += mirror_num - 1;
dfe25020 4469 else {
3e74317a 4470 int old_stripe_index = stripe_index;
30d9861f
SB
4471 stripe_index = find_live_mirror(fs_info, map,
4472 stripe_index,
dfe25020 4473 map->sub_stripes, stripe_index +
30d9861f
SB
4474 current->pid % map->sub_stripes,
4475 dev_replace_is_ongoing);
3e74317a 4476 mirror_num = stripe_index - old_stripe_index + 1;
dfe25020 4477 }
53b381b3
DW
4478
4479 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4480 BTRFS_BLOCK_GROUP_RAID6)) {
4481 u64 tmp;
4482
4483 if (bbio_ret && ((rw & REQ_WRITE) || mirror_num > 1)
4484 && raid_map_ret) {
4485 int i, rot;
4486
4487 /* push stripe_nr back to the start of the full stripe */
4488 stripe_nr = raid56_full_stripe_start;
4489 do_div(stripe_nr, stripe_len);
4490
4491 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
4492
4493 /* RAID[56] write or recovery. Return all stripes */
4494 num_stripes = map->num_stripes;
4495 max_errors = nr_parity_stripes(map);
4496
4497 raid_map = kmalloc(sizeof(u64) * num_stripes,
4498 GFP_NOFS);
4499 if (!raid_map) {
4500 ret = -ENOMEM;
4501 goto out;
4502 }
4503
4504 /* Work out the disk rotation on this stripe-set */
4505 tmp = stripe_nr;
4506 rot = do_div(tmp, num_stripes);
4507
4508 /* Fill in the logical address of each stripe */
4509 tmp = stripe_nr * nr_data_stripes(map);
4510 for (i = 0; i < nr_data_stripes(map); i++)
4511 raid_map[(i+rot) % num_stripes] =
4512 em->start + (tmp + i) * map->stripe_len;
4513
4514 raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
4515 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4516 raid_map[(i+rot+1) % num_stripes] =
4517 RAID6_Q_STRIPE;
4518
4519 *length = map->stripe_len;
4520 stripe_index = 0;
4521 stripe_offset = 0;
4522 } else {
4523 /*
4524 * Mirror #0 or #1 means the original data block.
4525 * Mirror #2 is RAID5 parity block.
4526 * Mirror #3 is RAID6 Q block.
4527 */
4528 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
4529 if (mirror_num > 1)
4530 stripe_index = nr_data_stripes(map) +
4531 mirror_num - 2;
4532
4533 /* We distribute the parity blocks across stripes */
4534 tmp = stripe_nr + stripe_index;
4535 stripe_index = do_div(tmp, map->num_stripes);
4536 }
8790d502
CM
4537 } else {
4538 /*
4539 * after this do_div call, stripe_nr is the number of stripes
4540 * on this device we have to walk to find the data, and
4541 * stripe_index is the number of our device in the stripe array
4542 */
4543 stripe_index = do_div(stripe_nr, map->num_stripes);
a1d3c478 4544 mirror_num = stripe_index + 1;
8790d502 4545 }
593060d7 4546 BUG_ON(stripe_index >= map->num_stripes);
cea9e445 4547
472262f3 4548 num_alloc_stripes = num_stripes;
ad6d620e
SB
4549 if (dev_replace_is_ongoing) {
4550 if (rw & (REQ_WRITE | REQ_DISCARD))
4551 num_alloc_stripes <<= 1;
4552 if (rw & REQ_GET_READ_MIRRORS)
4553 num_alloc_stripes++;
4554 }
472262f3 4555 bbio = kzalloc(btrfs_bio_size(num_alloc_stripes), GFP_NOFS);
de11cc12
LZ
4556 if (!bbio) {
4557 ret = -ENOMEM;
4558 goto out;
4559 }
4560 atomic_set(&bbio->error, 0);
4561
fce3bb9a 4562 if (rw & REQ_DISCARD) {
ec9ef7a1
LZ
4563 int factor = 0;
4564 int sub_stripes = 0;
4565 u64 stripes_per_dev = 0;
4566 u32 remaining_stripes = 0;
b89203f7 4567 u32 last_stripe = 0;
ec9ef7a1
LZ
4568
4569 if (map->type &
4570 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
4571 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
4572 sub_stripes = 1;
4573 else
4574 sub_stripes = map->sub_stripes;
4575
4576 factor = map->num_stripes / sub_stripes;
4577 stripes_per_dev = div_u64_rem(stripe_nr_end -
4578 stripe_nr_orig,
4579 factor,
4580 &remaining_stripes);
b89203f7
LB
4581 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
4582 last_stripe *= sub_stripes;
ec9ef7a1
LZ
4583 }
4584
fce3bb9a 4585 for (i = 0; i < num_stripes; i++) {
a1d3c478 4586 bbio->stripes[i].physical =
f2d8d74d
CM
4587 map->stripes[stripe_index].physical +
4588 stripe_offset + stripe_nr * map->stripe_len;
a1d3c478 4589 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
fce3bb9a 4590
ec9ef7a1
LZ
4591 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
4592 BTRFS_BLOCK_GROUP_RAID10)) {
4593 bbio->stripes[i].length = stripes_per_dev *
4594 map->stripe_len;
b89203f7 4595
ec9ef7a1
LZ
4596 if (i / sub_stripes < remaining_stripes)
4597 bbio->stripes[i].length +=
4598 map->stripe_len;
b89203f7
LB
4599
4600 /*
4601 * Special for the first stripe and
4602 * the last stripe:
4603 *
4604 * |-------|...|-------|
4605 * |----------|
4606 * off end_off
4607 */
ec9ef7a1 4608 if (i < sub_stripes)
a1d3c478 4609 bbio->stripes[i].length -=
fce3bb9a 4610 stripe_offset;
b89203f7
LB
4611
4612 if (stripe_index >= last_stripe &&
4613 stripe_index <= (last_stripe +
4614 sub_stripes - 1))
a1d3c478 4615 bbio->stripes[i].length -=
fce3bb9a 4616 stripe_end_offset;
b89203f7 4617
ec9ef7a1
LZ
4618 if (i == sub_stripes - 1)
4619 stripe_offset = 0;
fce3bb9a 4620 } else
a1d3c478 4621 bbio->stripes[i].length = *length;
fce3bb9a
LD
4622
4623 stripe_index++;
4624 if (stripe_index == map->num_stripes) {
4625 /* This could only happen for RAID0/10 */
4626 stripe_index = 0;
4627 stripe_nr++;
4628 }
4629 }
4630 } else {
4631 for (i = 0; i < num_stripes; i++) {
a1d3c478 4632 bbio->stripes[i].physical =
212a17ab
LT
4633 map->stripes[stripe_index].physical +
4634 stripe_offset +
4635 stripe_nr * map->stripe_len;
a1d3c478 4636 bbio->stripes[i].dev =
212a17ab 4637 map->stripes[stripe_index].dev;
fce3bb9a 4638 stripe_index++;
f2d8d74d 4639 }
593060d7 4640 }
de11cc12 4641
29a8d9a0 4642 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) {
de11cc12
LZ
4643 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
4644 BTRFS_BLOCK_GROUP_RAID10 |
53b381b3 4645 BTRFS_BLOCK_GROUP_RAID5 |
de11cc12
LZ
4646 BTRFS_BLOCK_GROUP_DUP)) {
4647 max_errors = 1;
53b381b3
DW
4648 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
4649 max_errors = 2;
de11cc12 4650 }
f2d8d74d 4651 }
de11cc12 4652
472262f3
SB
4653 if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
4654 dev_replace->tgtdev != NULL) {
4655 int index_where_to_add;
4656 u64 srcdev_devid = dev_replace->srcdev->devid;
4657
4658 /*
4659 * duplicate the write operations while the dev replace
4660 * procedure is running. Since the copying of the old disk
4661 * to the new disk takes place at run time while the
4662 * filesystem is mounted writable, the regular write
4663 * operations to the old disk have to be duplicated to go
4664 * to the new disk as well.
4665 * Note that device->missing is handled by the caller, and
4666 * that the write to the old disk is already set up in the
4667 * stripes array.
4668 */
4669 index_where_to_add = num_stripes;
4670 for (i = 0; i < num_stripes; i++) {
4671 if (bbio->stripes[i].dev->devid == srcdev_devid) {
4672 /* write to new disk, too */
4673 struct btrfs_bio_stripe *new =
4674 bbio->stripes + index_where_to_add;
4675 struct btrfs_bio_stripe *old =
4676 bbio->stripes + i;
4677
4678 new->physical = old->physical;
4679 new->length = old->length;
4680 new->dev = dev_replace->tgtdev;
4681 index_where_to_add++;
4682 max_errors++;
4683 }
4684 }
4685 num_stripes = index_where_to_add;
ad6d620e
SB
4686 } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
4687 dev_replace->tgtdev != NULL) {
4688 u64 srcdev_devid = dev_replace->srcdev->devid;
4689 int index_srcdev = 0;
4690 int found = 0;
4691 u64 physical_of_found = 0;
4692
4693 /*
4694 * During the dev-replace procedure, the target drive can
4695 * also be used to read data in case it is needed to repair
4696 * a corrupt block elsewhere. This is possible if the
4697 * requested area is left of the left cursor. In this area,
4698 * the target drive is a full copy of the source drive.
4699 */
4700 for (i = 0; i < num_stripes; i++) {
4701 if (bbio->stripes[i].dev->devid == srcdev_devid) {
4702 /*
4703 * In case of DUP, in order to keep it
4704 * simple, only add the mirror with the
4705 * lowest physical address
4706 */
4707 if (found &&
4708 physical_of_found <=
4709 bbio->stripes[i].physical)
4710 continue;
4711 index_srcdev = i;
4712 found = 1;
4713 physical_of_found = bbio->stripes[i].physical;
4714 }
4715 }
4716 if (found) {
4717 u64 length = map->stripe_len;
4718
4719 if (physical_of_found + length <=
4720 dev_replace->cursor_left) {
4721 struct btrfs_bio_stripe *tgtdev_stripe =
4722 bbio->stripes + num_stripes;
4723
4724 tgtdev_stripe->physical = physical_of_found;
4725 tgtdev_stripe->length =
4726 bbio->stripes[index_srcdev].length;
4727 tgtdev_stripe->dev = dev_replace->tgtdev;
4728
4729 num_stripes++;
4730 }
4731 }
472262f3
SB
4732 }
4733
de11cc12
LZ
4734 *bbio_ret = bbio;
4735 bbio->num_stripes = num_stripes;
4736 bbio->max_errors = max_errors;
4737 bbio->mirror_num = mirror_num;
ad6d620e
SB
4738
4739 /*
4740 * this is the case that REQ_READ && dev_replace_is_ongoing &&
4741 * mirror_num == num_stripes + 1 && dev_replace target drive is
4742 * available as a mirror
4743 */
4744 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
4745 WARN_ON(num_stripes > 1);
4746 bbio->stripes[0].dev = dev_replace->tgtdev;
4747 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
4748 bbio->mirror_num = map->num_stripes + 1;
4749 }
53b381b3
DW
4750 if (raid_map) {
4751 sort_parity_stripes(bbio, raid_map);
4752 *raid_map_ret = raid_map;
4753 }
cea9e445 4754out:
472262f3
SB
4755 if (dev_replace_is_ongoing)
4756 btrfs_dev_replace_unlock(dev_replace);
0b86a832 4757 free_extent_map(em);
de11cc12 4758 return ret;
0b86a832
CM
4759}
4760
3ec706c8 4761int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
f2d8d74d 4762 u64 logical, u64 *length,
a1d3c478 4763 struct btrfs_bio **bbio_ret, int mirror_num)
f2d8d74d 4764{
3ec706c8 4765 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
53b381b3 4766 mirror_num, NULL);
f2d8d74d
CM
4767}
4768
a512bbf8
YZ
4769int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
4770 u64 chunk_start, u64 physical, u64 devid,
4771 u64 **logical, int *naddrs, int *stripe_len)
4772{
4773 struct extent_map_tree *em_tree = &map_tree->map_tree;
4774 struct extent_map *em;
4775 struct map_lookup *map;
4776 u64 *buf;
4777 u64 bytenr;
4778 u64 length;
4779 u64 stripe_nr;
53b381b3 4780 u64 rmap_len;
a512bbf8
YZ
4781 int i, j, nr = 0;
4782
890871be 4783 read_lock(&em_tree->lock);
a512bbf8 4784 em = lookup_extent_mapping(em_tree, chunk_start, 1);
890871be 4785 read_unlock(&em_tree->lock);
a512bbf8
YZ
4786
4787 BUG_ON(!em || em->start != chunk_start);
4788 map = (struct map_lookup *)em->bdev;
4789
4790 length = em->len;
53b381b3
DW
4791 rmap_len = map->stripe_len;
4792
a512bbf8
YZ
4793 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4794 do_div(length, map->num_stripes / map->sub_stripes);
4795 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
4796 do_div(length, map->num_stripes);
53b381b3
DW
4797 else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4798 BTRFS_BLOCK_GROUP_RAID6)) {
4799 do_div(length, nr_data_stripes(map));
4800 rmap_len = map->stripe_len * nr_data_stripes(map);
4801 }
a512bbf8
YZ
4802
4803 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
79787eaa 4804 BUG_ON(!buf); /* -ENOMEM */
a512bbf8
YZ
4805
4806 for (i = 0; i < map->num_stripes; i++) {
4807 if (devid && map->stripes[i].dev->devid != devid)
4808 continue;
4809 if (map->stripes[i].physical > physical ||
4810 map->stripes[i].physical + length <= physical)
4811 continue;
4812
4813 stripe_nr = physical - map->stripes[i].physical;
4814 do_div(stripe_nr, map->stripe_len);
4815
4816 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
4817 stripe_nr = stripe_nr * map->num_stripes + i;
4818 do_div(stripe_nr, map->sub_stripes);
4819 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
4820 stripe_nr = stripe_nr * map->num_stripes + i;
53b381b3
DW
4821 } /* else if RAID[56], multiply by nr_data_stripes().
4822 * Alternatively, just use rmap_len below instead of
4823 * map->stripe_len */
4824
4825 bytenr = chunk_start + stripe_nr * rmap_len;
934d375b 4826 WARN_ON(nr >= map->num_stripes);
a512bbf8
YZ
4827 for (j = 0; j < nr; j++) {
4828 if (buf[j] == bytenr)
4829 break;
4830 }
934d375b
CM
4831 if (j == nr) {
4832 WARN_ON(nr >= map->num_stripes);
a512bbf8 4833 buf[nr++] = bytenr;
934d375b 4834 }
a512bbf8
YZ
4835 }
4836
a512bbf8
YZ
4837 *logical = buf;
4838 *naddrs = nr;
53b381b3 4839 *stripe_len = rmap_len;
a512bbf8
YZ
4840
4841 free_extent_map(em);
4842 return 0;
f2d8d74d
CM
4843}
4844
442a4f63
SB
4845static void *merge_stripe_index_into_bio_private(void *bi_private,
4846 unsigned int stripe_index)
4847{
4848 /*
4849 * with single, dup, RAID0, RAID1 and RAID10, stripe_index is
4850 * at most 1.
4851 * The alternative solution (instead of stealing bits from the
4852 * pointer) would be to allocate an intermediate structure
4853 * that contains the old private pointer plus the stripe_index.
4854 */
4855 BUG_ON((((uintptr_t)bi_private) & 3) != 0);
4856 BUG_ON(stripe_index > 3);
4857 return (void *)(((uintptr_t)bi_private) | stripe_index);
4858}
4859
4860static struct btrfs_bio *extract_bbio_from_bio_private(void *bi_private)
4861{
4862 return (struct btrfs_bio *)(((uintptr_t)bi_private) & ~((uintptr_t)3));
4863}
4864
4865static unsigned int extract_stripe_index_from_bio_private(void *bi_private)
4866{
4867 return (unsigned int)((uintptr_t)bi_private) & 3;
4868}
4869
a1d3c478 4870static void btrfs_end_bio(struct bio *bio, int err)
8790d502 4871{
442a4f63 4872 struct btrfs_bio *bbio = extract_bbio_from_bio_private(bio->bi_private);
7d2b4daa 4873 int is_orig_bio = 0;
8790d502 4874
442a4f63 4875 if (err) {
a1d3c478 4876 atomic_inc(&bbio->error);
442a4f63
SB
4877 if (err == -EIO || err == -EREMOTEIO) {
4878 unsigned int stripe_index =
4879 extract_stripe_index_from_bio_private(
4880 bio->bi_private);
4881 struct btrfs_device *dev;
4882
4883 BUG_ON(stripe_index >= bbio->num_stripes);
4884 dev = bbio->stripes[stripe_index].dev;
597a60fa
SB
4885 if (dev->bdev) {
4886 if (bio->bi_rw & WRITE)
4887 btrfs_dev_stat_inc(dev,
4888 BTRFS_DEV_STAT_WRITE_ERRS);
4889 else
4890 btrfs_dev_stat_inc(dev,
4891 BTRFS_DEV_STAT_READ_ERRS);
4892 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
4893 btrfs_dev_stat_inc(dev,
4894 BTRFS_DEV_STAT_FLUSH_ERRS);
4895 btrfs_dev_stat_print_on_error(dev);
4896 }
442a4f63
SB
4897 }
4898 }
8790d502 4899
a1d3c478 4900 if (bio == bbio->orig_bio)
7d2b4daa
CM
4901 is_orig_bio = 1;
4902
a1d3c478 4903 if (atomic_dec_and_test(&bbio->stripes_pending)) {
7d2b4daa
CM
4904 if (!is_orig_bio) {
4905 bio_put(bio);
a1d3c478 4906 bio = bbio->orig_bio;
7d2b4daa 4907 }
a1d3c478
JS
4908 bio->bi_private = bbio->private;
4909 bio->bi_end_io = bbio->end_io;
2774b2ca
JS
4910 bio->bi_bdev = (struct block_device *)
4911 (unsigned long)bbio->mirror_num;
a236aed1 4912 /* only send an error to the higher layers if it is
53b381b3 4913 * beyond the tolerance of the btrfs bio
a236aed1 4914 */
a1d3c478 4915 if (atomic_read(&bbio->error) > bbio->max_errors) {
a236aed1 4916 err = -EIO;
5dbc8fca 4917 } else {
1259ab75
CM
4918 /*
4919 * this bio is actually up to date, we didn't
4920 * go over the max number of errors
4921 */
4922 set_bit(BIO_UPTODATE, &bio->bi_flags);
a236aed1 4923 err = 0;
1259ab75 4924 }
a1d3c478 4925 kfree(bbio);
8790d502
CM
4926
4927 bio_endio(bio, err);
7d2b4daa 4928 } else if (!is_orig_bio) {
8790d502
CM
4929 bio_put(bio);
4930 }
8790d502
CM
4931}
4932
8b712842
CM
4933struct async_sched {
4934 struct bio *bio;
4935 int rw;
4936 struct btrfs_fs_info *info;
4937 struct btrfs_work work;
4938};
4939
4940/*
4941 * see run_scheduled_bios for a description of why bios are collected for
4942 * async submit.
4943 *
4944 * This will add one bio to the pending list for a device and make sure
4945 * the work struct is scheduled.
4946 */
53b381b3 4947noinline void btrfs_schedule_bio(struct btrfs_root *root,
a1b32a59
CM
4948 struct btrfs_device *device,
4949 int rw, struct bio *bio)
8b712842
CM
4950{
4951 int should_queue = 1;
ffbd517d 4952 struct btrfs_pending_bios *pending_bios;
8b712842 4953
53b381b3
DW
4954 if (device->missing || !device->bdev) {
4955 bio_endio(bio, -EIO);
4956 return;
4957 }
4958
8b712842 4959 /* don't bother with additional async steps for reads, right now */
7b6d91da 4960 if (!(rw & REQ_WRITE)) {
492bb6de 4961 bio_get(bio);
21adbd5c 4962 btrfsic_submit_bio(rw, bio);
492bb6de 4963 bio_put(bio);
143bede5 4964 return;
8b712842
CM
4965 }
4966
4967 /*
0986fe9e 4968 * nr_async_bios allows us to reliably return congestion to the
8b712842
CM
4969 * higher layers. Otherwise, the async bio makes it appear we have
4970 * made progress against dirty pages when we've really just put it
4971 * on a queue for later
4972 */
0986fe9e 4973 atomic_inc(&root->fs_info->nr_async_bios);
492bb6de 4974 WARN_ON(bio->bi_next);
8b712842
CM
4975 bio->bi_next = NULL;
4976 bio->bi_rw |= rw;
4977
4978 spin_lock(&device->io_lock);
7b6d91da 4979 if (bio->bi_rw & REQ_SYNC)
ffbd517d
CM
4980 pending_bios = &device->pending_sync_bios;
4981 else
4982 pending_bios = &device->pending_bios;
8b712842 4983
ffbd517d
CM
4984 if (pending_bios->tail)
4985 pending_bios->tail->bi_next = bio;
8b712842 4986
ffbd517d
CM
4987 pending_bios->tail = bio;
4988 if (!pending_bios->head)
4989 pending_bios->head = bio;
8b712842
CM
4990 if (device->running_pending)
4991 should_queue = 0;
4992
4993 spin_unlock(&device->io_lock);
4994
4995 if (should_queue)
1cc127b5
CM
4996 btrfs_queue_worker(&root->fs_info->submit_workers,
4997 &device->work);
8b712842
CM
4998}
4999
de1ee92a
JB
5000static int bio_size_ok(struct block_device *bdev, struct bio *bio,
5001 sector_t sector)
5002{
5003 struct bio_vec *prev;
5004 struct request_queue *q = bdev_get_queue(bdev);
5005 unsigned short max_sectors = queue_max_sectors(q);
5006 struct bvec_merge_data bvm = {
5007 .bi_bdev = bdev,
5008 .bi_sector = sector,
5009 .bi_rw = bio->bi_rw,
5010 };
5011
5012 if (bio->bi_vcnt == 0) {
5013 WARN_ON(1);
5014 return 1;
5015 }
5016
5017 prev = &bio->bi_io_vec[bio->bi_vcnt - 1];
5018 if ((bio->bi_size >> 9) > max_sectors)
5019 return 0;
5020
5021 if (!q->merge_bvec_fn)
5022 return 1;
5023
5024 bvm.bi_size = bio->bi_size - prev->bv_len;
5025 if (q->merge_bvec_fn(q, &bvm, prev) < prev->bv_len)
5026 return 0;
5027 return 1;
5028}
5029
5030static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5031 struct bio *bio, u64 physical, int dev_nr,
5032 int rw, int async)
5033{
5034 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
5035
5036 bio->bi_private = bbio;
5037 bio->bi_private = merge_stripe_index_into_bio_private(
5038 bio->bi_private, (unsigned int)dev_nr);
5039 bio->bi_end_io = btrfs_end_bio;
5040 bio->bi_sector = physical >> 9;
5041#ifdef DEBUG
5042 {
5043 struct rcu_string *name;
5044
5045 rcu_read_lock();
5046 name = rcu_dereference(dev->name);
d1423248 5047 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
de1ee92a
JB
5048 "(%s id %llu), size=%u\n", rw,
5049 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
5050 name->str, dev->devid, bio->bi_size);
5051 rcu_read_unlock();
5052 }
5053#endif
5054 bio->bi_bdev = dev->bdev;
5055 if (async)
53b381b3 5056 btrfs_schedule_bio(root, dev, rw, bio);
de1ee92a
JB
5057 else
5058 btrfsic_submit_bio(rw, bio);
5059}
5060
5061static int breakup_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5062 struct bio *first_bio, struct btrfs_device *dev,
5063 int dev_nr, int rw, int async)
5064{
5065 struct bio_vec *bvec = first_bio->bi_io_vec;
5066 struct bio *bio;
5067 int nr_vecs = bio_get_nr_vecs(dev->bdev);
5068 u64 physical = bbio->stripes[dev_nr].physical;
5069
5070again:
5071 bio = btrfs_bio_alloc(dev->bdev, physical >> 9, nr_vecs, GFP_NOFS);
5072 if (!bio)
5073 return -ENOMEM;
5074
5075 while (bvec <= (first_bio->bi_io_vec + first_bio->bi_vcnt - 1)) {
5076 if (bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5077 bvec->bv_offset) < bvec->bv_len) {
5078 u64 len = bio->bi_size;
5079
5080 atomic_inc(&bbio->stripes_pending);
5081 submit_stripe_bio(root, bbio, bio, physical, dev_nr,
5082 rw, async);
5083 physical += len;
5084 goto again;
5085 }
5086 bvec++;
5087 }
5088
5089 submit_stripe_bio(root, bbio, bio, physical, dev_nr, rw, async);
5090 return 0;
5091}
5092
5093static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
5094{
5095 atomic_inc(&bbio->error);
5096 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5097 bio->bi_private = bbio->private;
5098 bio->bi_end_io = bbio->end_io;
5099 bio->bi_bdev = (struct block_device *)
5100 (unsigned long)bbio->mirror_num;
5101 bio->bi_sector = logical >> 9;
5102 kfree(bbio);
5103 bio_endio(bio, -EIO);
5104 }
5105}
5106
f188591e 5107int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
8b712842 5108 int mirror_num, int async_submit)
0b86a832 5109{
0b86a832 5110 struct btrfs_device *dev;
8790d502 5111 struct bio *first_bio = bio;
a62b9401 5112 u64 logical = (u64)bio->bi_sector << 9;
0b86a832
CM
5113 u64 length = 0;
5114 u64 map_length;
53b381b3 5115 u64 *raid_map = NULL;
0b86a832 5116 int ret;
8790d502
CM
5117 int dev_nr = 0;
5118 int total_devs = 1;
a1d3c478 5119 struct btrfs_bio *bbio = NULL;
0b86a832 5120
f2d8d74d 5121 length = bio->bi_size;
0b86a832 5122 map_length = length;
cea9e445 5123
53b381b3
DW
5124 ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
5125 mirror_num, &raid_map);
5126 if (ret) /* -ENOMEM */
79787eaa 5127 return ret;
cea9e445 5128
a1d3c478 5129 total_devs = bbio->num_stripes;
53b381b3
DW
5130 bbio->orig_bio = first_bio;
5131 bbio->private = first_bio->bi_private;
5132 bbio->end_io = first_bio->bi_end_io;
5133 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
5134
5135 if (raid_map) {
5136 /* In this case, map_length has been set to the length of
5137 a single stripe; not the whole write */
5138 if (rw & WRITE) {
5139 return raid56_parity_write(root, bio, bbio,
5140 raid_map, map_length);
5141 } else {
5142 return raid56_parity_recover(root, bio, bbio,
5143 raid_map, map_length,
5144 mirror_num);
5145 }
5146 }
5147
cea9e445 5148 if (map_length < length) {
48940662 5149 printk(KERN_CRIT "btrfs: mapping failed logical %llu bio len %llu "
d397712b
CM
5150 "len %llu\n", (unsigned long long)logical,
5151 (unsigned long long)length,
5152 (unsigned long long)map_length);
cea9e445
CM
5153 BUG();
5154 }
a1d3c478 5155
d397712b 5156 while (dev_nr < total_devs) {
de1ee92a
JB
5157 dev = bbio->stripes[dev_nr].dev;
5158 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
5159 bbio_error(bbio, first_bio, logical);
5160 dev_nr++;
5161 continue;
5162 }
5163
5164 /*
5165 * Check and see if we're ok with this bio based on it's size
5166 * and offset with the given device.
5167 */
5168 if (!bio_size_ok(dev->bdev, first_bio,
5169 bbio->stripes[dev_nr].physical >> 9)) {
5170 ret = breakup_stripe_bio(root, bbio, first_bio, dev,
5171 dev_nr, rw, async_submit);
5172 BUG_ON(ret);
5173 dev_nr++;
5174 continue;
5175 }
5176
a1d3c478
JS
5177 if (dev_nr < total_devs - 1) {
5178 bio = bio_clone(first_bio, GFP_NOFS);
79787eaa 5179 BUG_ON(!bio); /* -ENOMEM */
a1d3c478
JS
5180 } else {
5181 bio = first_bio;
8790d502 5182 }
de1ee92a
JB
5183
5184 submit_stripe_bio(root, bbio, bio,
5185 bbio->stripes[dev_nr].physical, dev_nr, rw,
5186 async_submit);
8790d502
CM
5187 dev_nr++;
5188 }
0b86a832
CM
5189 return 0;
5190}
5191
aa1b8cd4 5192struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
2b82032c 5193 u8 *uuid, u8 *fsid)
0b86a832 5194{
2b82032c
YZ
5195 struct btrfs_device *device;
5196 struct btrfs_fs_devices *cur_devices;
5197
aa1b8cd4 5198 cur_devices = fs_info->fs_devices;
2b82032c
YZ
5199 while (cur_devices) {
5200 if (!fsid ||
5201 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5202 device = __find_device(&cur_devices->devices,
5203 devid, uuid);
5204 if (device)
5205 return device;
5206 }
5207 cur_devices = cur_devices->seed;
5208 }
5209 return NULL;
0b86a832
CM
5210}
5211
dfe25020
CM
5212static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
5213 u64 devid, u8 *dev_uuid)
5214{
5215 struct btrfs_device *device;
5216 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
5217
5218 device = kzalloc(sizeof(*device), GFP_NOFS);
7cbd8a83 5219 if (!device)
5220 return NULL;
dfe25020
CM
5221 list_add(&device->dev_list,
5222 &fs_devices->devices);
dfe25020
CM
5223 device->dev_root = root->fs_info->dev_root;
5224 device->devid = devid;
8b712842 5225 device->work.func = pending_bios_fn;
e4404d6e 5226 device->fs_devices = fs_devices;
cd02dca5 5227 device->missing = 1;
dfe25020 5228 fs_devices->num_devices++;
cd02dca5 5229 fs_devices->missing_devices++;
dfe25020 5230 spin_lock_init(&device->io_lock);
d20f7043 5231 INIT_LIST_HEAD(&device->dev_alloc_list);
dfe25020
CM
5232 memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
5233 return device;
5234}
5235
0b86a832
CM
5236static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
5237 struct extent_buffer *leaf,
5238 struct btrfs_chunk *chunk)
5239{
5240 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5241 struct map_lookup *map;
5242 struct extent_map *em;
5243 u64 logical;
5244 u64 length;
5245 u64 devid;
a443755f 5246 u8 uuid[BTRFS_UUID_SIZE];
593060d7 5247 int num_stripes;
0b86a832 5248 int ret;
593060d7 5249 int i;
0b86a832 5250
e17cade2
CM
5251 logical = key->offset;
5252 length = btrfs_chunk_length(leaf, chunk);
a061fc8d 5253
890871be 5254 read_lock(&map_tree->map_tree.lock);
0b86a832 5255 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
890871be 5256 read_unlock(&map_tree->map_tree.lock);
0b86a832
CM
5257
5258 /* already mapped? */
5259 if (em && em->start <= logical && em->start + em->len > logical) {
5260 free_extent_map(em);
0b86a832
CM
5261 return 0;
5262 } else if (em) {
5263 free_extent_map(em);
5264 }
0b86a832 5265
172ddd60 5266 em = alloc_extent_map();
0b86a832
CM
5267 if (!em)
5268 return -ENOMEM;
593060d7
CM
5269 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
5270 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
0b86a832
CM
5271 if (!map) {
5272 free_extent_map(em);
5273 return -ENOMEM;
5274 }
5275
5276 em->bdev = (struct block_device *)map;
5277 em->start = logical;
5278 em->len = length;
70c8a91c 5279 em->orig_start = 0;
0b86a832 5280 em->block_start = 0;
c8b97818 5281 em->block_len = em->len;
0b86a832 5282
593060d7
CM
5283 map->num_stripes = num_stripes;
5284 map->io_width = btrfs_chunk_io_width(leaf, chunk);
5285 map->io_align = btrfs_chunk_io_align(leaf, chunk);
5286 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
5287 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
5288 map->type = btrfs_chunk_type(leaf, chunk);
321aecc6 5289 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
593060d7
CM
5290 for (i = 0; i < num_stripes; i++) {
5291 map->stripes[i].physical =
5292 btrfs_stripe_offset_nr(leaf, chunk, i);
5293 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
a443755f
CM
5294 read_extent_buffer(leaf, uuid, (unsigned long)
5295 btrfs_stripe_dev_uuid_nr(chunk, i),
5296 BTRFS_UUID_SIZE);
aa1b8cd4
SB
5297 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
5298 uuid, NULL);
dfe25020 5299 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
593060d7
CM
5300 kfree(map);
5301 free_extent_map(em);
5302 return -EIO;
5303 }
dfe25020
CM
5304 if (!map->stripes[i].dev) {
5305 map->stripes[i].dev =
5306 add_missing_dev(root, devid, uuid);
5307 if (!map->stripes[i].dev) {
5308 kfree(map);
5309 free_extent_map(em);
5310 return -EIO;
5311 }
5312 }
5313 map->stripes[i].dev->in_fs_metadata = 1;
0b86a832
CM
5314 }
5315
890871be 5316 write_lock(&map_tree->map_tree.lock);
0b86a832 5317 ret = add_extent_mapping(&map_tree->map_tree, em);
890871be 5318 write_unlock(&map_tree->map_tree.lock);
79787eaa 5319 BUG_ON(ret); /* Tree corruption */
0b86a832
CM
5320 free_extent_map(em);
5321
5322 return 0;
5323}
5324
143bede5 5325static void fill_device_from_item(struct extent_buffer *leaf,
0b86a832
CM
5326 struct btrfs_dev_item *dev_item,
5327 struct btrfs_device *device)
5328{
5329 unsigned long ptr;
0b86a832
CM
5330
5331 device->devid = btrfs_device_id(leaf, dev_item);
d6397bae
CB
5332 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
5333 device->total_bytes = device->disk_total_bytes;
0b86a832
CM
5334 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
5335 device->type = btrfs_device_type(leaf, dev_item);
5336 device->io_align = btrfs_device_io_align(leaf, dev_item);
5337 device->io_width = btrfs_device_io_width(leaf, dev_item);
5338 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
8dabb742 5339 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
63a212ab 5340 device->is_tgtdev_for_dev_replace = 0;
0b86a832
CM
5341
5342 ptr = (unsigned long)btrfs_device_uuid(dev_item);
e17cade2 5343 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
0b86a832
CM
5344}
5345
2b82032c
YZ
5346static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
5347{
5348 struct btrfs_fs_devices *fs_devices;
5349 int ret;
5350
b367e47f 5351 BUG_ON(!mutex_is_locked(&uuid_mutex));
2b82032c
YZ
5352
5353 fs_devices = root->fs_info->fs_devices->seed;
5354 while (fs_devices) {
5355 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5356 ret = 0;
5357 goto out;
5358 }
5359 fs_devices = fs_devices->seed;
5360 }
5361
5362 fs_devices = find_fsid(fsid);
5363 if (!fs_devices) {
5364 ret = -ENOENT;
5365 goto out;
5366 }
e4404d6e
YZ
5367
5368 fs_devices = clone_fs_devices(fs_devices);
5369 if (IS_ERR(fs_devices)) {
5370 ret = PTR_ERR(fs_devices);
2b82032c
YZ
5371 goto out;
5372 }
5373
97288f2c 5374 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
15916de8 5375 root->fs_info->bdev_holder);
48d28232
JL
5376 if (ret) {
5377 free_fs_devices(fs_devices);
2b82032c 5378 goto out;
48d28232 5379 }
2b82032c
YZ
5380
5381 if (!fs_devices->seeding) {
5382 __btrfs_close_devices(fs_devices);
e4404d6e 5383 free_fs_devices(fs_devices);
2b82032c
YZ
5384 ret = -EINVAL;
5385 goto out;
5386 }
5387
5388 fs_devices->seed = root->fs_info->fs_devices->seed;
5389 root->fs_info->fs_devices->seed = fs_devices;
2b82032c 5390out:
2b82032c
YZ
5391 return ret;
5392}
5393
0d81ba5d 5394static int read_one_dev(struct btrfs_root *root,
0b86a832
CM
5395 struct extent_buffer *leaf,
5396 struct btrfs_dev_item *dev_item)
5397{
5398 struct btrfs_device *device;
5399 u64 devid;
5400 int ret;
2b82032c 5401 u8 fs_uuid[BTRFS_UUID_SIZE];
a443755f
CM
5402 u8 dev_uuid[BTRFS_UUID_SIZE];
5403
0b86a832 5404 devid = btrfs_device_id(leaf, dev_item);
a443755f
CM
5405 read_extent_buffer(leaf, dev_uuid,
5406 (unsigned long)btrfs_device_uuid(dev_item),
5407 BTRFS_UUID_SIZE);
2b82032c
YZ
5408 read_extent_buffer(leaf, fs_uuid,
5409 (unsigned long)btrfs_device_fsid(dev_item),
5410 BTRFS_UUID_SIZE);
5411
5412 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
5413 ret = open_seed_devices(root, fs_uuid);
e4404d6e 5414 if (ret && !btrfs_test_opt(root, DEGRADED))
2b82032c 5415 return ret;
2b82032c
YZ
5416 }
5417
aa1b8cd4 5418 device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
2b82032c 5419 if (!device || !device->bdev) {
e4404d6e 5420 if (!btrfs_test_opt(root, DEGRADED))
2b82032c
YZ
5421 return -EIO;
5422
5423 if (!device) {
d397712b
CM
5424 printk(KERN_WARNING "warning devid %llu missing\n",
5425 (unsigned long long)devid);
2b82032c
YZ
5426 device = add_missing_dev(root, devid, dev_uuid);
5427 if (!device)
5428 return -ENOMEM;
cd02dca5
CM
5429 } else if (!device->missing) {
5430 /*
5431 * this happens when a device that was properly setup
5432 * in the device info lists suddenly goes bad.
5433 * device->bdev is NULL, and so we have to set
5434 * device->missing to one here
5435 */
5436 root->fs_info->fs_devices->missing_devices++;
5437 device->missing = 1;
2b82032c
YZ
5438 }
5439 }
5440
5441 if (device->fs_devices != root->fs_info->fs_devices) {
5442 BUG_ON(device->writeable);
5443 if (device->generation !=
5444 btrfs_device_generation(leaf, dev_item))
5445 return -EINVAL;
6324fbf3 5446 }
0b86a832
CM
5447
5448 fill_device_from_item(leaf, dev_item, device);
5449 device->dev_root = root->fs_info->dev_root;
dfe25020 5450 device->in_fs_metadata = 1;
63a212ab 5451 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
2b82032c 5452 device->fs_devices->total_rw_bytes += device->total_bytes;
2bf64758
JB
5453 spin_lock(&root->fs_info->free_chunk_lock);
5454 root->fs_info->free_chunk_space += device->total_bytes -
5455 device->bytes_used;
5456 spin_unlock(&root->fs_info->free_chunk_lock);
5457 }
0b86a832 5458 ret = 0;
0b86a832
CM
5459 return ret;
5460}
5461
e4404d6e 5462int btrfs_read_sys_array(struct btrfs_root *root)
0b86a832 5463{
6c41761f 5464 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
a061fc8d 5465 struct extent_buffer *sb;
0b86a832 5466 struct btrfs_disk_key *disk_key;
0b86a832 5467 struct btrfs_chunk *chunk;
84eed90f
CM
5468 u8 *ptr;
5469 unsigned long sb_ptr;
5470 int ret = 0;
0b86a832
CM
5471 u32 num_stripes;
5472 u32 array_size;
5473 u32 len = 0;
0b86a832 5474 u32 cur;
84eed90f 5475 struct btrfs_key key;
0b86a832 5476
e4404d6e 5477 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
a061fc8d
CM
5478 BTRFS_SUPER_INFO_SIZE);
5479 if (!sb)
5480 return -ENOMEM;
5481 btrfs_set_buffer_uptodate(sb);
85d4e461 5482 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
8a334426
DS
5483 /*
5484 * The sb extent buffer is artifical and just used to read the system array.
5485 * btrfs_set_buffer_uptodate() call does not properly mark all it's
5486 * pages up-to-date when the page is larger: extent does not cover the
5487 * whole page and consequently check_page_uptodate does not find all
5488 * the page's extents up-to-date (the hole beyond sb),
5489 * write_extent_buffer then triggers a WARN_ON.
5490 *
5491 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
5492 * but sb spans only this function. Add an explicit SetPageUptodate call
5493 * to silence the warning eg. on PowerPC 64.
5494 */
5495 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
727011e0 5496 SetPageUptodate(sb->pages[0]);
4008c04a 5497
a061fc8d 5498 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
0b86a832
CM
5499 array_size = btrfs_super_sys_array_size(super_copy);
5500
0b86a832
CM
5501 ptr = super_copy->sys_chunk_array;
5502 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
5503 cur = 0;
5504
5505 while (cur < array_size) {
5506 disk_key = (struct btrfs_disk_key *)ptr;
5507 btrfs_disk_key_to_cpu(&key, disk_key);
5508
a061fc8d 5509 len = sizeof(*disk_key); ptr += len;
0b86a832
CM
5510 sb_ptr += len;
5511 cur += len;
5512
0d81ba5d 5513 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
0b86a832 5514 chunk = (struct btrfs_chunk *)sb_ptr;
0d81ba5d 5515 ret = read_one_chunk(root, &key, sb, chunk);
84eed90f
CM
5516 if (ret)
5517 break;
0b86a832
CM
5518 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
5519 len = btrfs_chunk_item_size(num_stripes);
5520 } else {
84eed90f
CM
5521 ret = -EIO;
5522 break;
0b86a832
CM
5523 }
5524 ptr += len;
5525 sb_ptr += len;
5526 cur += len;
5527 }
a061fc8d 5528 free_extent_buffer(sb);
84eed90f 5529 return ret;
0b86a832
CM
5530}
5531
5532int btrfs_read_chunk_tree(struct btrfs_root *root)
5533{
5534 struct btrfs_path *path;
5535 struct extent_buffer *leaf;
5536 struct btrfs_key key;
5537 struct btrfs_key found_key;
5538 int ret;
5539 int slot;
5540
5541 root = root->fs_info->chunk_root;
5542
5543 path = btrfs_alloc_path();
5544 if (!path)
5545 return -ENOMEM;
5546
b367e47f
LZ
5547 mutex_lock(&uuid_mutex);
5548 lock_chunks(root);
5549
0b86a832
CM
5550 /* first we search for all of the device items, and then we
5551 * read in all of the chunk items. This way we can create chunk
5552 * mappings that reference all of the devices that are afound
5553 */
5554 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
5555 key.offset = 0;
5556 key.type = 0;
5557again:
5558 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
ab59381e
ZL
5559 if (ret < 0)
5560 goto error;
d397712b 5561 while (1) {
0b86a832
CM
5562 leaf = path->nodes[0];
5563 slot = path->slots[0];
5564 if (slot >= btrfs_header_nritems(leaf)) {
5565 ret = btrfs_next_leaf(root, path);
5566 if (ret == 0)
5567 continue;
5568 if (ret < 0)
5569 goto error;
5570 break;
5571 }
5572 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5573 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
5574 if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
5575 break;
5576 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
5577 struct btrfs_dev_item *dev_item;
5578 dev_item = btrfs_item_ptr(leaf, slot,
5579 struct btrfs_dev_item);
0d81ba5d 5580 ret = read_one_dev(root, leaf, dev_item);
2b82032c
YZ
5581 if (ret)
5582 goto error;
0b86a832
CM
5583 }
5584 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
5585 struct btrfs_chunk *chunk;
5586 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
5587 ret = read_one_chunk(root, &found_key, leaf, chunk);
2b82032c
YZ
5588 if (ret)
5589 goto error;
0b86a832
CM
5590 }
5591 path->slots[0]++;
5592 }
5593 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
5594 key.objectid = 0;
b3b4aa74 5595 btrfs_release_path(path);
0b86a832
CM
5596 goto again;
5597 }
0b86a832
CM
5598 ret = 0;
5599error:
b367e47f
LZ
5600 unlock_chunks(root);
5601 mutex_unlock(&uuid_mutex);
5602
2b82032c 5603 btrfs_free_path(path);
0b86a832
CM
5604 return ret;
5605}
442a4f63 5606
733f4fbb
SB
5607static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
5608{
5609 int i;
5610
5611 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
5612 btrfs_dev_stat_reset(dev, i);
5613}
5614
5615int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
5616{
5617 struct btrfs_key key;
5618 struct btrfs_key found_key;
5619 struct btrfs_root *dev_root = fs_info->dev_root;
5620 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
5621 struct extent_buffer *eb;
5622 int slot;
5623 int ret = 0;
5624 struct btrfs_device *device;
5625 struct btrfs_path *path = NULL;
5626 int i;
5627
5628 path = btrfs_alloc_path();
5629 if (!path) {
5630 ret = -ENOMEM;
5631 goto out;
5632 }
5633
5634 mutex_lock(&fs_devices->device_list_mutex);
5635 list_for_each_entry(device, &fs_devices->devices, dev_list) {
5636 int item_size;
5637 struct btrfs_dev_stats_item *ptr;
5638
5639 key.objectid = 0;
5640 key.type = BTRFS_DEV_STATS_KEY;
5641 key.offset = device->devid;
5642 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
5643 if (ret) {
733f4fbb
SB
5644 __btrfs_reset_dev_stats(device);
5645 device->dev_stats_valid = 1;
5646 btrfs_release_path(path);
5647 continue;
5648 }
5649 slot = path->slots[0];
5650 eb = path->nodes[0];
5651 btrfs_item_key_to_cpu(eb, &found_key, slot);
5652 item_size = btrfs_item_size_nr(eb, slot);
5653
5654 ptr = btrfs_item_ptr(eb, slot,
5655 struct btrfs_dev_stats_item);
5656
5657 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
5658 if (item_size >= (1 + i) * sizeof(__le64))
5659 btrfs_dev_stat_set(device, i,
5660 btrfs_dev_stats_value(eb, ptr, i));
5661 else
5662 btrfs_dev_stat_reset(device, i);
5663 }
5664
5665 device->dev_stats_valid = 1;
5666 btrfs_dev_stat_print_on_load(device);
5667 btrfs_release_path(path);
5668 }
5669 mutex_unlock(&fs_devices->device_list_mutex);
5670
5671out:
5672 btrfs_free_path(path);
5673 return ret < 0 ? ret : 0;
5674}
5675
5676static int update_dev_stat_item(struct btrfs_trans_handle *trans,
5677 struct btrfs_root *dev_root,
5678 struct btrfs_device *device)
5679{
5680 struct btrfs_path *path;
5681 struct btrfs_key key;
5682 struct extent_buffer *eb;
5683 struct btrfs_dev_stats_item *ptr;
5684 int ret;
5685 int i;
5686
5687 key.objectid = 0;
5688 key.type = BTRFS_DEV_STATS_KEY;
5689 key.offset = device->devid;
5690
5691 path = btrfs_alloc_path();
5692 BUG_ON(!path);
5693 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
5694 if (ret < 0) {
606686ee
JB
5695 printk_in_rcu(KERN_WARNING "btrfs: error %d while searching for dev_stats item for device %s!\n",
5696 ret, rcu_str_deref(device->name));
733f4fbb
SB
5697 goto out;
5698 }
5699
5700 if (ret == 0 &&
5701 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
5702 /* need to delete old one and insert a new one */
5703 ret = btrfs_del_item(trans, dev_root, path);
5704 if (ret != 0) {
606686ee
JB
5705 printk_in_rcu(KERN_WARNING "btrfs: delete too small dev_stats item for device %s failed %d!\n",
5706 rcu_str_deref(device->name), ret);
733f4fbb
SB
5707 goto out;
5708 }
5709 ret = 1;
5710 }
5711
5712 if (ret == 1) {
5713 /* need to insert a new item */
5714 btrfs_release_path(path);
5715 ret = btrfs_insert_empty_item(trans, dev_root, path,
5716 &key, sizeof(*ptr));
5717 if (ret < 0) {
606686ee
JB
5718 printk_in_rcu(KERN_WARNING "btrfs: insert dev_stats item for device %s failed %d!\n",
5719 rcu_str_deref(device->name), ret);
733f4fbb
SB
5720 goto out;
5721 }
5722 }
5723
5724 eb = path->nodes[0];
5725 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
5726 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
5727 btrfs_set_dev_stats_value(eb, ptr, i,
5728 btrfs_dev_stat_read(device, i));
5729 btrfs_mark_buffer_dirty(eb);
5730
5731out:
5732 btrfs_free_path(path);
5733 return ret;
5734}
5735
5736/*
5737 * called from commit_transaction. Writes all changed device stats to disk.
5738 */
5739int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
5740 struct btrfs_fs_info *fs_info)
5741{
5742 struct btrfs_root *dev_root = fs_info->dev_root;
5743 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
5744 struct btrfs_device *device;
5745 int ret = 0;
5746
5747 mutex_lock(&fs_devices->device_list_mutex);
5748 list_for_each_entry(device, &fs_devices->devices, dev_list) {
5749 if (!device->dev_stats_valid || !device->dev_stats_dirty)
5750 continue;
5751
5752 ret = update_dev_stat_item(trans, dev_root, device);
5753 if (!ret)
5754 device->dev_stats_dirty = 0;
5755 }
5756 mutex_unlock(&fs_devices->device_list_mutex);
5757
5758 return ret;
5759}
5760
442a4f63
SB
5761void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
5762{
5763 btrfs_dev_stat_inc(dev, index);
5764 btrfs_dev_stat_print_on_error(dev);
5765}
5766
5767void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
5768{
733f4fbb
SB
5769 if (!dev->dev_stats_valid)
5770 return;
606686ee 5771 printk_ratelimited_in_rcu(KERN_ERR
442a4f63 5772 "btrfs: bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
606686ee 5773 rcu_str_deref(dev->name),
442a4f63
SB
5774 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
5775 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
5776 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
5777 btrfs_dev_stat_read(dev,
5778 BTRFS_DEV_STAT_CORRUPTION_ERRS),
5779 btrfs_dev_stat_read(dev,
5780 BTRFS_DEV_STAT_GENERATION_ERRS));
5781}
c11d2c23 5782
733f4fbb
SB
5783static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
5784{
a98cdb85
SB
5785 int i;
5786
5787 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
5788 if (btrfs_dev_stat_read(dev, i) != 0)
5789 break;
5790 if (i == BTRFS_DEV_STAT_VALUES_MAX)
5791 return; /* all values == 0, suppress message */
5792
606686ee
JB
5793 printk_in_rcu(KERN_INFO "btrfs: bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
5794 rcu_str_deref(dev->name),
733f4fbb
SB
5795 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
5796 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
5797 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
5798 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
5799 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
5800}
5801
c11d2c23 5802int btrfs_get_dev_stats(struct btrfs_root *root,
b27f7c0c 5803 struct btrfs_ioctl_get_dev_stats *stats)
c11d2c23
SB
5804{
5805 struct btrfs_device *dev;
5806 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
5807 int i;
5808
5809 mutex_lock(&fs_devices->device_list_mutex);
aa1b8cd4 5810 dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
c11d2c23
SB
5811 mutex_unlock(&fs_devices->device_list_mutex);
5812
5813 if (!dev) {
5814 printk(KERN_WARNING
5815 "btrfs: get dev_stats failed, device not found\n");
5816 return -ENODEV;
733f4fbb
SB
5817 } else if (!dev->dev_stats_valid) {
5818 printk(KERN_WARNING
5819 "btrfs: get dev_stats failed, not yet valid\n");
5820 return -ENODEV;
b27f7c0c 5821 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
c11d2c23
SB
5822 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
5823 if (stats->nr_items > i)
5824 stats->values[i] =
5825 btrfs_dev_stat_read_and_reset(dev, i);
5826 else
5827 btrfs_dev_stat_reset(dev, i);
5828 }
5829 } else {
5830 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
5831 if (stats->nr_items > i)
5832 stats->values[i] = btrfs_dev_stat_read(dev, i);
5833 }
5834 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
5835 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
5836 return 0;
5837}
a8a6dab7
SB
5838
5839int btrfs_scratch_superblock(struct btrfs_device *device)
5840{
5841 struct buffer_head *bh;
5842 struct btrfs_super_block *disk_super;
5843
5844 bh = btrfs_read_dev_super(device->bdev);
5845 if (!bh)
5846 return -EINVAL;
5847 disk_super = (struct btrfs_super_block *)bh->b_data;
5848
5849 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
5850 set_buffer_dirty(bh);
5851 sync_dirty_buffer(bh);
5852 brelse(bh);
5853
5854 return 0;
5855}
This page took 0.643189 seconds and 5 git commands to generate.