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