2 * Copyright (C) 2007 Oracle. All rights reserved.
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.
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.
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.
18 #include <linux/sched.h>
19 #include <linux/sched/mm.h>
20 #include <linux/bio.h>
21 #include <linux/slab.h>
22 #include <linux/buffer_head.h>
23 #include <linux/blkdev.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 <linux/uuid.h>
31 #include <asm/div64.h>
33 #include "extent_map.h"
35 #include "transaction.h"
36 #include "print-tree.h"
39 #include "async-thread.h"
40 #include "check-integrity.h"
41 #include "rcu-string.h"
43 #include "dev-replace.h"
46 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
47 [BTRFS_RAID_RAID10] = {
50 .devs_max = 0, /* 0 == as many as possible */
52 .tolerated_failures = 1,
56 [BTRFS_RAID_RAID1] = {
61 .tolerated_failures = 1,
70 .tolerated_failures = 0,
74 [BTRFS_RAID_RAID0] = {
79 .tolerated_failures = 0,
83 [BTRFS_RAID_SINGLE] = {
88 .tolerated_failures = 0,
92 [BTRFS_RAID_RAID5] = {
97 .tolerated_failures = 1,
101 [BTRFS_RAID_RAID6] = {
106 .tolerated_failures = 2,
112 const u64 btrfs_raid_group[BTRFS_NR_RAID_TYPES] = {
113 [BTRFS_RAID_RAID10] = BTRFS_BLOCK_GROUP_RAID10,
114 [BTRFS_RAID_RAID1] = BTRFS_BLOCK_GROUP_RAID1,
115 [BTRFS_RAID_DUP] = BTRFS_BLOCK_GROUP_DUP,
116 [BTRFS_RAID_RAID0] = BTRFS_BLOCK_GROUP_RAID0,
117 [BTRFS_RAID_SINGLE] = 0,
118 [BTRFS_RAID_RAID5] = BTRFS_BLOCK_GROUP_RAID5,
119 [BTRFS_RAID_RAID6] = BTRFS_BLOCK_GROUP_RAID6,
123 * Table to convert BTRFS_RAID_* to the error code if minimum number of devices
124 * condition is not met. Zero means there's no corresponding
125 * BTRFS_ERROR_DEV_*_NOT_MET value.
127 const int btrfs_raid_mindev_error[BTRFS_NR_RAID_TYPES] = {
128 [BTRFS_RAID_RAID10] = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
129 [BTRFS_RAID_RAID1] = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
130 [BTRFS_RAID_DUP] = 0,
131 [BTRFS_RAID_RAID0] = 0,
132 [BTRFS_RAID_SINGLE] = 0,
133 [BTRFS_RAID_RAID5] = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
134 [BTRFS_RAID_RAID6] = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
137 static int init_first_rw_device(struct btrfs_trans_handle *trans,
138 struct btrfs_fs_info *fs_info);
139 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
140 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
141 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
142 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
143 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
144 enum btrfs_map_op op,
145 u64 logical, u64 *length,
146 struct btrfs_bio **bbio_ret,
147 int mirror_num, int need_raid_map);
149 DEFINE_MUTEX(uuid_mutex);
150 static LIST_HEAD(fs_uuids);
151 struct list_head *btrfs_get_fs_uuids(void)
157 * alloc_fs_devices - allocate struct btrfs_fs_devices
158 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
160 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
161 * The returned struct is not linked onto any lists and can be destroyed with
162 * kfree() right away.
164 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
166 struct btrfs_fs_devices *fs_devs;
168 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
170 return ERR_PTR(-ENOMEM);
172 mutex_init(&fs_devs->device_list_mutex);
174 INIT_LIST_HEAD(&fs_devs->devices);
175 INIT_LIST_HEAD(&fs_devs->resized_devices);
176 INIT_LIST_HEAD(&fs_devs->alloc_list);
177 INIT_LIST_HEAD(&fs_devs->list);
179 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
184 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
186 struct btrfs_device *device;
187 WARN_ON(fs_devices->opened);
188 while (!list_empty(&fs_devices->devices)) {
189 device = list_entry(fs_devices->devices.next,
190 struct btrfs_device, dev_list);
191 list_del(&device->dev_list);
192 rcu_string_free(device->name);
198 static void btrfs_kobject_uevent(struct block_device *bdev,
199 enum kobject_action action)
203 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
205 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
207 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
208 &disk_to_dev(bdev->bd_disk)->kobj);
211 void btrfs_cleanup_fs_uuids(void)
213 struct btrfs_fs_devices *fs_devices;
215 while (!list_empty(&fs_uuids)) {
216 fs_devices = list_entry(fs_uuids.next,
217 struct btrfs_fs_devices, list);
218 list_del(&fs_devices->list);
219 free_fs_devices(fs_devices);
223 static struct btrfs_device *__alloc_device(void)
225 struct btrfs_device *dev;
227 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
229 return ERR_PTR(-ENOMEM);
232 * Preallocate a bio that's always going to be used for flushing device
233 * barriers and matches the device lifespan
235 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
236 if (!dev->flush_bio) {
238 return ERR_PTR(-ENOMEM);
241 INIT_LIST_HEAD(&dev->dev_list);
242 INIT_LIST_HEAD(&dev->dev_alloc_list);
243 INIT_LIST_HEAD(&dev->resized_list);
245 spin_lock_init(&dev->io_lock);
247 spin_lock_init(&dev->reada_lock);
248 atomic_set(&dev->reada_in_flight, 0);
249 atomic_set(&dev->dev_stats_ccnt, 0);
250 btrfs_device_data_ordered_init(dev);
251 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
252 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
258 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
261 * If devid and uuid are both specified, the match must be exact, otherwise
262 * only devid is used.
264 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
265 u64 devid, const u8 *uuid)
267 struct list_head *head = &fs_devices->devices;
268 struct btrfs_device *dev;
270 list_for_each_entry(dev, head, dev_list) {
271 if (dev->devid == devid &&
272 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
279 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
281 struct btrfs_fs_devices *fs_devices;
283 list_for_each_entry(fs_devices, &fs_uuids, list) {
284 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
291 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
292 int flush, struct block_device **bdev,
293 struct buffer_head **bh)
297 *bdev = blkdev_get_by_path(device_path, flags, holder);
300 ret = PTR_ERR(*bdev);
305 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
306 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
308 blkdev_put(*bdev, flags);
311 invalidate_bdev(*bdev);
312 *bh = btrfs_read_dev_super(*bdev);
315 blkdev_put(*bdev, flags);
327 static void requeue_list(struct btrfs_pending_bios *pending_bios,
328 struct bio *head, struct bio *tail)
331 struct bio *old_head;
333 old_head = pending_bios->head;
334 pending_bios->head = head;
335 if (pending_bios->tail)
336 tail->bi_next = old_head;
338 pending_bios->tail = tail;
342 * we try to collect pending bios for a device so we don't get a large
343 * number of procs sending bios down to the same device. This greatly
344 * improves the schedulers ability to collect and merge the bios.
346 * But, it also turns into a long list of bios to process and that is sure
347 * to eventually make the worker thread block. The solution here is to
348 * make some progress and then put this work struct back at the end of
349 * the list if the block device is congested. This way, multiple devices
350 * can make progress from a single worker thread.
352 static noinline void run_scheduled_bios(struct btrfs_device *device)
354 struct btrfs_fs_info *fs_info = device->fs_info;
356 struct backing_dev_info *bdi;
357 struct btrfs_pending_bios *pending_bios;
361 unsigned long num_run;
362 unsigned long batch_run = 0;
364 unsigned long last_waited = 0;
366 int sync_pending = 0;
367 struct blk_plug plug;
370 * this function runs all the bios we've collected for
371 * a particular device. We don't want to wander off to
372 * another device without first sending all of these down.
373 * So, setup a plug here and finish it off before we return
375 blk_start_plug(&plug);
377 bdi = device->bdev->bd_bdi;
378 limit = btrfs_async_submit_limit(fs_info);
379 limit = limit * 2 / 3;
382 spin_lock(&device->io_lock);
387 /* take all the bios off the list at once and process them
388 * later on (without the lock held). But, remember the
389 * tail and other pointers so the bios can be properly reinserted
390 * into the list if we hit congestion
392 if (!force_reg && device->pending_sync_bios.head) {
393 pending_bios = &device->pending_sync_bios;
396 pending_bios = &device->pending_bios;
400 pending = pending_bios->head;
401 tail = pending_bios->tail;
402 WARN_ON(pending && !tail);
405 * if pending was null this time around, no bios need processing
406 * at all and we can stop. Otherwise it'll loop back up again
407 * and do an additional check so no bios are missed.
409 * device->running_pending is used to synchronize with the
412 if (device->pending_sync_bios.head == NULL &&
413 device->pending_bios.head == NULL) {
415 device->running_pending = 0;
418 device->running_pending = 1;
421 pending_bios->head = NULL;
422 pending_bios->tail = NULL;
424 spin_unlock(&device->io_lock);
429 /* we want to work on both lists, but do more bios on the
430 * sync list than the regular list
433 pending_bios != &device->pending_sync_bios &&
434 device->pending_sync_bios.head) ||
435 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
436 device->pending_bios.head)) {
437 spin_lock(&device->io_lock);
438 requeue_list(pending_bios, pending, tail);
443 pending = pending->bi_next;
447 * atomic_dec_return implies a barrier for waitqueue_active
449 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
450 waitqueue_active(&fs_info->async_submit_wait))
451 wake_up(&fs_info->async_submit_wait);
453 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
456 * if we're doing the sync list, record that our
457 * plug has some sync requests on it
459 * If we're doing the regular list and there are
460 * sync requests sitting around, unplug before
463 if (pending_bios == &device->pending_sync_bios) {
465 } else if (sync_pending) {
466 blk_finish_plug(&plug);
467 blk_start_plug(&plug);
471 btrfsic_submit_bio(cur);
478 * we made progress, there is more work to do and the bdi
479 * is now congested. Back off and let other work structs
482 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
483 fs_info->fs_devices->open_devices > 1) {
484 struct io_context *ioc;
486 ioc = current->io_context;
489 * the main goal here is that we don't want to
490 * block if we're going to be able to submit
491 * more requests without blocking.
493 * This code does two great things, it pokes into
494 * the elevator code from a filesystem _and_
495 * it makes assumptions about how batching works.
497 if (ioc && ioc->nr_batch_requests > 0 &&
498 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
500 ioc->last_waited == last_waited)) {
502 * we want to go through our batch of
503 * requests and stop. So, we copy out
504 * the ioc->last_waited time and test
505 * against it before looping
507 last_waited = ioc->last_waited;
511 spin_lock(&device->io_lock);
512 requeue_list(pending_bios, pending, tail);
513 device->running_pending = 1;
515 spin_unlock(&device->io_lock);
516 btrfs_queue_work(fs_info->submit_workers,
520 /* unplug every 64 requests just for good measure */
521 if (batch_run % 64 == 0) {
522 blk_finish_plug(&plug);
523 blk_start_plug(&plug);
532 spin_lock(&device->io_lock);
533 if (device->pending_bios.head || device->pending_sync_bios.head)
535 spin_unlock(&device->io_lock);
538 blk_finish_plug(&plug);
541 static void pending_bios_fn(struct btrfs_work *work)
543 struct btrfs_device *device;
545 device = container_of(work, struct btrfs_device, work);
546 run_scheduled_bios(device);
550 void btrfs_free_stale_device(struct btrfs_device *cur_dev)
552 struct btrfs_fs_devices *fs_devs;
553 struct btrfs_device *dev;
558 list_for_each_entry(fs_devs, &fs_uuids, list) {
563 if (fs_devs->seeding)
566 list_for_each_entry(dev, &fs_devs->devices, dev_list) {
574 * Todo: This won't be enough. What if the same device
575 * comes back (with new uuid and) with its mapper path?
576 * But for now, this does help as mostly an admin will
577 * either use mapper or non mapper path throughout.
580 del = strcmp(rcu_str_deref(dev->name),
581 rcu_str_deref(cur_dev->name));
588 /* delete the stale device */
589 if (fs_devs->num_devices == 1) {
590 btrfs_sysfs_remove_fsid(fs_devs);
591 list_del(&fs_devs->list);
592 free_fs_devices(fs_devs);
595 fs_devs->num_devices--;
596 list_del(&dev->dev_list);
597 rcu_string_free(dev->name);
606 * Add new device to list of registered devices
609 * 1 - first time device is seen
610 * 0 - device already known
613 static noinline int device_list_add(const char *path,
614 struct btrfs_super_block *disk_super,
615 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
617 struct btrfs_device *device;
618 struct btrfs_fs_devices *fs_devices;
619 struct rcu_string *name;
621 u64 found_transid = btrfs_super_generation(disk_super);
623 fs_devices = find_fsid(disk_super->fsid);
625 fs_devices = alloc_fs_devices(disk_super->fsid);
626 if (IS_ERR(fs_devices))
627 return PTR_ERR(fs_devices);
629 list_add(&fs_devices->list, &fs_uuids);
633 device = find_device(fs_devices, devid,
634 disk_super->dev_item.uuid);
638 if (fs_devices->opened)
641 device = btrfs_alloc_device(NULL, &devid,
642 disk_super->dev_item.uuid);
643 if (IS_ERR(device)) {
644 /* we can safely leave the fs_devices entry around */
645 return PTR_ERR(device);
648 name = rcu_string_strdup(path, GFP_NOFS);
653 rcu_assign_pointer(device->name, name);
655 mutex_lock(&fs_devices->device_list_mutex);
656 list_add_rcu(&device->dev_list, &fs_devices->devices);
657 fs_devices->num_devices++;
658 mutex_unlock(&fs_devices->device_list_mutex);
661 device->fs_devices = fs_devices;
662 } else if (!device->name || strcmp(device->name->str, path)) {
664 * When FS is already mounted.
665 * 1. If you are here and if the device->name is NULL that
666 * means this device was missing at time of FS mount.
667 * 2. If you are here and if the device->name is different
668 * from 'path' that means either
669 * a. The same device disappeared and reappeared with
671 * b. The missing-disk-which-was-replaced, has
674 * We must allow 1 and 2a above. But 2b would be a spurious
677 * Further in case of 1 and 2a above, the disk at 'path'
678 * would have missed some transaction when it was away and
679 * in case of 2a the stale bdev has to be updated as well.
680 * 2b must not be allowed at all time.
684 * For now, we do allow update to btrfs_fs_device through the
685 * btrfs dev scan cli after FS has been mounted. We're still
686 * tracking a problem where systems fail mount by subvolume id
687 * when we reject replacement on a mounted FS.
689 if (!fs_devices->opened && found_transid < device->generation) {
691 * That is if the FS is _not_ mounted and if you
692 * are here, that means there is more than one
693 * disk with same uuid and devid.We keep the one
694 * with larger generation number or the last-in if
695 * generation are equal.
700 name = rcu_string_strdup(path, GFP_NOFS);
703 rcu_string_free(device->name);
704 rcu_assign_pointer(device->name, name);
705 if (device->missing) {
706 fs_devices->missing_devices--;
712 * Unmount does not free the btrfs_device struct but would zero
713 * generation along with most of the other members. So just update
714 * it back. We need it to pick the disk with largest generation
717 if (!fs_devices->opened)
718 device->generation = found_transid;
721 * if there is new btrfs on an already registered device,
722 * then remove the stale device entry.
725 btrfs_free_stale_device(device);
727 *fs_devices_ret = fs_devices;
732 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
734 struct btrfs_fs_devices *fs_devices;
735 struct btrfs_device *device;
736 struct btrfs_device *orig_dev;
738 fs_devices = alloc_fs_devices(orig->fsid);
739 if (IS_ERR(fs_devices))
742 mutex_lock(&orig->device_list_mutex);
743 fs_devices->total_devices = orig->total_devices;
745 /* We have held the volume lock, it is safe to get the devices. */
746 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
747 struct rcu_string *name;
749 device = btrfs_alloc_device(NULL, &orig_dev->devid,
755 * This is ok to do without rcu read locked because we hold the
756 * uuid mutex so nothing we touch in here is going to disappear.
758 if (orig_dev->name) {
759 name = rcu_string_strdup(orig_dev->name->str,
765 rcu_assign_pointer(device->name, name);
768 list_add(&device->dev_list, &fs_devices->devices);
769 device->fs_devices = fs_devices;
770 fs_devices->num_devices++;
772 mutex_unlock(&orig->device_list_mutex);
775 mutex_unlock(&orig->device_list_mutex);
776 free_fs_devices(fs_devices);
777 return ERR_PTR(-ENOMEM);
780 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices, int step)
782 struct btrfs_device *device, *next;
783 struct btrfs_device *latest_dev = NULL;
785 mutex_lock(&uuid_mutex);
787 /* This is the initialized path, it is safe to release the devices. */
788 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
789 if (device->in_fs_metadata) {
790 if (!device->is_tgtdev_for_dev_replace &&
792 device->generation > latest_dev->generation)) {
798 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
800 * In the first step, keep the device which has
801 * the correct fsid and the devid that is used
802 * for the dev_replace procedure.
803 * In the second step, the dev_replace state is
804 * read from the device tree and it is known
805 * whether the procedure is really active or
806 * not, which means whether this device is
807 * used or whether it should be removed.
809 if (step == 0 || device->is_tgtdev_for_dev_replace) {
814 blkdev_put(device->bdev, device->mode);
816 fs_devices->open_devices--;
818 if (device->writeable) {
819 list_del_init(&device->dev_alloc_list);
820 device->writeable = 0;
821 if (!device->is_tgtdev_for_dev_replace)
822 fs_devices->rw_devices--;
824 list_del_init(&device->dev_list);
825 fs_devices->num_devices--;
826 rcu_string_free(device->name);
830 if (fs_devices->seed) {
831 fs_devices = fs_devices->seed;
835 fs_devices->latest_bdev = latest_dev->bdev;
837 mutex_unlock(&uuid_mutex);
840 static void __free_device(struct work_struct *work)
842 struct btrfs_device *device;
844 device = container_of(work, struct btrfs_device, rcu_work);
845 rcu_string_free(device->name);
846 bio_put(device->flush_bio);
850 static void free_device(struct rcu_head *head)
852 struct btrfs_device *device;
854 device = container_of(head, struct btrfs_device, rcu);
856 INIT_WORK(&device->rcu_work, __free_device);
857 schedule_work(&device->rcu_work);
860 static void btrfs_close_bdev(struct btrfs_device *device)
862 if (device->bdev && device->writeable) {
863 sync_blockdev(device->bdev);
864 invalidate_bdev(device->bdev);
868 blkdev_put(device->bdev, device->mode);
871 static void btrfs_prepare_close_one_device(struct btrfs_device *device)
873 struct btrfs_fs_devices *fs_devices = device->fs_devices;
874 struct btrfs_device *new_device;
875 struct rcu_string *name;
878 fs_devices->open_devices--;
880 if (device->writeable &&
881 device->devid != BTRFS_DEV_REPLACE_DEVID) {
882 list_del_init(&device->dev_alloc_list);
883 fs_devices->rw_devices--;
887 fs_devices->missing_devices--;
889 new_device = btrfs_alloc_device(NULL, &device->devid,
891 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
893 /* Safe because we are under uuid_mutex */
895 name = rcu_string_strdup(device->name->str, GFP_NOFS);
896 BUG_ON(!name); /* -ENOMEM */
897 rcu_assign_pointer(new_device->name, name);
900 list_replace_rcu(&device->dev_list, &new_device->dev_list);
901 new_device->fs_devices = device->fs_devices;
904 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
906 struct btrfs_device *device, *tmp;
907 struct list_head pending_put;
909 INIT_LIST_HEAD(&pending_put);
911 if (--fs_devices->opened > 0)
914 mutex_lock(&fs_devices->device_list_mutex);
915 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
916 btrfs_prepare_close_one_device(device);
917 list_add(&device->dev_list, &pending_put);
919 mutex_unlock(&fs_devices->device_list_mutex);
922 * btrfs_show_devname() is using the device_list_mutex,
923 * sometimes call to blkdev_put() leads vfs calling
924 * into this func. So do put outside of device_list_mutex,
927 while (!list_empty(&pending_put)) {
928 device = list_first_entry(&pending_put,
929 struct btrfs_device, dev_list);
930 list_del(&device->dev_list);
931 btrfs_close_bdev(device);
932 call_rcu(&device->rcu, free_device);
935 WARN_ON(fs_devices->open_devices);
936 WARN_ON(fs_devices->rw_devices);
937 fs_devices->opened = 0;
938 fs_devices->seeding = 0;
943 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
945 struct btrfs_fs_devices *seed_devices = NULL;
948 mutex_lock(&uuid_mutex);
949 ret = __btrfs_close_devices(fs_devices);
950 if (!fs_devices->opened) {
951 seed_devices = fs_devices->seed;
952 fs_devices->seed = NULL;
954 mutex_unlock(&uuid_mutex);
956 while (seed_devices) {
957 fs_devices = seed_devices;
958 seed_devices = fs_devices->seed;
959 __btrfs_close_devices(fs_devices);
960 free_fs_devices(fs_devices);
963 * Wait for rcu kworkers under __btrfs_close_devices
964 * to finish all blkdev_puts so device is really
965 * free when umount is done.
971 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
972 fmode_t flags, void *holder)
974 struct request_queue *q;
975 struct block_device *bdev;
976 struct list_head *head = &fs_devices->devices;
977 struct btrfs_device *device;
978 struct btrfs_device *latest_dev = NULL;
979 struct buffer_head *bh;
980 struct btrfs_super_block *disk_super;
987 list_for_each_entry(device, head, dev_list) {
993 /* Just open everything we can; ignore failures here */
994 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
998 disk_super = (struct btrfs_super_block *)bh->b_data;
999 devid = btrfs_stack_device_id(&disk_super->dev_item);
1000 if (devid != device->devid)
1003 if (memcmp(device->uuid, disk_super->dev_item.uuid,
1007 device->generation = btrfs_super_generation(disk_super);
1009 device->generation > latest_dev->generation)
1010 latest_dev = device;
1012 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
1013 device->writeable = 0;
1015 device->writeable = !bdev_read_only(bdev);
1019 q = bdev_get_queue(bdev);
1020 if (blk_queue_discard(q))
1021 device->can_discard = 1;
1022 if (!blk_queue_nonrot(q))
1023 fs_devices->rotating = 1;
1025 device->bdev = bdev;
1026 device->in_fs_metadata = 0;
1027 device->mode = flags;
1029 fs_devices->open_devices++;
1030 if (device->writeable &&
1031 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1032 fs_devices->rw_devices++;
1033 list_add(&device->dev_alloc_list,
1034 &fs_devices->alloc_list);
1041 blkdev_put(bdev, flags);
1044 if (fs_devices->open_devices == 0) {
1048 fs_devices->seeding = seeding;
1049 fs_devices->opened = 1;
1050 fs_devices->latest_bdev = latest_dev->bdev;
1051 fs_devices->total_rw_bytes = 0;
1056 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1057 fmode_t flags, void *holder)
1061 mutex_lock(&uuid_mutex);
1062 if (fs_devices->opened) {
1063 fs_devices->opened++;
1066 ret = __btrfs_open_devices(fs_devices, flags, holder);
1068 mutex_unlock(&uuid_mutex);
1072 void btrfs_release_disk_super(struct page *page)
1078 int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1079 struct page **page, struct btrfs_super_block **disk_super)
1084 /* make sure our super fits in the device */
1085 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1088 /* make sure our super fits in the page */
1089 if (sizeof(**disk_super) > PAGE_SIZE)
1092 /* make sure our super doesn't straddle pages on disk */
1093 index = bytenr >> PAGE_SHIFT;
1094 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1097 /* pull in the page with our super */
1098 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1101 if (IS_ERR_OR_NULL(*page))
1106 /* align our pointer to the offset of the super block */
1107 *disk_super = p + (bytenr & ~PAGE_MASK);
1109 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1110 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1111 btrfs_release_disk_super(*page);
1115 if ((*disk_super)->label[0] &&
1116 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1117 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1123 * Look for a btrfs signature on a device. This may be called out of the mount path
1124 * and we are not allowed to call set_blocksize during the scan. The superblock
1125 * is read via pagecache
1127 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1128 struct btrfs_fs_devices **fs_devices_ret)
1130 struct btrfs_super_block *disk_super;
1131 struct block_device *bdev;
1140 * we would like to check all the supers, but that would make
1141 * a btrfs mount succeed after a mkfs from a different FS.
1142 * So, we need to add a special mount option to scan for
1143 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1145 bytenr = btrfs_sb_offset(0);
1146 flags |= FMODE_EXCL;
1147 mutex_lock(&uuid_mutex);
1149 bdev = blkdev_get_by_path(path, flags, holder);
1151 ret = PTR_ERR(bdev);
1155 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super))
1156 goto error_bdev_put;
1158 devid = btrfs_stack_device_id(&disk_super->dev_item);
1159 transid = btrfs_super_generation(disk_super);
1160 total_devices = btrfs_super_num_devices(disk_super);
1162 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
1164 if (disk_super->label[0]) {
1165 pr_info("BTRFS: device label %s ", disk_super->label);
1167 pr_info("BTRFS: device fsid %pU ", disk_super->fsid);
1170 pr_cont("devid %llu transid %llu %s\n", devid, transid, path);
1173 if (!ret && fs_devices_ret)
1174 (*fs_devices_ret)->total_devices = total_devices;
1176 btrfs_release_disk_super(page);
1179 blkdev_put(bdev, flags);
1181 mutex_unlock(&uuid_mutex);
1185 /* helper to account the used device space in the range */
1186 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1187 u64 end, u64 *length)
1189 struct btrfs_key key;
1190 struct btrfs_root *root = device->fs_info->dev_root;
1191 struct btrfs_dev_extent *dev_extent;
1192 struct btrfs_path *path;
1196 struct extent_buffer *l;
1200 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1203 path = btrfs_alloc_path();
1206 path->reada = READA_FORWARD;
1208 key.objectid = device->devid;
1210 key.type = BTRFS_DEV_EXTENT_KEY;
1212 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1216 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1223 slot = path->slots[0];
1224 if (slot >= btrfs_header_nritems(l)) {
1225 ret = btrfs_next_leaf(root, path);
1233 btrfs_item_key_to_cpu(l, &key, slot);
1235 if (key.objectid < device->devid)
1238 if (key.objectid > device->devid)
1241 if (key.type != BTRFS_DEV_EXTENT_KEY)
1244 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1245 extent_end = key.offset + btrfs_dev_extent_length(l,
1247 if (key.offset <= start && extent_end > end) {
1248 *length = end - start + 1;
1250 } else if (key.offset <= start && extent_end > start)
1251 *length += extent_end - start;
1252 else if (key.offset > start && extent_end <= end)
1253 *length += extent_end - key.offset;
1254 else if (key.offset > start && key.offset <= end) {
1255 *length += end - key.offset + 1;
1257 } else if (key.offset > end)
1265 btrfs_free_path(path);
1269 static int contains_pending_extent(struct btrfs_transaction *transaction,
1270 struct btrfs_device *device,
1271 u64 *start, u64 len)
1273 struct btrfs_fs_info *fs_info = device->fs_info;
1274 struct extent_map *em;
1275 struct list_head *search_list = &fs_info->pinned_chunks;
1277 u64 physical_start = *start;
1280 search_list = &transaction->pending_chunks;
1282 list_for_each_entry(em, search_list, list) {
1283 struct map_lookup *map;
1286 map = em->map_lookup;
1287 for (i = 0; i < map->num_stripes; i++) {
1290 if (map->stripes[i].dev != device)
1292 if (map->stripes[i].physical >= physical_start + len ||
1293 map->stripes[i].physical + em->orig_block_len <=
1297 * Make sure that while processing the pinned list we do
1298 * not override our *start with a lower value, because
1299 * we can have pinned chunks that fall within this
1300 * device hole and that have lower physical addresses
1301 * than the pending chunks we processed before. If we
1302 * do not take this special care we can end up getting
1303 * 2 pending chunks that start at the same physical
1304 * device offsets because the end offset of a pinned
1305 * chunk can be equal to the start offset of some
1308 end = map->stripes[i].physical + em->orig_block_len;
1315 if (search_list != &fs_info->pinned_chunks) {
1316 search_list = &fs_info->pinned_chunks;
1325 * find_free_dev_extent_start - find free space in the specified device
1326 * @device: the device which we search the free space in
1327 * @num_bytes: the size of the free space that we need
1328 * @search_start: the position from which to begin the search
1329 * @start: store the start of the free space.
1330 * @len: the size of the free space. that we find, or the size
1331 * of the max free space if we don't find suitable free space
1333 * this uses a pretty simple search, the expectation is that it is
1334 * called very infrequently and that a given device has a small number
1337 * @start is used to store the start of the free space if we find. But if we
1338 * don't find suitable free space, it will be used to store the start position
1339 * of the max free space.
1341 * @len is used to store the size of the free space that we find.
1342 * But if we don't find suitable free space, it is used to store the size of
1343 * the max free space.
1345 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1346 struct btrfs_device *device, u64 num_bytes,
1347 u64 search_start, u64 *start, u64 *len)
1349 struct btrfs_fs_info *fs_info = device->fs_info;
1350 struct btrfs_root *root = fs_info->dev_root;
1351 struct btrfs_key key;
1352 struct btrfs_dev_extent *dev_extent;
1353 struct btrfs_path *path;
1358 u64 search_end = device->total_bytes;
1361 struct extent_buffer *l;
1364 * We don't want to overwrite the superblock on the drive nor any area
1365 * used by the boot loader (grub for example), so we make sure to start
1366 * at an offset of at least 1MB.
1368 search_start = max_t(u64, search_start, SZ_1M);
1370 path = btrfs_alloc_path();
1374 max_hole_start = search_start;
1378 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1383 path->reada = READA_FORWARD;
1384 path->search_commit_root = 1;
1385 path->skip_locking = 1;
1387 key.objectid = device->devid;
1388 key.offset = search_start;
1389 key.type = BTRFS_DEV_EXTENT_KEY;
1391 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1395 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1400 while (search_start < search_end) {
1402 slot = path->slots[0];
1403 if (slot >= btrfs_header_nritems(l)) {
1404 ret = btrfs_next_leaf(root, path);
1412 btrfs_item_key_to_cpu(l, &key, slot);
1414 if (key.objectid < device->devid)
1417 if (key.objectid > device->devid)
1420 if (key.type != BTRFS_DEV_EXTENT_KEY)
1423 if (key.offset > search_end)
1426 if (key.offset > search_start) {
1427 hole_size = key.offset - search_start;
1430 * Have to check before we set max_hole_start, otherwise
1431 * we could end up sending back this offset anyway.
1433 if (contains_pending_extent(transaction, device,
1436 if (key.offset >= search_start) {
1437 hole_size = key.offset - search_start;
1444 if (hole_size > max_hole_size) {
1445 max_hole_start = search_start;
1446 max_hole_size = hole_size;
1450 * If this free space is greater than which we need,
1451 * it must be the max free space that we have found
1452 * until now, so max_hole_start must point to the start
1453 * of this free space and the length of this free space
1454 * is stored in max_hole_size. Thus, we return
1455 * max_hole_start and max_hole_size and go back to the
1458 if (hole_size >= num_bytes) {
1464 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1465 extent_end = key.offset + btrfs_dev_extent_length(l,
1467 if (extent_end > search_start)
1468 search_start = extent_end;
1475 * At this point, search_start should be the end of
1476 * allocated dev extents, and when shrinking the device,
1477 * search_end may be smaller than search_start.
1479 if (search_end > search_start) {
1480 hole_size = search_end - search_start;
1482 if (contains_pending_extent(transaction, device, &search_start,
1484 btrfs_release_path(path);
1488 if (hole_size > max_hole_size) {
1489 max_hole_start = search_start;
1490 max_hole_size = hole_size;
1495 if (max_hole_size < num_bytes)
1500 ASSERT(max_hole_start + max_hole_size <= search_end);
1502 btrfs_free_path(path);
1503 *start = max_hole_start;
1505 *len = max_hole_size;
1509 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1510 struct btrfs_device *device, u64 num_bytes,
1511 u64 *start, u64 *len)
1513 /* FIXME use last free of some kind */
1514 return find_free_dev_extent_start(trans->transaction, device,
1515 num_bytes, 0, start, len);
1518 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1519 struct btrfs_device *device,
1520 u64 start, u64 *dev_extent_len)
1522 struct btrfs_fs_info *fs_info = device->fs_info;
1523 struct btrfs_root *root = fs_info->dev_root;
1525 struct btrfs_path *path;
1526 struct btrfs_key key;
1527 struct btrfs_key found_key;
1528 struct extent_buffer *leaf = NULL;
1529 struct btrfs_dev_extent *extent = NULL;
1531 path = btrfs_alloc_path();
1535 key.objectid = device->devid;
1537 key.type = BTRFS_DEV_EXTENT_KEY;
1539 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1541 ret = btrfs_previous_item(root, path, key.objectid,
1542 BTRFS_DEV_EXTENT_KEY);
1545 leaf = path->nodes[0];
1546 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1547 extent = btrfs_item_ptr(leaf, path->slots[0],
1548 struct btrfs_dev_extent);
1549 BUG_ON(found_key.offset > start || found_key.offset +
1550 btrfs_dev_extent_length(leaf, extent) < start);
1552 btrfs_release_path(path);
1554 } else if (ret == 0) {
1555 leaf = path->nodes[0];
1556 extent = btrfs_item_ptr(leaf, path->slots[0],
1557 struct btrfs_dev_extent);
1559 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1563 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1565 ret = btrfs_del_item(trans, root, path);
1567 btrfs_handle_fs_error(fs_info, ret,
1568 "Failed to remove dev extent item");
1570 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1573 btrfs_free_path(path);
1577 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1578 struct btrfs_device *device,
1579 u64 chunk_offset, u64 start, u64 num_bytes)
1582 struct btrfs_path *path;
1583 struct btrfs_fs_info *fs_info = device->fs_info;
1584 struct btrfs_root *root = fs_info->dev_root;
1585 struct btrfs_dev_extent *extent;
1586 struct extent_buffer *leaf;
1587 struct btrfs_key key;
1589 WARN_ON(!device->in_fs_metadata);
1590 WARN_ON(device->is_tgtdev_for_dev_replace);
1591 path = btrfs_alloc_path();
1595 key.objectid = device->devid;
1597 key.type = BTRFS_DEV_EXTENT_KEY;
1598 ret = btrfs_insert_empty_item(trans, root, path, &key,
1603 leaf = path->nodes[0];
1604 extent = btrfs_item_ptr(leaf, path->slots[0],
1605 struct btrfs_dev_extent);
1606 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1607 BTRFS_CHUNK_TREE_OBJECTID);
1608 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1609 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1610 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1612 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1613 btrfs_mark_buffer_dirty(leaf);
1615 btrfs_free_path(path);
1619 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1621 struct extent_map_tree *em_tree;
1622 struct extent_map *em;
1626 em_tree = &fs_info->mapping_tree.map_tree;
1627 read_lock(&em_tree->lock);
1628 n = rb_last(&em_tree->map);
1630 em = rb_entry(n, struct extent_map, rb_node);
1631 ret = em->start + em->len;
1633 read_unlock(&em_tree->lock);
1638 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1642 struct btrfs_key key;
1643 struct btrfs_key found_key;
1644 struct btrfs_path *path;
1646 path = btrfs_alloc_path();
1650 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1651 key.type = BTRFS_DEV_ITEM_KEY;
1652 key.offset = (u64)-1;
1654 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1658 BUG_ON(ret == 0); /* Corruption */
1660 ret = btrfs_previous_item(fs_info->chunk_root, path,
1661 BTRFS_DEV_ITEMS_OBJECTID,
1662 BTRFS_DEV_ITEM_KEY);
1666 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1668 *devid_ret = found_key.offset + 1;
1672 btrfs_free_path(path);
1677 * the device information is stored in the chunk root
1678 * the btrfs_device struct should be fully filled in
1680 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1681 struct btrfs_fs_info *fs_info,
1682 struct btrfs_device *device)
1684 struct btrfs_root *root = fs_info->chunk_root;
1686 struct btrfs_path *path;
1687 struct btrfs_dev_item *dev_item;
1688 struct extent_buffer *leaf;
1689 struct btrfs_key key;
1692 path = btrfs_alloc_path();
1696 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1697 key.type = BTRFS_DEV_ITEM_KEY;
1698 key.offset = device->devid;
1700 ret = btrfs_insert_empty_item(trans, root, path, &key,
1705 leaf = path->nodes[0];
1706 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1708 btrfs_set_device_id(leaf, dev_item, device->devid);
1709 btrfs_set_device_generation(leaf, dev_item, 0);
1710 btrfs_set_device_type(leaf, dev_item, device->type);
1711 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1712 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1713 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1714 btrfs_set_device_total_bytes(leaf, dev_item,
1715 btrfs_device_get_disk_total_bytes(device));
1716 btrfs_set_device_bytes_used(leaf, dev_item,
1717 btrfs_device_get_bytes_used(device));
1718 btrfs_set_device_group(leaf, dev_item, 0);
1719 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1720 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1721 btrfs_set_device_start_offset(leaf, dev_item, 0);
1723 ptr = btrfs_device_uuid(dev_item);
1724 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1725 ptr = btrfs_device_fsid(dev_item);
1726 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1727 btrfs_mark_buffer_dirty(leaf);
1731 btrfs_free_path(path);
1736 * Function to update ctime/mtime for a given device path.
1737 * Mainly used for ctime/mtime based probe like libblkid.
1739 static void update_dev_time(const char *path_name)
1743 filp = filp_open(path_name, O_RDWR, 0);
1746 file_update_time(filp);
1747 filp_close(filp, NULL);
1750 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1751 struct btrfs_device *device)
1753 struct btrfs_root *root = fs_info->chunk_root;
1755 struct btrfs_path *path;
1756 struct btrfs_key key;
1757 struct btrfs_trans_handle *trans;
1759 path = btrfs_alloc_path();
1763 trans = btrfs_start_transaction(root, 0);
1764 if (IS_ERR(trans)) {
1765 btrfs_free_path(path);
1766 return PTR_ERR(trans);
1768 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1769 key.type = BTRFS_DEV_ITEM_KEY;
1770 key.offset = device->devid;
1772 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1776 btrfs_abort_transaction(trans, ret);
1777 btrfs_end_transaction(trans);
1781 ret = btrfs_del_item(trans, root, path);
1783 btrfs_abort_transaction(trans, ret);
1784 btrfs_end_transaction(trans);
1788 btrfs_free_path(path);
1790 ret = btrfs_commit_transaction(trans);
1795 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1796 * filesystem. It's up to the caller to adjust that number regarding eg. device
1799 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1807 seq = read_seqbegin(&fs_info->profiles_lock);
1809 all_avail = fs_info->avail_data_alloc_bits |
1810 fs_info->avail_system_alloc_bits |
1811 fs_info->avail_metadata_alloc_bits;
1812 } while (read_seqretry(&fs_info->profiles_lock, seq));
1814 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1815 if (!(all_avail & btrfs_raid_group[i]))
1818 if (num_devices < btrfs_raid_array[i].devs_min) {
1819 int ret = btrfs_raid_mindev_error[i];
1829 struct btrfs_device *btrfs_find_next_active_device(struct btrfs_fs_devices *fs_devs,
1830 struct btrfs_device *device)
1832 struct btrfs_device *next_device;
1834 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1835 if (next_device != device &&
1836 !next_device->missing && next_device->bdev)
1844 * Helper function to check if the given device is part of s_bdev / latest_bdev
1845 * and replace it with the provided or the next active device, in the context
1846 * where this function called, there should be always be another device (or
1847 * this_dev) which is active.
1849 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1850 struct btrfs_device *device, struct btrfs_device *this_dev)
1852 struct btrfs_device *next_device;
1855 next_device = this_dev;
1857 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1859 ASSERT(next_device);
1861 if (fs_info->sb->s_bdev &&
1862 (fs_info->sb->s_bdev == device->bdev))
1863 fs_info->sb->s_bdev = next_device->bdev;
1865 if (fs_info->fs_devices->latest_bdev == device->bdev)
1866 fs_info->fs_devices->latest_bdev = next_device->bdev;
1869 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1872 struct btrfs_device *device;
1873 struct btrfs_fs_devices *cur_devices;
1877 mutex_lock(&uuid_mutex);
1879 num_devices = fs_info->fs_devices->num_devices;
1880 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
1881 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1882 WARN_ON(num_devices < 1);
1885 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
1887 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1891 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1896 if (device->is_tgtdev_for_dev_replace) {
1897 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1901 if (device->writeable && fs_info->fs_devices->rw_devices == 1) {
1902 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1906 if (device->writeable) {
1907 mutex_lock(&fs_info->chunk_mutex);
1908 list_del_init(&device->dev_alloc_list);
1909 device->fs_devices->rw_devices--;
1910 mutex_unlock(&fs_info->chunk_mutex);
1913 mutex_unlock(&uuid_mutex);
1914 ret = btrfs_shrink_device(device, 0);
1915 mutex_lock(&uuid_mutex);
1920 * TODO: the superblock still includes this device in its num_devices
1921 * counter although write_all_supers() is not locked out. This
1922 * could give a filesystem state which requires a degraded mount.
1924 ret = btrfs_rm_dev_item(fs_info, device);
1928 device->in_fs_metadata = 0;
1929 btrfs_scrub_cancel_dev(fs_info, device);
1932 * the device list mutex makes sure that we don't change
1933 * the device list while someone else is writing out all
1934 * the device supers. Whoever is writing all supers, should
1935 * lock the device list mutex before getting the number of
1936 * devices in the super block (super_copy). Conversely,
1937 * whoever updates the number of devices in the super block
1938 * (super_copy) should hold the device list mutex.
1941 cur_devices = device->fs_devices;
1942 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1943 list_del_rcu(&device->dev_list);
1945 device->fs_devices->num_devices--;
1946 device->fs_devices->total_devices--;
1948 if (device->missing)
1949 device->fs_devices->missing_devices--;
1951 btrfs_assign_next_active_device(fs_info, device, NULL);
1954 device->fs_devices->open_devices--;
1955 /* remove sysfs entry */
1956 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
1959 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1960 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
1961 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1964 * at this point, the device is zero sized and detached from
1965 * the devices list. All that's left is to zero out the old
1966 * supers and free the device.
1968 if (device->writeable)
1969 btrfs_scratch_superblocks(device->bdev, device->name->str);
1971 btrfs_close_bdev(device);
1972 call_rcu(&device->rcu, free_device);
1974 if (cur_devices->open_devices == 0) {
1975 struct btrfs_fs_devices *fs_devices;
1976 fs_devices = fs_info->fs_devices;
1977 while (fs_devices) {
1978 if (fs_devices->seed == cur_devices) {
1979 fs_devices->seed = cur_devices->seed;
1982 fs_devices = fs_devices->seed;
1984 cur_devices->seed = NULL;
1985 __btrfs_close_devices(cur_devices);
1986 free_fs_devices(cur_devices);
1990 mutex_unlock(&uuid_mutex);
1994 if (device->writeable) {
1995 mutex_lock(&fs_info->chunk_mutex);
1996 list_add(&device->dev_alloc_list,
1997 &fs_info->fs_devices->alloc_list);
1998 device->fs_devices->rw_devices++;
1999 mutex_unlock(&fs_info->chunk_mutex);
2004 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2005 struct btrfs_device *srcdev)
2007 struct btrfs_fs_devices *fs_devices;
2009 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
2012 * in case of fs with no seed, srcdev->fs_devices will point
2013 * to fs_devices of fs_info. However when the dev being replaced is
2014 * a seed dev it will point to the seed's local fs_devices. In short
2015 * srcdev will have its correct fs_devices in both the cases.
2017 fs_devices = srcdev->fs_devices;
2019 list_del_rcu(&srcdev->dev_list);
2020 list_del_rcu(&srcdev->dev_alloc_list);
2021 fs_devices->num_devices--;
2022 if (srcdev->missing)
2023 fs_devices->missing_devices--;
2025 if (srcdev->writeable)
2026 fs_devices->rw_devices--;
2029 fs_devices->open_devices--;
2032 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2033 struct btrfs_device *srcdev)
2035 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2037 if (srcdev->writeable) {
2038 /* zero out the old super if it is writable */
2039 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2042 btrfs_close_bdev(srcdev);
2044 call_rcu(&srcdev->rcu, free_device);
2047 * unless fs_devices is seed fs, num_devices shouldn't go
2050 BUG_ON(!fs_devices->num_devices && !fs_devices->seeding);
2052 /* if this is no devs we rather delete the fs_devices */
2053 if (!fs_devices->num_devices) {
2054 struct btrfs_fs_devices *tmp_fs_devices;
2056 tmp_fs_devices = fs_info->fs_devices;
2057 while (tmp_fs_devices) {
2058 if (tmp_fs_devices->seed == fs_devices) {
2059 tmp_fs_devices->seed = fs_devices->seed;
2062 tmp_fs_devices = tmp_fs_devices->seed;
2064 fs_devices->seed = NULL;
2065 __btrfs_close_devices(fs_devices);
2066 free_fs_devices(fs_devices);
2070 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2071 struct btrfs_device *tgtdev)
2073 mutex_lock(&uuid_mutex);
2075 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2077 btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2080 fs_info->fs_devices->open_devices--;
2082 fs_info->fs_devices->num_devices--;
2084 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2086 list_del_rcu(&tgtdev->dev_list);
2088 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2089 mutex_unlock(&uuid_mutex);
2092 * The update_dev_time() with in btrfs_scratch_superblocks()
2093 * may lead to a call to btrfs_show_devname() which will try
2094 * to hold device_list_mutex. And here this device
2095 * is already out of device list, so we don't have to hold
2096 * the device_list_mutex lock.
2098 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2100 btrfs_close_bdev(tgtdev);
2101 call_rcu(&tgtdev->rcu, free_device);
2104 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2105 const char *device_path,
2106 struct btrfs_device **device)
2109 struct btrfs_super_block *disk_super;
2112 struct block_device *bdev;
2113 struct buffer_head *bh;
2116 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2117 fs_info->bdev_holder, 0, &bdev, &bh);
2120 disk_super = (struct btrfs_super_block *)bh->b_data;
2121 devid = btrfs_stack_device_id(&disk_super->dev_item);
2122 dev_uuid = disk_super->dev_item.uuid;
2123 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2127 blkdev_put(bdev, FMODE_READ);
2131 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2132 const char *device_path,
2133 struct btrfs_device **device)
2136 if (strcmp(device_path, "missing") == 0) {
2137 struct list_head *devices;
2138 struct btrfs_device *tmp;
2140 devices = &fs_info->fs_devices->devices;
2142 * It is safe to read the devices since the volume_mutex
2143 * is held by the caller.
2145 list_for_each_entry(tmp, devices, dev_list) {
2146 if (tmp->in_fs_metadata && !tmp->bdev) {
2153 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2157 return btrfs_find_device_by_path(fs_info, device_path, device);
2162 * Lookup a device given by device id, or the path if the id is 0.
2164 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2165 const char *devpath,
2166 struct btrfs_device **device)
2172 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2176 if (!devpath || !devpath[0])
2179 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2186 * does all the dirty work required for changing file system's UUID.
2188 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2190 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2191 struct btrfs_fs_devices *old_devices;
2192 struct btrfs_fs_devices *seed_devices;
2193 struct btrfs_super_block *disk_super = fs_info->super_copy;
2194 struct btrfs_device *device;
2197 BUG_ON(!mutex_is_locked(&uuid_mutex));
2198 if (!fs_devices->seeding)
2201 seed_devices = alloc_fs_devices(NULL);
2202 if (IS_ERR(seed_devices))
2203 return PTR_ERR(seed_devices);
2205 old_devices = clone_fs_devices(fs_devices);
2206 if (IS_ERR(old_devices)) {
2207 kfree(seed_devices);
2208 return PTR_ERR(old_devices);
2211 list_add(&old_devices->list, &fs_uuids);
2213 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2214 seed_devices->opened = 1;
2215 INIT_LIST_HEAD(&seed_devices->devices);
2216 INIT_LIST_HEAD(&seed_devices->alloc_list);
2217 mutex_init(&seed_devices->device_list_mutex);
2219 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2220 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2222 list_for_each_entry(device, &seed_devices->devices, dev_list)
2223 device->fs_devices = seed_devices;
2225 mutex_lock(&fs_info->chunk_mutex);
2226 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2227 mutex_unlock(&fs_info->chunk_mutex);
2229 fs_devices->seeding = 0;
2230 fs_devices->num_devices = 0;
2231 fs_devices->open_devices = 0;
2232 fs_devices->missing_devices = 0;
2233 fs_devices->rotating = 0;
2234 fs_devices->seed = seed_devices;
2236 generate_random_uuid(fs_devices->fsid);
2237 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2238 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2239 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2241 super_flags = btrfs_super_flags(disk_super) &
2242 ~BTRFS_SUPER_FLAG_SEEDING;
2243 btrfs_set_super_flags(disk_super, super_flags);
2249 * Store the expected generation for seed devices in device items.
2251 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2252 struct btrfs_fs_info *fs_info)
2254 struct btrfs_root *root = fs_info->chunk_root;
2255 struct btrfs_path *path;
2256 struct extent_buffer *leaf;
2257 struct btrfs_dev_item *dev_item;
2258 struct btrfs_device *device;
2259 struct btrfs_key key;
2260 u8 fs_uuid[BTRFS_FSID_SIZE];
2261 u8 dev_uuid[BTRFS_UUID_SIZE];
2265 path = btrfs_alloc_path();
2269 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2271 key.type = BTRFS_DEV_ITEM_KEY;
2274 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2278 leaf = path->nodes[0];
2280 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2281 ret = btrfs_next_leaf(root, path);
2286 leaf = path->nodes[0];
2287 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2288 btrfs_release_path(path);
2292 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2293 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2294 key.type != BTRFS_DEV_ITEM_KEY)
2297 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2298 struct btrfs_dev_item);
2299 devid = btrfs_device_id(leaf, dev_item);
2300 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2302 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2304 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2305 BUG_ON(!device); /* Logic error */
2307 if (device->fs_devices->seeding) {
2308 btrfs_set_device_generation(leaf, dev_item,
2309 device->generation);
2310 btrfs_mark_buffer_dirty(leaf);
2318 btrfs_free_path(path);
2322 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2324 struct btrfs_root *root = fs_info->dev_root;
2325 struct request_queue *q;
2326 struct btrfs_trans_handle *trans;
2327 struct btrfs_device *device;
2328 struct block_device *bdev;
2329 struct list_head *devices;
2330 struct super_block *sb = fs_info->sb;
2331 struct rcu_string *name;
2333 int seeding_dev = 0;
2336 if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2339 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2340 fs_info->bdev_holder);
2342 return PTR_ERR(bdev);
2344 if (fs_info->fs_devices->seeding) {
2346 down_write(&sb->s_umount);
2347 mutex_lock(&uuid_mutex);
2350 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2352 devices = &fs_info->fs_devices->devices;
2354 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2355 list_for_each_entry(device, devices, dev_list) {
2356 if (device->bdev == bdev) {
2359 &fs_info->fs_devices->device_list_mutex);
2363 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2365 device = btrfs_alloc_device(fs_info, NULL, NULL);
2366 if (IS_ERR(device)) {
2367 /* we can safely leave the fs_devices entry around */
2368 ret = PTR_ERR(device);
2372 name = rcu_string_strdup(device_path, GFP_KERNEL);
2378 rcu_assign_pointer(device->name, name);
2380 trans = btrfs_start_transaction(root, 0);
2381 if (IS_ERR(trans)) {
2382 rcu_string_free(device->name);
2384 ret = PTR_ERR(trans);
2388 q = bdev_get_queue(bdev);
2389 if (blk_queue_discard(q))
2390 device->can_discard = 1;
2391 device->writeable = 1;
2392 device->generation = trans->transid;
2393 device->io_width = fs_info->sectorsize;
2394 device->io_align = fs_info->sectorsize;
2395 device->sector_size = fs_info->sectorsize;
2396 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2397 fs_info->sectorsize);
2398 device->disk_total_bytes = device->total_bytes;
2399 device->commit_total_bytes = device->total_bytes;
2400 device->fs_info = fs_info;
2401 device->bdev = bdev;
2402 device->in_fs_metadata = 1;
2403 device->is_tgtdev_for_dev_replace = 0;
2404 device->mode = FMODE_EXCL;
2405 device->dev_stats_valid = 1;
2406 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2409 sb->s_flags &= ~MS_RDONLY;
2410 ret = btrfs_prepare_sprout(fs_info);
2411 BUG_ON(ret); /* -ENOMEM */
2414 device->fs_devices = fs_info->fs_devices;
2416 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2417 mutex_lock(&fs_info->chunk_mutex);
2418 list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2419 list_add(&device->dev_alloc_list,
2420 &fs_info->fs_devices->alloc_list);
2421 fs_info->fs_devices->num_devices++;
2422 fs_info->fs_devices->open_devices++;
2423 fs_info->fs_devices->rw_devices++;
2424 fs_info->fs_devices->total_devices++;
2425 fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2427 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2429 if (!blk_queue_nonrot(q))
2430 fs_info->fs_devices->rotating = 1;
2432 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2433 btrfs_set_super_total_bytes(fs_info->super_copy,
2434 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2436 tmp = btrfs_super_num_devices(fs_info->super_copy);
2437 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2440 * we've got more storage, clear any full flags on the space
2443 btrfs_clear_space_info_full(fs_info);
2445 mutex_unlock(&fs_info->chunk_mutex);
2447 /* Add sysfs device entry */
2448 btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2450 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2453 mutex_lock(&fs_info->chunk_mutex);
2454 ret = init_first_rw_device(trans, fs_info);
2455 mutex_unlock(&fs_info->chunk_mutex);
2457 btrfs_abort_transaction(trans, ret);
2462 ret = btrfs_add_device(trans, fs_info, device);
2464 btrfs_abort_transaction(trans, ret);
2469 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2471 ret = btrfs_finish_sprout(trans, fs_info);
2473 btrfs_abort_transaction(trans, ret);
2477 /* Sprouting would change fsid of the mounted root,
2478 * so rename the fsid on the sysfs
2480 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2482 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2484 "sysfs: failed to create fsid for sprout");
2487 ret = btrfs_commit_transaction(trans);
2490 mutex_unlock(&uuid_mutex);
2491 up_write(&sb->s_umount);
2493 if (ret) /* transaction commit */
2496 ret = btrfs_relocate_sys_chunks(fs_info);
2498 btrfs_handle_fs_error(fs_info, ret,
2499 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2500 trans = btrfs_attach_transaction(root);
2501 if (IS_ERR(trans)) {
2502 if (PTR_ERR(trans) == -ENOENT)
2504 return PTR_ERR(trans);
2506 ret = btrfs_commit_transaction(trans);
2509 /* Update ctime/mtime for libblkid */
2510 update_dev_time(device_path);
2515 sb->s_flags |= MS_RDONLY;
2516 btrfs_end_transaction(trans);
2517 rcu_string_free(device->name);
2518 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2521 blkdev_put(bdev, FMODE_EXCL);
2523 mutex_unlock(&uuid_mutex);
2524 up_write(&sb->s_umount);
2529 int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2530 const char *device_path,
2531 struct btrfs_device *srcdev,
2532 struct btrfs_device **device_out)
2534 struct request_queue *q;
2535 struct btrfs_device *device;
2536 struct block_device *bdev;
2537 struct list_head *devices;
2538 struct rcu_string *name;
2539 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2543 if (fs_info->fs_devices->seeding) {
2544 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2548 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2549 fs_info->bdev_holder);
2551 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2552 return PTR_ERR(bdev);
2555 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2557 devices = &fs_info->fs_devices->devices;
2558 list_for_each_entry(device, devices, dev_list) {
2559 if (device->bdev == bdev) {
2561 "target device is in the filesystem!");
2568 if (i_size_read(bdev->bd_inode) <
2569 btrfs_device_get_total_bytes(srcdev)) {
2571 "target device is smaller than source device!");
2577 device = btrfs_alloc_device(NULL, &devid, NULL);
2578 if (IS_ERR(device)) {
2579 ret = PTR_ERR(device);
2583 name = rcu_string_strdup(device_path, GFP_KERNEL);
2589 rcu_assign_pointer(device->name, name);
2591 q = bdev_get_queue(bdev);
2592 if (blk_queue_discard(q))
2593 device->can_discard = 1;
2594 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2595 device->writeable = 1;
2596 device->generation = 0;
2597 device->io_width = fs_info->sectorsize;
2598 device->io_align = fs_info->sectorsize;
2599 device->sector_size = fs_info->sectorsize;
2600 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2601 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2602 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2603 ASSERT(list_empty(&srcdev->resized_list));
2604 device->commit_total_bytes = srcdev->commit_total_bytes;
2605 device->commit_bytes_used = device->bytes_used;
2606 device->fs_info = fs_info;
2607 device->bdev = bdev;
2608 device->in_fs_metadata = 1;
2609 device->is_tgtdev_for_dev_replace = 1;
2610 device->mode = FMODE_EXCL;
2611 device->dev_stats_valid = 1;
2612 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2613 device->fs_devices = fs_info->fs_devices;
2614 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2615 fs_info->fs_devices->num_devices++;
2616 fs_info->fs_devices->open_devices++;
2617 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2619 *device_out = device;
2623 blkdev_put(bdev, FMODE_EXCL);
2627 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2628 struct btrfs_device *tgtdev)
2630 u32 sectorsize = fs_info->sectorsize;
2632 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2633 tgtdev->io_width = sectorsize;
2634 tgtdev->io_align = sectorsize;
2635 tgtdev->sector_size = sectorsize;
2636 tgtdev->fs_info = fs_info;
2637 tgtdev->in_fs_metadata = 1;
2640 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2641 struct btrfs_device *device)
2644 struct btrfs_path *path;
2645 struct btrfs_root *root = device->fs_info->chunk_root;
2646 struct btrfs_dev_item *dev_item;
2647 struct extent_buffer *leaf;
2648 struct btrfs_key key;
2650 path = btrfs_alloc_path();
2654 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2655 key.type = BTRFS_DEV_ITEM_KEY;
2656 key.offset = device->devid;
2658 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2667 leaf = path->nodes[0];
2668 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2670 btrfs_set_device_id(leaf, dev_item, device->devid);
2671 btrfs_set_device_type(leaf, dev_item, device->type);
2672 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2673 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2674 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2675 btrfs_set_device_total_bytes(leaf, dev_item,
2676 btrfs_device_get_disk_total_bytes(device));
2677 btrfs_set_device_bytes_used(leaf, dev_item,
2678 btrfs_device_get_bytes_used(device));
2679 btrfs_mark_buffer_dirty(leaf);
2682 btrfs_free_path(path);
2686 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2687 struct btrfs_device *device, u64 new_size)
2689 struct btrfs_fs_info *fs_info = device->fs_info;
2690 struct btrfs_super_block *super_copy = fs_info->super_copy;
2691 struct btrfs_fs_devices *fs_devices;
2695 if (!device->writeable)
2698 new_size = round_down(new_size, fs_info->sectorsize);
2700 mutex_lock(&fs_info->chunk_mutex);
2701 old_total = btrfs_super_total_bytes(super_copy);
2702 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2704 if (new_size <= device->total_bytes ||
2705 device->is_tgtdev_for_dev_replace) {
2706 mutex_unlock(&fs_info->chunk_mutex);
2710 fs_devices = fs_info->fs_devices;
2712 btrfs_set_super_total_bytes(super_copy,
2713 round_down(old_total + diff, fs_info->sectorsize));
2714 device->fs_devices->total_rw_bytes += diff;
2716 btrfs_device_set_total_bytes(device, new_size);
2717 btrfs_device_set_disk_total_bytes(device, new_size);
2718 btrfs_clear_space_info_full(device->fs_info);
2719 if (list_empty(&device->resized_list))
2720 list_add_tail(&device->resized_list,
2721 &fs_devices->resized_devices);
2722 mutex_unlock(&fs_info->chunk_mutex);
2724 return btrfs_update_device(trans, device);
2727 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2728 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2730 struct btrfs_root *root = fs_info->chunk_root;
2732 struct btrfs_path *path;
2733 struct btrfs_key key;
2735 path = btrfs_alloc_path();
2739 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2740 key.offset = chunk_offset;
2741 key.type = BTRFS_CHUNK_ITEM_KEY;
2743 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2746 else if (ret > 0) { /* Logic error or corruption */
2747 btrfs_handle_fs_error(fs_info, -ENOENT,
2748 "Failed lookup while freeing chunk.");
2753 ret = btrfs_del_item(trans, root, path);
2755 btrfs_handle_fs_error(fs_info, ret,
2756 "Failed to delete chunk item.");
2758 btrfs_free_path(path);
2762 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2764 struct btrfs_super_block *super_copy = fs_info->super_copy;
2765 struct btrfs_disk_key *disk_key;
2766 struct btrfs_chunk *chunk;
2773 struct btrfs_key key;
2775 mutex_lock(&fs_info->chunk_mutex);
2776 array_size = btrfs_super_sys_array_size(super_copy);
2778 ptr = super_copy->sys_chunk_array;
2781 while (cur < array_size) {
2782 disk_key = (struct btrfs_disk_key *)ptr;
2783 btrfs_disk_key_to_cpu(&key, disk_key);
2785 len = sizeof(*disk_key);
2787 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2788 chunk = (struct btrfs_chunk *)(ptr + len);
2789 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2790 len += btrfs_chunk_item_size(num_stripes);
2795 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2796 key.offset == chunk_offset) {
2797 memmove(ptr, ptr + len, array_size - (cur + len));
2799 btrfs_set_super_sys_array_size(super_copy, array_size);
2805 mutex_unlock(&fs_info->chunk_mutex);
2809 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2810 u64 logical, u64 length)
2812 struct extent_map_tree *em_tree;
2813 struct extent_map *em;
2815 em_tree = &fs_info->mapping_tree.map_tree;
2816 read_lock(&em_tree->lock);
2817 em = lookup_extent_mapping(em_tree, logical, length);
2818 read_unlock(&em_tree->lock);
2821 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2823 return ERR_PTR(-EINVAL);
2826 if (em->start > logical || em->start + em->len < logical) {
2828 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2829 logical, length, em->start, em->start + em->len);
2830 free_extent_map(em);
2831 return ERR_PTR(-EINVAL);
2834 /* callers are responsible for dropping em's ref. */
2838 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2839 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2841 struct extent_map *em;
2842 struct map_lookup *map;
2843 u64 dev_extent_len = 0;
2845 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2847 em = get_chunk_map(fs_info, chunk_offset, 1);
2850 * This is a logic error, but we don't want to just rely on the
2851 * user having built with ASSERT enabled, so if ASSERT doesn't
2852 * do anything we still error out.
2857 map = em->map_lookup;
2858 mutex_lock(&fs_info->chunk_mutex);
2859 check_system_chunk(trans, fs_info, map->type);
2860 mutex_unlock(&fs_info->chunk_mutex);
2863 * Take the device list mutex to prevent races with the final phase of
2864 * a device replace operation that replaces the device object associated
2865 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2867 mutex_lock(&fs_devices->device_list_mutex);
2868 for (i = 0; i < map->num_stripes; i++) {
2869 struct btrfs_device *device = map->stripes[i].dev;
2870 ret = btrfs_free_dev_extent(trans, device,
2871 map->stripes[i].physical,
2874 mutex_unlock(&fs_devices->device_list_mutex);
2875 btrfs_abort_transaction(trans, ret);
2879 if (device->bytes_used > 0) {
2880 mutex_lock(&fs_info->chunk_mutex);
2881 btrfs_device_set_bytes_used(device,
2882 device->bytes_used - dev_extent_len);
2883 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2884 btrfs_clear_space_info_full(fs_info);
2885 mutex_unlock(&fs_info->chunk_mutex);
2888 if (map->stripes[i].dev) {
2889 ret = btrfs_update_device(trans, map->stripes[i].dev);
2891 mutex_unlock(&fs_devices->device_list_mutex);
2892 btrfs_abort_transaction(trans, ret);
2897 mutex_unlock(&fs_devices->device_list_mutex);
2899 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2901 btrfs_abort_transaction(trans, ret);
2905 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2907 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2908 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2910 btrfs_abort_transaction(trans, ret);
2915 ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2917 btrfs_abort_transaction(trans, ret);
2923 free_extent_map(em);
2927 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2929 struct btrfs_root *root = fs_info->chunk_root;
2930 struct btrfs_trans_handle *trans;
2934 * Prevent races with automatic removal of unused block groups.
2935 * After we relocate and before we remove the chunk with offset
2936 * chunk_offset, automatic removal of the block group can kick in,
2937 * resulting in a failure when calling btrfs_remove_chunk() below.
2939 * Make sure to acquire this mutex before doing a tree search (dev
2940 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2941 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2942 * we release the path used to search the chunk/dev tree and before
2943 * the current task acquires this mutex and calls us.
2945 ASSERT(mutex_is_locked(&fs_info->delete_unused_bgs_mutex));
2947 ret = btrfs_can_relocate(fs_info, chunk_offset);
2951 /* step one, relocate all the extents inside this chunk */
2952 btrfs_scrub_pause(fs_info);
2953 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2954 btrfs_scrub_continue(fs_info);
2958 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2960 if (IS_ERR(trans)) {
2961 ret = PTR_ERR(trans);
2962 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2967 * step two, delete the device extents and the
2968 * chunk tree entries
2970 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
2971 btrfs_end_transaction(trans);
2975 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2977 struct btrfs_root *chunk_root = fs_info->chunk_root;
2978 struct btrfs_path *path;
2979 struct extent_buffer *leaf;
2980 struct btrfs_chunk *chunk;
2981 struct btrfs_key key;
2982 struct btrfs_key found_key;
2984 bool retried = false;
2988 path = btrfs_alloc_path();
2993 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2994 key.offset = (u64)-1;
2995 key.type = BTRFS_CHUNK_ITEM_KEY;
2998 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2999 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3001 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3004 BUG_ON(ret == 0); /* Corruption */
3006 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3009 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3015 leaf = path->nodes[0];
3016 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3018 chunk = btrfs_item_ptr(leaf, path->slots[0],
3019 struct btrfs_chunk);
3020 chunk_type = btrfs_chunk_type(leaf, chunk);
3021 btrfs_release_path(path);
3023 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3024 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3030 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3032 if (found_key.offset == 0)
3034 key.offset = found_key.offset - 1;
3037 if (failed && !retried) {
3041 } else if (WARN_ON(failed && retried)) {
3045 btrfs_free_path(path);
3049 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3050 struct btrfs_balance_control *bctl)
3052 struct btrfs_root *root = fs_info->tree_root;
3053 struct btrfs_trans_handle *trans;
3054 struct btrfs_balance_item *item;
3055 struct btrfs_disk_balance_args disk_bargs;
3056 struct btrfs_path *path;
3057 struct extent_buffer *leaf;
3058 struct btrfs_key key;
3061 path = btrfs_alloc_path();
3065 trans = btrfs_start_transaction(root, 0);
3066 if (IS_ERR(trans)) {
3067 btrfs_free_path(path);
3068 return PTR_ERR(trans);
3071 key.objectid = BTRFS_BALANCE_OBJECTID;
3072 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3075 ret = btrfs_insert_empty_item(trans, root, path, &key,
3080 leaf = path->nodes[0];
3081 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3083 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3085 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3086 btrfs_set_balance_data(leaf, item, &disk_bargs);
3087 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3088 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3089 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3090 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3092 btrfs_set_balance_flags(leaf, item, bctl->flags);
3094 btrfs_mark_buffer_dirty(leaf);
3096 btrfs_free_path(path);
3097 err = btrfs_commit_transaction(trans);
3103 static int del_balance_item(struct btrfs_fs_info *fs_info)
3105 struct btrfs_root *root = fs_info->tree_root;
3106 struct btrfs_trans_handle *trans;
3107 struct btrfs_path *path;
3108 struct btrfs_key key;
3111 path = btrfs_alloc_path();
3115 trans = btrfs_start_transaction(root, 0);
3116 if (IS_ERR(trans)) {
3117 btrfs_free_path(path);
3118 return PTR_ERR(trans);
3121 key.objectid = BTRFS_BALANCE_OBJECTID;
3122 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3125 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3133 ret = btrfs_del_item(trans, root, path);
3135 btrfs_free_path(path);
3136 err = btrfs_commit_transaction(trans);
3143 * This is a heuristic used to reduce the number of chunks balanced on
3144 * resume after balance was interrupted.
3146 static void update_balance_args(struct btrfs_balance_control *bctl)
3149 * Turn on soft mode for chunk types that were being converted.
3151 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3152 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3153 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3154 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3155 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3156 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3159 * Turn on usage filter if is not already used. The idea is
3160 * that chunks that we have already balanced should be
3161 * reasonably full. Don't do it for chunks that are being
3162 * converted - that will keep us from relocating unconverted
3163 * (albeit full) chunks.
3165 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3166 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3167 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3168 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3169 bctl->data.usage = 90;
3171 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3172 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3173 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3174 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3175 bctl->sys.usage = 90;
3177 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3178 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3179 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3180 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3181 bctl->meta.usage = 90;
3186 * Should be called with both balance and volume mutexes held to
3187 * serialize other volume operations (add_dev/rm_dev/resize) with
3188 * restriper. Same goes for unset_balance_control.
3190 static void set_balance_control(struct btrfs_balance_control *bctl)
3192 struct btrfs_fs_info *fs_info = bctl->fs_info;
3194 BUG_ON(fs_info->balance_ctl);
3196 spin_lock(&fs_info->balance_lock);
3197 fs_info->balance_ctl = bctl;
3198 spin_unlock(&fs_info->balance_lock);
3201 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3203 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3205 BUG_ON(!fs_info->balance_ctl);
3207 spin_lock(&fs_info->balance_lock);
3208 fs_info->balance_ctl = NULL;
3209 spin_unlock(&fs_info->balance_lock);
3215 * Balance filters. Return 1 if chunk should be filtered out
3216 * (should not be balanced).
3218 static int chunk_profiles_filter(u64 chunk_type,
3219 struct btrfs_balance_args *bargs)
3221 chunk_type = chunk_to_extended(chunk_type) &
3222 BTRFS_EXTENDED_PROFILE_MASK;
3224 if (bargs->profiles & chunk_type)
3230 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3231 struct btrfs_balance_args *bargs)
3233 struct btrfs_block_group_cache *cache;
3235 u64 user_thresh_min;
3236 u64 user_thresh_max;
3239 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3240 chunk_used = btrfs_block_group_used(&cache->item);
3242 if (bargs->usage_min == 0)
3243 user_thresh_min = 0;
3245 user_thresh_min = div_factor_fine(cache->key.offset,
3248 if (bargs->usage_max == 0)
3249 user_thresh_max = 1;
3250 else if (bargs->usage_max > 100)
3251 user_thresh_max = cache->key.offset;
3253 user_thresh_max = div_factor_fine(cache->key.offset,
3256 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3259 btrfs_put_block_group(cache);
3263 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3264 u64 chunk_offset, struct btrfs_balance_args *bargs)
3266 struct btrfs_block_group_cache *cache;
3267 u64 chunk_used, user_thresh;
3270 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3271 chunk_used = btrfs_block_group_used(&cache->item);
3273 if (bargs->usage_min == 0)
3275 else if (bargs->usage > 100)
3276 user_thresh = cache->key.offset;
3278 user_thresh = div_factor_fine(cache->key.offset,
3281 if (chunk_used < user_thresh)
3284 btrfs_put_block_group(cache);
3288 static int chunk_devid_filter(struct extent_buffer *leaf,
3289 struct btrfs_chunk *chunk,
3290 struct btrfs_balance_args *bargs)
3292 struct btrfs_stripe *stripe;
3293 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3296 for (i = 0; i < num_stripes; i++) {
3297 stripe = btrfs_stripe_nr(chunk, i);
3298 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3305 /* [pstart, pend) */
3306 static int chunk_drange_filter(struct extent_buffer *leaf,
3307 struct btrfs_chunk *chunk,
3308 struct btrfs_balance_args *bargs)
3310 struct btrfs_stripe *stripe;
3311 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3317 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3320 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3321 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3322 factor = num_stripes / 2;
3323 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3324 factor = num_stripes - 1;
3325 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3326 factor = num_stripes - 2;
3328 factor = num_stripes;
3331 for (i = 0; i < num_stripes; i++) {
3332 stripe = btrfs_stripe_nr(chunk, i);
3333 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3336 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3337 stripe_length = btrfs_chunk_length(leaf, chunk);
3338 stripe_length = div_u64(stripe_length, factor);
3340 if (stripe_offset < bargs->pend &&
3341 stripe_offset + stripe_length > bargs->pstart)
3348 /* [vstart, vend) */
3349 static int chunk_vrange_filter(struct extent_buffer *leaf,
3350 struct btrfs_chunk *chunk,
3352 struct btrfs_balance_args *bargs)
3354 if (chunk_offset < bargs->vend &&
3355 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3356 /* at least part of the chunk is inside this vrange */
3362 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3363 struct btrfs_chunk *chunk,
3364 struct btrfs_balance_args *bargs)
3366 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3368 if (bargs->stripes_min <= num_stripes
3369 && num_stripes <= bargs->stripes_max)
3375 static int chunk_soft_convert_filter(u64 chunk_type,
3376 struct btrfs_balance_args *bargs)
3378 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3381 chunk_type = chunk_to_extended(chunk_type) &
3382 BTRFS_EXTENDED_PROFILE_MASK;
3384 if (bargs->target == chunk_type)
3390 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3391 struct extent_buffer *leaf,
3392 struct btrfs_chunk *chunk, u64 chunk_offset)
3394 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3395 struct btrfs_balance_args *bargs = NULL;
3396 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3399 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3400 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3404 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3405 bargs = &bctl->data;
3406 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3408 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3409 bargs = &bctl->meta;
3411 /* profiles filter */
3412 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3413 chunk_profiles_filter(chunk_type, bargs)) {
3418 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3419 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3421 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3422 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3427 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3428 chunk_devid_filter(leaf, chunk, bargs)) {
3432 /* drange filter, makes sense only with devid filter */
3433 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3434 chunk_drange_filter(leaf, chunk, bargs)) {
3439 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3440 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3444 /* stripes filter */
3445 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3446 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3450 /* soft profile changing mode */
3451 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3452 chunk_soft_convert_filter(chunk_type, bargs)) {
3457 * limited by count, must be the last filter
3459 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3460 if (bargs->limit == 0)
3464 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3466 * Same logic as the 'limit' filter; the minimum cannot be
3467 * determined here because we do not have the global information
3468 * about the count of all chunks that satisfy the filters.
3470 if (bargs->limit_max == 0)
3479 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3481 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3482 struct btrfs_root *chunk_root = fs_info->chunk_root;
3483 struct btrfs_root *dev_root = fs_info->dev_root;
3484 struct list_head *devices;
3485 struct btrfs_device *device;
3489 struct btrfs_chunk *chunk;
3490 struct btrfs_path *path = NULL;
3491 struct btrfs_key key;
3492 struct btrfs_key found_key;
3493 struct btrfs_trans_handle *trans;
3494 struct extent_buffer *leaf;
3497 int enospc_errors = 0;
3498 bool counting = true;
3499 /* The single value limit and min/max limits use the same bytes in the */
3500 u64 limit_data = bctl->data.limit;
3501 u64 limit_meta = bctl->meta.limit;
3502 u64 limit_sys = bctl->sys.limit;
3506 int chunk_reserved = 0;
3509 /* step one make some room on all the devices */
3510 devices = &fs_info->fs_devices->devices;
3511 list_for_each_entry(device, devices, dev_list) {
3512 old_size = btrfs_device_get_total_bytes(device);
3513 size_to_free = div_factor(old_size, 1);
3514 size_to_free = min_t(u64, size_to_free, SZ_1M);
3515 if (!device->writeable ||
3516 btrfs_device_get_total_bytes(device) -
3517 btrfs_device_get_bytes_used(device) > size_to_free ||
3518 device->is_tgtdev_for_dev_replace)
3521 ret = btrfs_shrink_device(device, old_size - size_to_free);
3525 /* btrfs_shrink_device never returns ret > 0 */
3530 trans = btrfs_start_transaction(dev_root, 0);
3531 if (IS_ERR(trans)) {
3532 ret = PTR_ERR(trans);
3533 btrfs_info_in_rcu(fs_info,
3534 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3535 rcu_str_deref(device->name), ret,
3536 old_size, old_size - size_to_free);
3540 ret = btrfs_grow_device(trans, device, old_size);
3542 btrfs_end_transaction(trans);
3543 /* btrfs_grow_device never returns ret > 0 */
3545 btrfs_info_in_rcu(fs_info,
3546 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3547 rcu_str_deref(device->name), ret,
3548 old_size, old_size - size_to_free);
3552 btrfs_end_transaction(trans);
3555 /* step two, relocate all the chunks */
3556 path = btrfs_alloc_path();
3562 /* zero out stat counters */
3563 spin_lock(&fs_info->balance_lock);
3564 memset(&bctl->stat, 0, sizeof(bctl->stat));
3565 spin_unlock(&fs_info->balance_lock);
3569 * The single value limit and min/max limits use the same bytes
3572 bctl->data.limit = limit_data;
3573 bctl->meta.limit = limit_meta;
3574 bctl->sys.limit = limit_sys;
3576 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3577 key.offset = (u64)-1;
3578 key.type = BTRFS_CHUNK_ITEM_KEY;
3581 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3582 atomic_read(&fs_info->balance_cancel_req)) {
3587 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3588 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3590 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3595 * this shouldn't happen, it means the last relocate
3599 BUG(); /* FIXME break ? */
3601 ret = btrfs_previous_item(chunk_root, path, 0,
3602 BTRFS_CHUNK_ITEM_KEY);
3604 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3609 leaf = path->nodes[0];
3610 slot = path->slots[0];
3611 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3613 if (found_key.objectid != key.objectid) {
3614 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3618 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3619 chunk_type = btrfs_chunk_type(leaf, chunk);
3622 spin_lock(&fs_info->balance_lock);
3623 bctl->stat.considered++;
3624 spin_unlock(&fs_info->balance_lock);
3627 ret = should_balance_chunk(fs_info, leaf, chunk,
3630 btrfs_release_path(path);
3632 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3637 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3638 spin_lock(&fs_info->balance_lock);
3639 bctl->stat.expected++;
3640 spin_unlock(&fs_info->balance_lock);
3642 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3644 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3646 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3653 * Apply limit_min filter, no need to check if the LIMITS
3654 * filter is used, limit_min is 0 by default
3656 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3657 count_data < bctl->data.limit_min)
3658 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3659 count_meta < bctl->meta.limit_min)
3660 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3661 count_sys < bctl->sys.limit_min)) {
3662 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3666 ASSERT(fs_info->data_sinfo);
3667 spin_lock(&fs_info->data_sinfo->lock);
3668 bytes_used = fs_info->data_sinfo->bytes_used;
3669 spin_unlock(&fs_info->data_sinfo->lock);
3671 if ((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3672 !chunk_reserved && !bytes_used) {
3673 trans = btrfs_start_transaction(chunk_root, 0);
3674 if (IS_ERR(trans)) {
3675 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3676 ret = PTR_ERR(trans);
3680 ret = btrfs_force_chunk_alloc(trans, fs_info,
3681 BTRFS_BLOCK_GROUP_DATA);
3682 btrfs_end_transaction(trans);
3684 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3690 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3691 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3692 if (ret && ret != -ENOSPC)
3694 if (ret == -ENOSPC) {
3697 spin_lock(&fs_info->balance_lock);
3698 bctl->stat.completed++;
3699 spin_unlock(&fs_info->balance_lock);
3702 if (found_key.offset == 0)
3704 key.offset = found_key.offset - 1;
3708 btrfs_release_path(path);
3713 btrfs_free_path(path);
3714 if (enospc_errors) {
3715 btrfs_info(fs_info, "%d enospc errors during balance",
3725 * alloc_profile_is_valid - see if a given profile is valid and reduced
3726 * @flags: profile to validate
3727 * @extended: if true @flags is treated as an extended profile
3729 static int alloc_profile_is_valid(u64 flags, int extended)
3731 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3732 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3734 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3736 /* 1) check that all other bits are zeroed */
3740 /* 2) see if profile is reduced */
3742 return !extended; /* "0" is valid for usual profiles */
3744 /* true if exactly one bit set */
3745 return (flags & (flags - 1)) == 0;
3748 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3750 /* cancel requested || normal exit path */
3751 return atomic_read(&fs_info->balance_cancel_req) ||
3752 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3753 atomic_read(&fs_info->balance_cancel_req) == 0);
3756 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3760 unset_balance_control(fs_info);
3761 ret = del_balance_item(fs_info);
3763 btrfs_handle_fs_error(fs_info, ret, NULL);
3765 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3768 /* Non-zero return value signifies invalidity */
3769 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3772 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3773 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3774 (bctl_arg->target & ~allowed)));
3778 * Should be called with both balance and volume mutexes held
3780 int btrfs_balance(struct btrfs_balance_control *bctl,
3781 struct btrfs_ioctl_balance_args *bargs)
3783 struct btrfs_fs_info *fs_info = bctl->fs_info;
3784 u64 meta_target, data_target;
3791 if (btrfs_fs_closing(fs_info) ||
3792 atomic_read(&fs_info->balance_pause_req) ||
3793 atomic_read(&fs_info->balance_cancel_req)) {
3798 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3799 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3803 * In case of mixed groups both data and meta should be picked,
3804 * and identical options should be given for both of them.
3806 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3807 if (mixed && (bctl->flags & allowed)) {
3808 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3809 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3810 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3812 "with mixed groups data and metadata balance options must be the same");
3818 num_devices = fs_info->fs_devices->num_devices;
3819 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
3820 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3821 BUG_ON(num_devices < 1);
3824 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
3825 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3826 if (num_devices > 1)
3827 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3828 if (num_devices > 2)
3829 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3830 if (num_devices > 3)
3831 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3832 BTRFS_BLOCK_GROUP_RAID6);
3833 if (validate_convert_profile(&bctl->data, allowed)) {
3835 "unable to start balance with target data profile %llu",
3840 if (validate_convert_profile(&bctl->meta, allowed)) {
3842 "unable to start balance with target metadata profile %llu",
3847 if (validate_convert_profile(&bctl->sys, allowed)) {
3849 "unable to start balance with target system profile %llu",
3855 /* allow to reduce meta or sys integrity only if force set */
3856 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3857 BTRFS_BLOCK_GROUP_RAID10 |
3858 BTRFS_BLOCK_GROUP_RAID5 |
3859 BTRFS_BLOCK_GROUP_RAID6;
3861 seq = read_seqbegin(&fs_info->profiles_lock);
3863 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3864 (fs_info->avail_system_alloc_bits & allowed) &&
3865 !(bctl->sys.target & allowed)) ||
3866 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3867 (fs_info->avail_metadata_alloc_bits & allowed) &&
3868 !(bctl->meta.target & allowed))) {
3869 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3871 "force reducing metadata integrity");
3874 "balance will reduce metadata integrity, use force if you want this");
3879 } while (read_seqretry(&fs_info->profiles_lock, seq));
3881 /* if we're not converting, the target field is uninitialized */
3882 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3883 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3884 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3885 bctl->data.target : fs_info->avail_data_alloc_bits;
3886 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3887 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3889 "metadata profile 0x%llx has lower redundancy than data profile 0x%llx",
3890 meta_target, data_target);
3893 ret = insert_balance_item(fs_info, bctl);
3894 if (ret && ret != -EEXIST)
3897 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3898 BUG_ON(ret == -EEXIST);
3899 set_balance_control(bctl);
3901 BUG_ON(ret != -EEXIST);
3902 spin_lock(&fs_info->balance_lock);
3903 update_balance_args(bctl);
3904 spin_unlock(&fs_info->balance_lock);
3907 atomic_inc(&fs_info->balance_running);
3908 mutex_unlock(&fs_info->balance_mutex);
3910 ret = __btrfs_balance(fs_info);
3912 mutex_lock(&fs_info->balance_mutex);
3913 atomic_dec(&fs_info->balance_running);
3916 memset(bargs, 0, sizeof(*bargs));
3917 update_ioctl_balance_args(fs_info, 0, bargs);
3920 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3921 balance_need_close(fs_info)) {
3922 __cancel_balance(fs_info);
3925 wake_up(&fs_info->balance_wait_q);
3929 if (bctl->flags & BTRFS_BALANCE_RESUME)
3930 __cancel_balance(fs_info);
3933 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3938 static int balance_kthread(void *data)
3940 struct btrfs_fs_info *fs_info = data;
3943 mutex_lock(&fs_info->volume_mutex);
3944 mutex_lock(&fs_info->balance_mutex);
3946 if (fs_info->balance_ctl) {
3947 btrfs_info(fs_info, "continuing balance");
3948 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3951 mutex_unlock(&fs_info->balance_mutex);
3952 mutex_unlock(&fs_info->volume_mutex);
3957 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3959 struct task_struct *tsk;
3961 spin_lock(&fs_info->balance_lock);
3962 if (!fs_info->balance_ctl) {
3963 spin_unlock(&fs_info->balance_lock);
3966 spin_unlock(&fs_info->balance_lock);
3968 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
3969 btrfs_info(fs_info, "force skipping balance");
3974 * A ro->rw remount sequence should continue with the paused balance
3975 * regardless of who pauses it, system or the user as of now, so set
3978 spin_lock(&fs_info->balance_lock);
3979 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
3980 spin_unlock(&fs_info->balance_lock);
3982 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3983 return PTR_ERR_OR_ZERO(tsk);
3986 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3988 struct btrfs_balance_control *bctl;
3989 struct btrfs_balance_item *item;
3990 struct btrfs_disk_balance_args disk_bargs;
3991 struct btrfs_path *path;
3992 struct extent_buffer *leaf;
3993 struct btrfs_key key;
3996 path = btrfs_alloc_path();
4000 key.objectid = BTRFS_BALANCE_OBJECTID;
4001 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4004 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4007 if (ret > 0) { /* ret = -ENOENT; */
4012 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4018 leaf = path->nodes[0];
4019 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4021 bctl->fs_info = fs_info;
4022 bctl->flags = btrfs_balance_flags(leaf, item);
4023 bctl->flags |= BTRFS_BALANCE_RESUME;
4025 btrfs_balance_data(leaf, item, &disk_bargs);
4026 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4027 btrfs_balance_meta(leaf, item, &disk_bargs);
4028 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4029 btrfs_balance_sys(leaf, item, &disk_bargs);
4030 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4032 WARN_ON(test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4034 mutex_lock(&fs_info->volume_mutex);
4035 mutex_lock(&fs_info->balance_mutex);
4037 set_balance_control(bctl);
4039 mutex_unlock(&fs_info->balance_mutex);
4040 mutex_unlock(&fs_info->volume_mutex);
4042 btrfs_free_path(path);
4046 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4050 mutex_lock(&fs_info->balance_mutex);
4051 if (!fs_info->balance_ctl) {
4052 mutex_unlock(&fs_info->balance_mutex);
4056 if (atomic_read(&fs_info->balance_running)) {
4057 atomic_inc(&fs_info->balance_pause_req);
4058 mutex_unlock(&fs_info->balance_mutex);
4060 wait_event(fs_info->balance_wait_q,
4061 atomic_read(&fs_info->balance_running) == 0);
4063 mutex_lock(&fs_info->balance_mutex);
4064 /* we are good with balance_ctl ripped off from under us */
4065 BUG_ON(atomic_read(&fs_info->balance_running));
4066 atomic_dec(&fs_info->balance_pause_req);
4071 mutex_unlock(&fs_info->balance_mutex);
4075 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4077 if (sb_rdonly(fs_info->sb))
4080 mutex_lock(&fs_info->balance_mutex);
4081 if (!fs_info->balance_ctl) {
4082 mutex_unlock(&fs_info->balance_mutex);
4086 atomic_inc(&fs_info->balance_cancel_req);
4088 * if we are running just wait and return, balance item is
4089 * deleted in btrfs_balance in this case
4091 if (atomic_read(&fs_info->balance_running)) {
4092 mutex_unlock(&fs_info->balance_mutex);
4093 wait_event(fs_info->balance_wait_q,
4094 atomic_read(&fs_info->balance_running) == 0);
4095 mutex_lock(&fs_info->balance_mutex);
4097 /* __cancel_balance needs volume_mutex */
4098 mutex_unlock(&fs_info->balance_mutex);
4099 mutex_lock(&fs_info->volume_mutex);
4100 mutex_lock(&fs_info->balance_mutex);
4102 if (fs_info->balance_ctl)
4103 __cancel_balance(fs_info);
4105 mutex_unlock(&fs_info->volume_mutex);
4108 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
4109 atomic_dec(&fs_info->balance_cancel_req);
4110 mutex_unlock(&fs_info->balance_mutex);
4114 static int btrfs_uuid_scan_kthread(void *data)
4116 struct btrfs_fs_info *fs_info = data;
4117 struct btrfs_root *root = fs_info->tree_root;
4118 struct btrfs_key key;
4119 struct btrfs_path *path = NULL;
4121 struct extent_buffer *eb;
4123 struct btrfs_root_item root_item;
4125 struct btrfs_trans_handle *trans = NULL;
4127 path = btrfs_alloc_path();
4134 key.type = BTRFS_ROOT_ITEM_KEY;
4138 ret = btrfs_search_forward(root, &key, path, 0);
4145 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4146 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4147 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4148 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4151 eb = path->nodes[0];
4152 slot = path->slots[0];
4153 item_size = btrfs_item_size_nr(eb, slot);
4154 if (item_size < sizeof(root_item))
4157 read_extent_buffer(eb, &root_item,
4158 btrfs_item_ptr_offset(eb, slot),
4159 (int)sizeof(root_item));
4160 if (btrfs_root_refs(&root_item) == 0)
4163 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4164 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4168 btrfs_release_path(path);
4170 * 1 - subvol uuid item
4171 * 1 - received_subvol uuid item
4173 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4174 if (IS_ERR(trans)) {
4175 ret = PTR_ERR(trans);
4183 btrfs_release_path(path);
4184 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4185 ret = btrfs_uuid_tree_add(trans, fs_info,
4187 BTRFS_UUID_KEY_SUBVOL,
4190 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4196 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4197 ret = btrfs_uuid_tree_add(trans, fs_info,
4198 root_item.received_uuid,
4199 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4202 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4209 btrfs_release_path(path);
4211 ret = btrfs_end_transaction(trans);
4217 if (key.offset < (u64)-1) {
4219 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4221 key.type = BTRFS_ROOT_ITEM_KEY;
4222 } else if (key.objectid < (u64)-1) {
4224 key.type = BTRFS_ROOT_ITEM_KEY;
4233 btrfs_free_path(path);
4234 if (trans && !IS_ERR(trans))
4235 btrfs_end_transaction(trans);
4237 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4239 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4240 up(&fs_info->uuid_tree_rescan_sem);
4245 * Callback for btrfs_uuid_tree_iterate().
4247 * 0 check succeeded, the entry is not outdated.
4248 * < 0 if an error occurred.
4249 * > 0 if the check failed, which means the caller shall remove the entry.
4251 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4252 u8 *uuid, u8 type, u64 subid)
4254 struct btrfs_key key;
4256 struct btrfs_root *subvol_root;
4258 if (type != BTRFS_UUID_KEY_SUBVOL &&
4259 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4262 key.objectid = subid;
4263 key.type = BTRFS_ROOT_ITEM_KEY;
4264 key.offset = (u64)-1;
4265 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4266 if (IS_ERR(subvol_root)) {
4267 ret = PTR_ERR(subvol_root);
4274 case BTRFS_UUID_KEY_SUBVOL:
4275 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4278 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4279 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4289 static int btrfs_uuid_rescan_kthread(void *data)
4291 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4295 * 1st step is to iterate through the existing UUID tree and
4296 * to delete all entries that contain outdated data.
4297 * 2nd step is to add all missing entries to the UUID tree.
4299 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4301 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4302 up(&fs_info->uuid_tree_rescan_sem);
4305 return btrfs_uuid_scan_kthread(data);
4308 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4310 struct btrfs_trans_handle *trans;
4311 struct btrfs_root *tree_root = fs_info->tree_root;
4312 struct btrfs_root *uuid_root;
4313 struct task_struct *task;
4320 trans = btrfs_start_transaction(tree_root, 2);
4322 return PTR_ERR(trans);
4324 uuid_root = btrfs_create_tree(trans, fs_info,
4325 BTRFS_UUID_TREE_OBJECTID);
4326 if (IS_ERR(uuid_root)) {
4327 ret = PTR_ERR(uuid_root);
4328 btrfs_abort_transaction(trans, ret);
4329 btrfs_end_transaction(trans);
4333 fs_info->uuid_root = uuid_root;
4335 ret = btrfs_commit_transaction(trans);
4339 down(&fs_info->uuid_tree_rescan_sem);
4340 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4342 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4343 btrfs_warn(fs_info, "failed to start uuid_scan task");
4344 up(&fs_info->uuid_tree_rescan_sem);
4345 return PTR_ERR(task);
4351 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4353 struct task_struct *task;
4355 down(&fs_info->uuid_tree_rescan_sem);
4356 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4358 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4359 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4360 up(&fs_info->uuid_tree_rescan_sem);
4361 return PTR_ERR(task);
4368 * shrinking a device means finding all of the device extents past
4369 * the new size, and then following the back refs to the chunks.
4370 * The chunk relocation code actually frees the device extent
4372 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4374 struct btrfs_fs_info *fs_info = device->fs_info;
4375 struct btrfs_root *root = fs_info->dev_root;
4376 struct btrfs_trans_handle *trans;
4377 struct btrfs_dev_extent *dev_extent = NULL;
4378 struct btrfs_path *path;
4384 bool retried = false;
4385 bool checked_pending_chunks = false;
4386 struct extent_buffer *l;
4387 struct btrfs_key key;
4388 struct btrfs_super_block *super_copy = fs_info->super_copy;
4389 u64 old_total = btrfs_super_total_bytes(super_copy);
4390 u64 old_size = btrfs_device_get_total_bytes(device);
4393 new_size = round_down(new_size, fs_info->sectorsize);
4394 diff = round_down(old_size - new_size, fs_info->sectorsize);
4396 if (device->is_tgtdev_for_dev_replace)
4399 path = btrfs_alloc_path();
4403 path->reada = READA_FORWARD;
4405 mutex_lock(&fs_info->chunk_mutex);
4407 btrfs_device_set_total_bytes(device, new_size);
4408 if (device->writeable) {
4409 device->fs_devices->total_rw_bytes -= diff;
4410 atomic64_sub(diff, &fs_info->free_chunk_space);
4412 mutex_unlock(&fs_info->chunk_mutex);
4415 key.objectid = device->devid;
4416 key.offset = (u64)-1;
4417 key.type = BTRFS_DEV_EXTENT_KEY;
4420 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4421 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4423 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4427 ret = btrfs_previous_item(root, path, 0, key.type);
4429 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4434 btrfs_release_path(path);
4439 slot = path->slots[0];
4440 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4442 if (key.objectid != device->devid) {
4443 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4444 btrfs_release_path(path);
4448 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4449 length = btrfs_dev_extent_length(l, dev_extent);
4451 if (key.offset + length <= new_size) {
4452 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4453 btrfs_release_path(path);
4457 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4458 btrfs_release_path(path);
4460 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4461 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4462 if (ret && ret != -ENOSPC)
4466 } while (key.offset-- > 0);
4468 if (failed && !retried) {
4472 } else if (failed && retried) {
4477 /* Shrinking succeeded, else we would be at "done". */
4478 trans = btrfs_start_transaction(root, 0);
4479 if (IS_ERR(trans)) {
4480 ret = PTR_ERR(trans);
4484 mutex_lock(&fs_info->chunk_mutex);
4487 * We checked in the above loop all device extents that were already in
4488 * the device tree. However before we have updated the device's
4489 * total_bytes to the new size, we might have had chunk allocations that
4490 * have not complete yet (new block groups attached to transaction
4491 * handles), and therefore their device extents were not yet in the
4492 * device tree and we missed them in the loop above. So if we have any
4493 * pending chunk using a device extent that overlaps the device range
4494 * that we can not use anymore, commit the current transaction and
4495 * repeat the search on the device tree - this way we guarantee we will
4496 * not have chunks using device extents that end beyond 'new_size'.
4498 if (!checked_pending_chunks) {
4499 u64 start = new_size;
4500 u64 len = old_size - new_size;
4502 if (contains_pending_extent(trans->transaction, device,
4504 mutex_unlock(&fs_info->chunk_mutex);
4505 checked_pending_chunks = true;
4508 ret = btrfs_commit_transaction(trans);
4515 btrfs_device_set_disk_total_bytes(device, new_size);
4516 if (list_empty(&device->resized_list))
4517 list_add_tail(&device->resized_list,
4518 &fs_info->fs_devices->resized_devices);
4520 WARN_ON(diff > old_total);
4521 btrfs_set_super_total_bytes(super_copy,
4522 round_down(old_total - diff, fs_info->sectorsize));
4523 mutex_unlock(&fs_info->chunk_mutex);
4525 /* Now btrfs_update_device() will change the on-disk size. */
4526 ret = btrfs_update_device(trans, device);
4528 btrfs_abort_transaction(trans, ret);
4529 btrfs_end_transaction(trans);
4531 ret = btrfs_commit_transaction(trans);
4534 btrfs_free_path(path);
4536 mutex_lock(&fs_info->chunk_mutex);
4537 btrfs_device_set_total_bytes(device, old_size);
4538 if (device->writeable)
4539 device->fs_devices->total_rw_bytes += diff;
4540 atomic64_add(diff, &fs_info->free_chunk_space);
4541 mutex_unlock(&fs_info->chunk_mutex);
4546 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4547 struct btrfs_key *key,
4548 struct btrfs_chunk *chunk, int item_size)
4550 struct btrfs_super_block *super_copy = fs_info->super_copy;
4551 struct btrfs_disk_key disk_key;
4555 mutex_lock(&fs_info->chunk_mutex);
4556 array_size = btrfs_super_sys_array_size(super_copy);
4557 if (array_size + item_size + sizeof(disk_key)
4558 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4559 mutex_unlock(&fs_info->chunk_mutex);
4563 ptr = super_copy->sys_chunk_array + array_size;
4564 btrfs_cpu_key_to_disk(&disk_key, key);
4565 memcpy(ptr, &disk_key, sizeof(disk_key));
4566 ptr += sizeof(disk_key);
4567 memcpy(ptr, chunk, item_size);
4568 item_size += sizeof(disk_key);
4569 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4570 mutex_unlock(&fs_info->chunk_mutex);
4576 * sort the devices in descending order by max_avail, total_avail
4578 static int btrfs_cmp_device_info(const void *a, const void *b)
4580 const struct btrfs_device_info *di_a = a;
4581 const struct btrfs_device_info *di_b = b;
4583 if (di_a->max_avail > di_b->max_avail)
4585 if (di_a->max_avail < di_b->max_avail)
4587 if (di_a->total_avail > di_b->total_avail)
4589 if (di_a->total_avail < di_b->total_avail)
4594 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4596 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4599 btrfs_set_fs_incompat(info, RAID56);
4602 #define BTRFS_MAX_DEVS(r) ((BTRFS_MAX_ITEM_SIZE(r->fs_info) \
4603 - sizeof(struct btrfs_chunk)) \
4604 / sizeof(struct btrfs_stripe) + 1)
4606 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4607 - 2 * sizeof(struct btrfs_disk_key) \
4608 - 2 * sizeof(struct btrfs_chunk)) \
4609 / sizeof(struct btrfs_stripe) + 1)
4611 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4612 u64 start, u64 type)
4614 struct btrfs_fs_info *info = trans->fs_info;
4615 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4616 struct btrfs_device *device;
4617 struct map_lookup *map = NULL;
4618 struct extent_map_tree *em_tree;
4619 struct extent_map *em;
4620 struct btrfs_device_info *devices_info = NULL;
4622 int num_stripes; /* total number of stripes to allocate */
4623 int data_stripes; /* number of stripes that count for
4625 int sub_stripes; /* sub_stripes info for map */
4626 int dev_stripes; /* stripes per dev */
4627 int devs_max; /* max devs to use */
4628 int devs_min; /* min devs needed */
4629 int devs_increment; /* ndevs has to be a multiple of this */
4630 int ncopies; /* how many copies to data has */
4632 u64 max_stripe_size;
4641 BUG_ON(!alloc_profile_is_valid(type, 0));
4643 if (list_empty(&fs_devices->alloc_list))
4646 index = __get_raid_index(type);
4648 sub_stripes = btrfs_raid_array[index].sub_stripes;
4649 dev_stripes = btrfs_raid_array[index].dev_stripes;
4650 devs_max = btrfs_raid_array[index].devs_max;
4651 devs_min = btrfs_raid_array[index].devs_min;
4652 devs_increment = btrfs_raid_array[index].devs_increment;
4653 ncopies = btrfs_raid_array[index].ncopies;
4655 if (type & BTRFS_BLOCK_GROUP_DATA) {
4656 max_stripe_size = SZ_1G;
4657 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4659 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4660 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4661 /* for larger filesystems, use larger metadata chunks */
4662 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4663 max_stripe_size = SZ_1G;
4665 max_stripe_size = SZ_256M;
4666 max_chunk_size = max_stripe_size;
4668 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4669 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4670 max_stripe_size = SZ_32M;
4671 max_chunk_size = 2 * max_stripe_size;
4673 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4675 btrfs_err(info, "invalid chunk type 0x%llx requested",
4680 /* we don't want a chunk larger than 10% of writeable space */
4681 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4684 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4690 * in the first pass through the devices list, we gather information
4691 * about the available holes on each device.
4694 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4698 if (!device->writeable) {
4700 "BTRFS: read-only device in alloc_list\n");
4704 if (!device->in_fs_metadata ||
4705 device->is_tgtdev_for_dev_replace)
4708 if (device->total_bytes > device->bytes_used)
4709 total_avail = device->total_bytes - device->bytes_used;
4713 /* If there is no space on this device, skip it. */
4714 if (total_avail == 0)
4717 ret = find_free_dev_extent(trans, device,
4718 max_stripe_size * dev_stripes,
4719 &dev_offset, &max_avail);
4720 if (ret && ret != -ENOSPC)
4724 max_avail = max_stripe_size * dev_stripes;
4726 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4729 if (ndevs == fs_devices->rw_devices) {
4730 WARN(1, "%s: found more than %llu devices\n",
4731 __func__, fs_devices->rw_devices);
4734 devices_info[ndevs].dev_offset = dev_offset;
4735 devices_info[ndevs].max_avail = max_avail;
4736 devices_info[ndevs].total_avail = total_avail;
4737 devices_info[ndevs].dev = device;
4742 * now sort the devices by hole size / available space
4744 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4745 btrfs_cmp_device_info, NULL);
4747 /* round down to number of usable stripes */
4748 ndevs = round_down(ndevs, devs_increment);
4750 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4755 ndevs = min(ndevs, devs_max);
4758 * The primary goal is to maximize the number of stripes, so use as
4759 * many devices as possible, even if the stripes are not maximum sized.
4761 * The DUP profile stores more than one stripe per device, the
4762 * max_avail is the total size so we have to adjust.
4764 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4765 num_stripes = ndevs * dev_stripes;
4768 * this will have to be fixed for RAID1 and RAID10 over
4771 data_stripes = num_stripes / ncopies;
4773 if (type & BTRFS_BLOCK_GROUP_RAID5)
4774 data_stripes = num_stripes - 1;
4776 if (type & BTRFS_BLOCK_GROUP_RAID6)
4777 data_stripes = num_stripes - 2;
4780 * Use the number of data stripes to figure out how big this chunk
4781 * is really going to be in terms of logical address space,
4782 * and compare that answer with the max chunk size
4784 if (stripe_size * data_stripes > max_chunk_size) {
4785 u64 mask = (1ULL << 24) - 1;
4787 stripe_size = div_u64(max_chunk_size, data_stripes);
4789 /* bump the answer up to a 16MB boundary */
4790 stripe_size = (stripe_size + mask) & ~mask;
4792 /* but don't go higher than the limits we found
4793 * while searching for free extents
4795 if (stripe_size > devices_info[ndevs-1].max_avail)
4796 stripe_size = devices_info[ndevs-1].max_avail;
4799 /* align to BTRFS_STRIPE_LEN */
4800 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4802 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4807 map->num_stripes = num_stripes;
4809 for (i = 0; i < ndevs; ++i) {
4810 for (j = 0; j < dev_stripes; ++j) {
4811 int s = i * dev_stripes + j;
4812 map->stripes[s].dev = devices_info[i].dev;
4813 map->stripes[s].physical = devices_info[i].dev_offset +
4817 map->stripe_len = BTRFS_STRIPE_LEN;
4818 map->io_align = BTRFS_STRIPE_LEN;
4819 map->io_width = BTRFS_STRIPE_LEN;
4821 map->sub_stripes = sub_stripes;
4823 num_bytes = stripe_size * data_stripes;
4825 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4827 em = alloc_extent_map();
4833 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4834 em->map_lookup = map;
4836 em->len = num_bytes;
4837 em->block_start = 0;
4838 em->block_len = em->len;
4839 em->orig_block_len = stripe_size;
4841 em_tree = &info->mapping_tree.map_tree;
4842 write_lock(&em_tree->lock);
4843 ret = add_extent_mapping(em_tree, em, 0);
4845 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4846 refcount_inc(&em->refs);
4848 write_unlock(&em_tree->lock);
4850 free_extent_map(em);
4854 ret = btrfs_make_block_group(trans, info, 0, type, start, num_bytes);
4856 goto error_del_extent;
4858 for (i = 0; i < map->num_stripes; i++) {
4859 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4860 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4861 map->stripes[i].dev->has_pending_chunks = true;
4864 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4866 free_extent_map(em);
4867 check_raid56_incompat_flag(info, type);
4869 kfree(devices_info);
4873 write_lock(&em_tree->lock);
4874 remove_extent_mapping(em_tree, em);
4875 write_unlock(&em_tree->lock);
4877 /* One for our allocation */
4878 free_extent_map(em);
4879 /* One for the tree reference */
4880 free_extent_map(em);
4881 /* One for the pending_chunks list reference */
4882 free_extent_map(em);
4884 kfree(devices_info);
4888 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4889 struct btrfs_fs_info *fs_info,
4890 u64 chunk_offset, u64 chunk_size)
4892 struct btrfs_root *extent_root = fs_info->extent_root;
4893 struct btrfs_root *chunk_root = fs_info->chunk_root;
4894 struct btrfs_key key;
4895 struct btrfs_device *device;
4896 struct btrfs_chunk *chunk;
4897 struct btrfs_stripe *stripe;
4898 struct extent_map *em;
4899 struct map_lookup *map;
4906 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4910 map = em->map_lookup;
4911 item_size = btrfs_chunk_item_size(map->num_stripes);
4912 stripe_size = em->orig_block_len;
4914 chunk = kzalloc(item_size, GFP_NOFS);
4921 * Take the device list mutex to prevent races with the final phase of
4922 * a device replace operation that replaces the device object associated
4923 * with the map's stripes, because the device object's id can change
4924 * at any time during that final phase of the device replace operation
4925 * (dev-replace.c:btrfs_dev_replace_finishing()).
4927 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4928 for (i = 0; i < map->num_stripes; i++) {
4929 device = map->stripes[i].dev;
4930 dev_offset = map->stripes[i].physical;
4932 ret = btrfs_update_device(trans, device);
4935 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
4936 dev_offset, stripe_size);
4941 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4945 stripe = &chunk->stripe;
4946 for (i = 0; i < map->num_stripes; i++) {
4947 device = map->stripes[i].dev;
4948 dev_offset = map->stripes[i].physical;
4950 btrfs_set_stack_stripe_devid(stripe, device->devid);
4951 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4952 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4955 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4957 btrfs_set_stack_chunk_length(chunk, chunk_size);
4958 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4959 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4960 btrfs_set_stack_chunk_type(chunk, map->type);
4961 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4962 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4963 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4964 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
4965 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4967 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4968 key.type = BTRFS_CHUNK_ITEM_KEY;
4969 key.offset = chunk_offset;
4971 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4972 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4974 * TODO: Cleanup of inserted chunk root in case of
4977 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
4982 free_extent_map(em);
4987 * Chunk allocation falls into two parts. The first part does works
4988 * that make the new allocated chunk useable, but not do any operation
4989 * that modifies the chunk tree. The second part does the works that
4990 * require modifying the chunk tree. This division is important for the
4991 * bootstrap process of adding storage to a seed btrfs.
4993 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4994 struct btrfs_fs_info *fs_info, u64 type)
4998 ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
4999 chunk_offset = find_next_chunk(fs_info);
5000 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5003 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5004 struct btrfs_fs_info *fs_info)
5007 u64 sys_chunk_offset;
5011 chunk_offset = find_next_chunk(fs_info);
5012 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5013 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5017 sys_chunk_offset = find_next_chunk(fs_info);
5018 alloc_profile = btrfs_system_alloc_profile(fs_info);
5019 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5023 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5027 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5028 BTRFS_BLOCK_GROUP_RAID10 |
5029 BTRFS_BLOCK_GROUP_RAID5)) {
5031 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5040 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5042 struct extent_map *em;
5043 struct map_lookup *map;
5048 em = get_chunk_map(fs_info, chunk_offset, 1);
5052 map = em->map_lookup;
5053 for (i = 0; i < map->num_stripes; i++) {
5054 if (map->stripes[i].dev->missing) {
5059 if (!map->stripes[i].dev->writeable) {
5066 * If the number of missing devices is larger than max errors,
5067 * we can not write the data into that chunk successfully, so
5070 if (miss_ndevs > btrfs_chunk_max_errors(map))
5073 free_extent_map(em);
5077 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5079 extent_map_tree_init(&tree->map_tree);
5082 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5084 struct extent_map *em;
5087 write_lock(&tree->map_tree.lock);
5088 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5090 remove_extent_mapping(&tree->map_tree, em);
5091 write_unlock(&tree->map_tree.lock);
5095 free_extent_map(em);
5096 /* once for the tree */
5097 free_extent_map(em);
5101 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5103 struct extent_map *em;
5104 struct map_lookup *map;
5107 em = get_chunk_map(fs_info, logical, len);
5110 * We could return errors for these cases, but that could get
5111 * ugly and we'd probably do the same thing which is just not do
5112 * anything else and exit, so return 1 so the callers don't try
5113 * to use other copies.
5117 map = em->map_lookup;
5118 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5119 ret = map->num_stripes;
5120 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5121 ret = map->sub_stripes;
5122 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5124 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5126 * There could be two corrupted data stripes, we need
5127 * to loop retry in order to rebuild the correct data.
5129 * Fail a stripe at a time on every retry except the
5130 * stripe under reconstruction.
5132 ret = map->num_stripes;
5135 free_extent_map(em);
5137 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
5138 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5139 fs_info->dev_replace.tgtdev)
5141 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
5146 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5149 struct extent_map *em;
5150 struct map_lookup *map;
5151 unsigned long len = fs_info->sectorsize;
5153 em = get_chunk_map(fs_info, logical, len);
5155 if (!WARN_ON(IS_ERR(em))) {
5156 map = em->map_lookup;
5157 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5158 len = map->stripe_len * nr_data_stripes(map);
5159 free_extent_map(em);
5164 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5166 struct extent_map *em;
5167 struct map_lookup *map;
5170 em = get_chunk_map(fs_info, logical, len);
5172 if(!WARN_ON(IS_ERR(em))) {
5173 map = em->map_lookup;
5174 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5176 free_extent_map(em);
5181 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5182 struct map_lookup *map, int first, int num,
5183 int optimal, int dev_replace_is_ongoing)
5187 struct btrfs_device *srcdev;
5189 if (dev_replace_is_ongoing &&
5190 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5191 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5192 srcdev = fs_info->dev_replace.srcdev;
5197 * try to avoid the drive that is the source drive for a
5198 * dev-replace procedure, only choose it if no other non-missing
5199 * mirror is available
5201 for (tolerance = 0; tolerance < 2; tolerance++) {
5202 if (map->stripes[optimal].dev->bdev &&
5203 (tolerance || map->stripes[optimal].dev != srcdev))
5205 for (i = first; i < first + num; i++) {
5206 if (map->stripes[i].dev->bdev &&
5207 (tolerance || map->stripes[i].dev != srcdev))
5212 /* we couldn't find one that doesn't fail. Just return something
5213 * and the io error handling code will clean up eventually
5218 static inline int parity_smaller(u64 a, u64 b)
5223 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5224 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5226 struct btrfs_bio_stripe s;
5233 for (i = 0; i < num_stripes - 1; i++) {
5234 if (parity_smaller(bbio->raid_map[i],
5235 bbio->raid_map[i+1])) {
5236 s = bbio->stripes[i];
5237 l = bbio->raid_map[i];
5238 bbio->stripes[i] = bbio->stripes[i+1];
5239 bbio->raid_map[i] = bbio->raid_map[i+1];
5240 bbio->stripes[i+1] = s;
5241 bbio->raid_map[i+1] = l;
5249 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5251 struct btrfs_bio *bbio = kzalloc(
5252 /* the size of the btrfs_bio */
5253 sizeof(struct btrfs_bio) +
5254 /* plus the variable array for the stripes */
5255 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5256 /* plus the variable array for the tgt dev */
5257 sizeof(int) * (real_stripes) +
5259 * plus the raid_map, which includes both the tgt dev
5262 sizeof(u64) * (total_stripes),
5263 GFP_NOFS|__GFP_NOFAIL);
5265 atomic_set(&bbio->error, 0);
5266 refcount_set(&bbio->refs, 1);
5271 void btrfs_get_bbio(struct btrfs_bio *bbio)
5273 WARN_ON(!refcount_read(&bbio->refs));
5274 refcount_inc(&bbio->refs);
5277 void btrfs_put_bbio(struct btrfs_bio *bbio)
5281 if (refcount_dec_and_test(&bbio->refs))
5285 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5287 * Please note that, discard won't be sent to target device of device
5290 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5291 u64 logical, u64 length,
5292 struct btrfs_bio **bbio_ret)
5294 struct extent_map *em;
5295 struct map_lookup *map;
5296 struct btrfs_bio *bbio;
5300 u64 stripe_end_offset;
5307 u32 sub_stripes = 0;
5308 u64 stripes_per_dev = 0;
5309 u32 remaining_stripes = 0;
5310 u32 last_stripe = 0;
5314 /* discard always return a bbio */
5317 em = get_chunk_map(fs_info, logical, length);
5321 map = em->map_lookup;
5322 /* we don't discard raid56 yet */
5323 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5328 offset = logical - em->start;
5329 length = min_t(u64, em->len - offset, length);
5331 stripe_len = map->stripe_len;
5333 * stripe_nr counts the total number of stripes we have to stride
5334 * to get to this block
5336 stripe_nr = div64_u64(offset, stripe_len);
5338 /* stripe_offset is the offset of this block in its stripe */
5339 stripe_offset = offset - stripe_nr * stripe_len;
5341 stripe_nr_end = round_up(offset + length, map->stripe_len);
5342 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5343 stripe_cnt = stripe_nr_end - stripe_nr;
5344 stripe_end_offset = stripe_nr_end * map->stripe_len -
5347 * after this, stripe_nr is the number of stripes on this
5348 * device we have to walk to find the data, and stripe_index is
5349 * the number of our device in the stripe array
5353 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5354 BTRFS_BLOCK_GROUP_RAID10)) {
5355 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5358 sub_stripes = map->sub_stripes;
5360 factor = map->num_stripes / sub_stripes;
5361 num_stripes = min_t(u64, map->num_stripes,
5362 sub_stripes * stripe_cnt);
5363 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5364 stripe_index *= sub_stripes;
5365 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5366 &remaining_stripes);
5367 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5368 last_stripe *= sub_stripes;
5369 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5370 BTRFS_BLOCK_GROUP_DUP)) {
5371 num_stripes = map->num_stripes;
5373 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5377 bbio = alloc_btrfs_bio(num_stripes, 0);
5383 for (i = 0; i < num_stripes; i++) {
5384 bbio->stripes[i].physical =
5385 map->stripes[stripe_index].physical +
5386 stripe_offset + stripe_nr * map->stripe_len;
5387 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5389 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5390 BTRFS_BLOCK_GROUP_RAID10)) {
5391 bbio->stripes[i].length = stripes_per_dev *
5394 if (i / sub_stripes < remaining_stripes)
5395 bbio->stripes[i].length +=
5399 * Special for the first stripe and
5402 * |-------|...|-------|
5406 if (i < sub_stripes)
5407 bbio->stripes[i].length -=
5410 if (stripe_index >= last_stripe &&
5411 stripe_index <= (last_stripe +
5413 bbio->stripes[i].length -=
5416 if (i == sub_stripes - 1)
5419 bbio->stripes[i].length = length;
5423 if (stripe_index == map->num_stripes) {
5430 bbio->map_type = map->type;
5431 bbio->num_stripes = num_stripes;
5433 free_extent_map(em);
5438 * In dev-replace case, for repair case (that's the only case where the mirror
5439 * is selected explicitly when calling btrfs_map_block), blocks left of the
5440 * left cursor can also be read from the target drive.
5442 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5444 * For READ, it also needs to be supported using the same mirror number.
5446 * If the requested block is not left of the left cursor, EIO is returned. This
5447 * can happen because btrfs_num_copies() returns one more in the dev-replace
5450 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5451 u64 logical, u64 length,
5452 u64 srcdev_devid, int *mirror_num,
5455 struct btrfs_bio *bbio = NULL;
5457 int index_srcdev = 0;
5459 u64 physical_of_found = 0;
5463 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5464 logical, &length, &bbio, 0, 0);
5466 ASSERT(bbio == NULL);
5470 num_stripes = bbio->num_stripes;
5471 if (*mirror_num > num_stripes) {
5473 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5474 * that means that the requested area is not left of the left
5477 btrfs_put_bbio(bbio);
5482 * process the rest of the function using the mirror_num of the source
5483 * drive. Therefore look it up first. At the end, patch the device
5484 * pointer to the one of the target drive.
5486 for (i = 0; i < num_stripes; i++) {
5487 if (bbio->stripes[i].dev->devid != srcdev_devid)
5491 * In case of DUP, in order to keep it simple, only add the
5492 * mirror with the lowest physical address
5495 physical_of_found <= bbio->stripes[i].physical)
5500 physical_of_found = bbio->stripes[i].physical;
5503 btrfs_put_bbio(bbio);
5509 *mirror_num = index_srcdev + 1;
5510 *physical = physical_of_found;
5514 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5515 struct btrfs_bio **bbio_ret,
5516 struct btrfs_dev_replace *dev_replace,
5517 int *num_stripes_ret, int *max_errors_ret)
5519 struct btrfs_bio *bbio = *bbio_ret;
5520 u64 srcdev_devid = dev_replace->srcdev->devid;
5521 int tgtdev_indexes = 0;
5522 int num_stripes = *num_stripes_ret;
5523 int max_errors = *max_errors_ret;
5526 if (op == BTRFS_MAP_WRITE) {
5527 int index_where_to_add;
5530 * duplicate the write operations while the dev replace
5531 * procedure is running. Since the copying of the old disk to
5532 * the new disk takes place at run time while the filesystem is
5533 * mounted writable, the regular write operations to the old
5534 * disk have to be duplicated to go to the new disk as well.
5536 * Note that device->missing is handled by the caller, and that
5537 * the write to the old disk is already set up in the stripes
5540 index_where_to_add = num_stripes;
5541 for (i = 0; i < num_stripes; i++) {
5542 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5543 /* write to new disk, too */
5544 struct btrfs_bio_stripe *new =
5545 bbio->stripes + index_where_to_add;
5546 struct btrfs_bio_stripe *old =
5549 new->physical = old->physical;
5550 new->length = old->length;
5551 new->dev = dev_replace->tgtdev;
5552 bbio->tgtdev_map[i] = index_where_to_add;
5553 index_where_to_add++;
5558 num_stripes = index_where_to_add;
5559 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5560 int index_srcdev = 0;
5562 u64 physical_of_found = 0;
5565 * During the dev-replace procedure, the target drive can also
5566 * be used to read data in case it is needed to repair a corrupt
5567 * block elsewhere. This is possible if the requested area is
5568 * left of the left cursor. In this area, the target drive is a
5569 * full copy of the source drive.
5571 for (i = 0; i < num_stripes; i++) {
5572 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5574 * In case of DUP, in order to keep it simple,
5575 * only add the mirror with the lowest physical
5579 physical_of_found <=
5580 bbio->stripes[i].physical)
5584 physical_of_found = bbio->stripes[i].physical;
5588 struct btrfs_bio_stripe *tgtdev_stripe =
5589 bbio->stripes + num_stripes;
5591 tgtdev_stripe->physical = physical_of_found;
5592 tgtdev_stripe->length =
5593 bbio->stripes[index_srcdev].length;
5594 tgtdev_stripe->dev = dev_replace->tgtdev;
5595 bbio->tgtdev_map[index_srcdev] = num_stripes;
5602 *num_stripes_ret = num_stripes;
5603 *max_errors_ret = max_errors;
5604 bbio->num_tgtdevs = tgtdev_indexes;
5608 static bool need_full_stripe(enum btrfs_map_op op)
5610 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5613 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5614 enum btrfs_map_op op,
5615 u64 logical, u64 *length,
5616 struct btrfs_bio **bbio_ret,
5617 int mirror_num, int need_raid_map)
5619 struct extent_map *em;
5620 struct map_lookup *map;
5630 int tgtdev_indexes = 0;
5631 struct btrfs_bio *bbio = NULL;
5632 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5633 int dev_replace_is_ongoing = 0;
5634 int num_alloc_stripes;
5635 int patch_the_first_stripe_for_dev_replace = 0;
5636 u64 physical_to_patch_in_first_stripe = 0;
5637 u64 raid56_full_stripe_start = (u64)-1;
5639 if (op == BTRFS_MAP_DISCARD)
5640 return __btrfs_map_block_for_discard(fs_info, logical,
5643 em = get_chunk_map(fs_info, logical, *length);
5647 map = em->map_lookup;
5648 offset = logical - em->start;
5650 stripe_len = map->stripe_len;
5653 * stripe_nr counts the total number of stripes we have to stride
5654 * to get to this block
5656 stripe_nr = div64_u64(stripe_nr, stripe_len);
5658 stripe_offset = stripe_nr * stripe_len;
5659 if (offset < stripe_offset) {
5661 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5662 stripe_offset, offset, em->start, logical,
5664 free_extent_map(em);
5668 /* stripe_offset is the offset of this block in its stripe*/
5669 stripe_offset = offset - stripe_offset;
5671 /* if we're here for raid56, we need to know the stripe aligned start */
5672 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5673 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5674 raid56_full_stripe_start = offset;
5676 /* allow a write of a full stripe, but make sure we don't
5677 * allow straddling of stripes
5679 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5681 raid56_full_stripe_start *= full_stripe_len;
5684 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5686 /* For writes to RAID[56], allow a full stripeset across all disks.
5687 For other RAID types and for RAID[56] reads, just allow a single
5688 stripe (on a single disk). */
5689 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5690 (op == BTRFS_MAP_WRITE)) {
5691 max_len = stripe_len * nr_data_stripes(map) -
5692 (offset - raid56_full_stripe_start);
5694 /* we limit the length of each bio to what fits in a stripe */
5695 max_len = stripe_len - stripe_offset;
5697 *length = min_t(u64, em->len - offset, max_len);
5699 *length = em->len - offset;
5702 /* This is for when we're called from btrfs_merge_bio_hook() and all
5703 it cares about is the length */
5707 btrfs_dev_replace_lock(dev_replace, 0);
5708 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5709 if (!dev_replace_is_ongoing)
5710 btrfs_dev_replace_unlock(dev_replace, 0);
5712 btrfs_dev_replace_set_lock_blocking(dev_replace);
5714 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5715 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5716 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5717 dev_replace->srcdev->devid,
5719 &physical_to_patch_in_first_stripe);
5723 patch_the_first_stripe_for_dev_replace = 1;
5724 } else if (mirror_num > map->num_stripes) {
5730 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5731 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5733 if (op != BTRFS_MAP_WRITE && op != BTRFS_MAP_GET_READ_MIRRORS)
5735 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5736 if (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS)
5737 num_stripes = map->num_stripes;
5738 else if (mirror_num)
5739 stripe_index = mirror_num - 1;
5741 stripe_index = find_live_mirror(fs_info, map, 0,
5743 current->pid % map->num_stripes,
5744 dev_replace_is_ongoing);
5745 mirror_num = stripe_index + 1;
5748 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5749 if (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS) {
5750 num_stripes = map->num_stripes;
5751 } else if (mirror_num) {
5752 stripe_index = mirror_num - 1;
5757 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5758 u32 factor = map->num_stripes / map->sub_stripes;
5760 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5761 stripe_index *= map->sub_stripes;
5763 if (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS)
5764 num_stripes = map->sub_stripes;
5765 else if (mirror_num)
5766 stripe_index += mirror_num - 1;
5768 int old_stripe_index = stripe_index;
5769 stripe_index = find_live_mirror(fs_info, map,
5771 map->sub_stripes, stripe_index +
5772 current->pid % map->sub_stripes,
5773 dev_replace_is_ongoing);
5774 mirror_num = stripe_index - old_stripe_index + 1;
5777 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5778 if (need_raid_map &&
5779 (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS ||
5781 /* push stripe_nr back to the start of the full stripe */
5782 stripe_nr = div64_u64(raid56_full_stripe_start,
5783 stripe_len * nr_data_stripes(map));
5785 /* RAID[56] write or recovery. Return all stripes */
5786 num_stripes = map->num_stripes;
5787 max_errors = nr_parity_stripes(map);
5789 *length = map->stripe_len;
5794 * Mirror #0 or #1 means the original data block.
5795 * Mirror #2 is RAID5 parity block.
5796 * Mirror #3 is RAID6 Q block.
5798 stripe_nr = div_u64_rem(stripe_nr,
5799 nr_data_stripes(map), &stripe_index);
5801 stripe_index = nr_data_stripes(map) +
5804 /* We distribute the parity blocks across stripes */
5805 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5807 if ((op != BTRFS_MAP_WRITE &&
5808 op != BTRFS_MAP_GET_READ_MIRRORS) &&
5814 * after this, stripe_nr is the number of stripes on this
5815 * device we have to walk to find the data, and stripe_index is
5816 * the number of our device in the stripe array
5818 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5820 mirror_num = stripe_index + 1;
5822 if (stripe_index >= map->num_stripes) {
5824 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5825 stripe_index, map->num_stripes);
5830 num_alloc_stripes = num_stripes;
5831 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5832 if (op == BTRFS_MAP_WRITE)
5833 num_alloc_stripes <<= 1;
5834 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5835 num_alloc_stripes++;
5836 tgtdev_indexes = num_stripes;
5839 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5844 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5845 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5847 /* build raid_map */
5848 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5849 (need_full_stripe(op) || mirror_num > 1)) {
5853 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5854 sizeof(struct btrfs_bio_stripe) *
5856 sizeof(int) * tgtdev_indexes);
5858 /* Work out the disk rotation on this stripe-set */
5859 div_u64_rem(stripe_nr, num_stripes, &rot);
5861 /* Fill in the logical address of each stripe */
5862 tmp = stripe_nr * nr_data_stripes(map);
5863 for (i = 0; i < nr_data_stripes(map); i++)
5864 bbio->raid_map[(i+rot) % num_stripes] =
5865 em->start + (tmp + i) * map->stripe_len;
5867 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5868 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5869 bbio->raid_map[(i+rot+1) % num_stripes] =
5874 for (i = 0; i < num_stripes; i++) {
5875 bbio->stripes[i].physical =
5876 map->stripes[stripe_index].physical +
5878 stripe_nr * map->stripe_len;
5879 bbio->stripes[i].dev =
5880 map->stripes[stripe_index].dev;
5884 if (need_full_stripe(op))
5885 max_errors = btrfs_chunk_max_errors(map);
5888 sort_parity_stripes(bbio, num_stripes);
5890 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5891 need_full_stripe(op)) {
5892 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5897 bbio->map_type = map->type;
5898 bbio->num_stripes = num_stripes;
5899 bbio->max_errors = max_errors;
5900 bbio->mirror_num = mirror_num;
5903 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5904 * mirror_num == num_stripes + 1 && dev_replace target drive is
5905 * available as a mirror
5907 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5908 WARN_ON(num_stripes > 1);
5909 bbio->stripes[0].dev = dev_replace->tgtdev;
5910 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5911 bbio->mirror_num = map->num_stripes + 1;
5914 if (dev_replace_is_ongoing) {
5915 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5916 btrfs_dev_replace_unlock(dev_replace, 0);
5918 free_extent_map(em);
5922 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5923 u64 logical, u64 *length,
5924 struct btrfs_bio **bbio_ret, int mirror_num)
5926 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
5930 /* For Scrub/replace */
5931 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5932 u64 logical, u64 *length,
5933 struct btrfs_bio **bbio_ret)
5935 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
5938 int btrfs_rmap_block(struct btrfs_fs_info *fs_info,
5939 u64 chunk_start, u64 physical, u64 devid,
5940 u64 **logical, int *naddrs, int *stripe_len)
5942 struct extent_map *em;
5943 struct map_lookup *map;
5951 em = get_chunk_map(fs_info, chunk_start, 1);
5955 map = em->map_lookup;
5957 rmap_len = map->stripe_len;
5959 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5960 length = div_u64(length, map->num_stripes / map->sub_stripes);
5961 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5962 length = div_u64(length, map->num_stripes);
5963 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5964 length = div_u64(length, nr_data_stripes(map));
5965 rmap_len = map->stripe_len * nr_data_stripes(map);
5968 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5969 BUG_ON(!buf); /* -ENOMEM */
5971 for (i = 0; i < map->num_stripes; i++) {
5972 if (devid && map->stripes[i].dev->devid != devid)
5974 if (map->stripes[i].physical > physical ||
5975 map->stripes[i].physical + length <= physical)
5978 stripe_nr = physical - map->stripes[i].physical;
5979 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
5981 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5982 stripe_nr = stripe_nr * map->num_stripes + i;
5983 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
5984 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5985 stripe_nr = stripe_nr * map->num_stripes + i;
5986 } /* else if RAID[56], multiply by nr_data_stripes().
5987 * Alternatively, just use rmap_len below instead of
5988 * map->stripe_len */
5990 bytenr = chunk_start + stripe_nr * rmap_len;
5991 WARN_ON(nr >= map->num_stripes);
5992 for (j = 0; j < nr; j++) {
5993 if (buf[j] == bytenr)
5997 WARN_ON(nr >= map->num_stripes);
6004 *stripe_len = rmap_len;
6006 free_extent_map(em);
6010 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6012 bio->bi_private = bbio->private;
6013 bio->bi_end_io = bbio->end_io;
6016 btrfs_put_bbio(bbio);
6019 static void btrfs_end_bio(struct bio *bio)
6021 struct btrfs_bio *bbio = bio->bi_private;
6022 int is_orig_bio = 0;
6024 if (bio->bi_status) {
6025 atomic_inc(&bbio->error);
6026 if (bio->bi_status == BLK_STS_IOERR ||
6027 bio->bi_status == BLK_STS_TARGET) {
6028 unsigned int stripe_index =
6029 btrfs_io_bio(bio)->stripe_index;
6030 struct btrfs_device *dev;
6032 BUG_ON(stripe_index >= bbio->num_stripes);
6033 dev = bbio->stripes[stripe_index].dev;
6035 if (bio_op(bio) == REQ_OP_WRITE)
6036 btrfs_dev_stat_inc(dev,
6037 BTRFS_DEV_STAT_WRITE_ERRS);
6039 btrfs_dev_stat_inc(dev,
6040 BTRFS_DEV_STAT_READ_ERRS);
6041 if (bio->bi_opf & REQ_PREFLUSH)
6042 btrfs_dev_stat_inc(dev,
6043 BTRFS_DEV_STAT_FLUSH_ERRS);
6044 btrfs_dev_stat_print_on_error(dev);
6049 if (bio == bbio->orig_bio)
6052 btrfs_bio_counter_dec(bbio->fs_info);
6054 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6057 bio = bbio->orig_bio;
6060 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6061 /* only send an error to the higher layers if it is
6062 * beyond the tolerance of the btrfs bio
6064 if (atomic_read(&bbio->error) > bbio->max_errors) {
6065 bio->bi_status = BLK_STS_IOERR;
6068 * this bio is actually up to date, we didn't
6069 * go over the max number of errors
6074 btrfs_end_bbio(bbio, bio);
6075 } else if (!is_orig_bio) {
6081 * see run_scheduled_bios for a description of why bios are collected for
6084 * This will add one bio to the pending list for a device and make sure
6085 * the work struct is scheduled.
6087 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6090 struct btrfs_fs_info *fs_info = device->fs_info;
6091 int should_queue = 1;
6092 struct btrfs_pending_bios *pending_bios;
6094 if (device->missing || !device->bdev) {
6099 /* don't bother with additional async steps for reads, right now */
6100 if (bio_op(bio) == REQ_OP_READ) {
6102 btrfsic_submit_bio(bio);
6108 * nr_async_bios allows us to reliably return congestion to the
6109 * higher layers. Otherwise, the async bio makes it appear we have
6110 * made progress against dirty pages when we've really just put it
6111 * on a queue for later
6113 atomic_inc(&fs_info->nr_async_bios);
6114 WARN_ON(bio->bi_next);
6115 bio->bi_next = NULL;
6117 spin_lock(&device->io_lock);
6118 if (op_is_sync(bio->bi_opf))
6119 pending_bios = &device->pending_sync_bios;
6121 pending_bios = &device->pending_bios;
6123 if (pending_bios->tail)
6124 pending_bios->tail->bi_next = bio;
6126 pending_bios->tail = bio;
6127 if (!pending_bios->head)
6128 pending_bios->head = bio;
6129 if (device->running_pending)
6132 spin_unlock(&device->io_lock);
6135 btrfs_queue_work(fs_info->submit_workers, &device->work);
6138 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6139 u64 physical, int dev_nr, int async)
6141 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6142 struct btrfs_fs_info *fs_info = bbio->fs_info;
6144 bio->bi_private = bbio;
6145 btrfs_io_bio(bio)->stripe_index = dev_nr;
6146 bio->bi_end_io = btrfs_end_bio;
6147 bio->bi_iter.bi_sector = physical >> 9;
6150 struct rcu_string *name;
6153 name = rcu_dereference(dev->name);
6154 btrfs_debug(fs_info,
6155 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6156 bio_op(bio), bio->bi_opf,
6157 (u64)bio->bi_iter.bi_sector,
6158 (u_long)dev->bdev->bd_dev, name->str, dev->devid,
6159 bio->bi_iter.bi_size);
6163 bio_set_dev(bio, dev->bdev);
6165 btrfs_bio_counter_inc_noblocked(fs_info);
6168 btrfs_schedule_bio(dev, bio);
6170 btrfsic_submit_bio(bio);
6173 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6175 atomic_inc(&bbio->error);
6176 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6177 /* Should be the original bio. */
6178 WARN_ON(bio != bbio->orig_bio);
6180 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6181 bio->bi_iter.bi_sector = logical >> 9;
6182 if (atomic_read(&bbio->error) > bbio->max_errors)
6183 bio->bi_status = BLK_STS_IOERR;
6185 bio->bi_status = BLK_STS_OK;
6186 btrfs_end_bbio(bbio, bio);
6190 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6191 int mirror_num, int async_submit)
6193 struct btrfs_device *dev;
6194 struct bio *first_bio = bio;
6195 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6201 struct btrfs_bio *bbio = NULL;
6203 length = bio->bi_iter.bi_size;
6204 map_length = length;
6206 btrfs_bio_counter_inc_blocked(fs_info);
6207 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6208 &map_length, &bbio, mirror_num, 1);
6210 btrfs_bio_counter_dec(fs_info);
6211 return errno_to_blk_status(ret);
6214 total_devs = bbio->num_stripes;
6215 bbio->orig_bio = first_bio;
6216 bbio->private = first_bio->bi_private;
6217 bbio->end_io = first_bio->bi_end_io;
6218 bbio->fs_info = fs_info;
6219 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6221 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6222 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6223 /* In this case, map_length has been set to the length of
6224 a single stripe; not the whole write */
6225 if (bio_op(bio) == REQ_OP_WRITE) {
6226 ret = raid56_parity_write(fs_info, bio, bbio,
6229 ret = raid56_parity_recover(fs_info, bio, bbio,
6230 map_length, mirror_num, 1);
6233 btrfs_bio_counter_dec(fs_info);
6234 return errno_to_blk_status(ret);
6237 if (map_length < length) {
6239 "mapping failed logical %llu bio len %llu len %llu",
6240 logical, length, map_length);
6244 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6245 dev = bbio->stripes[dev_nr].dev;
6246 if (!dev || !dev->bdev ||
6247 (bio_op(first_bio) == REQ_OP_WRITE && !dev->writeable)) {
6248 bbio_error(bbio, first_bio, logical);
6252 if (dev_nr < total_devs - 1)
6253 bio = btrfs_bio_clone(first_bio);
6257 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6258 dev_nr, async_submit);
6260 btrfs_bio_counter_dec(fs_info);
6264 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6267 struct btrfs_device *device;
6268 struct btrfs_fs_devices *cur_devices;
6270 cur_devices = fs_info->fs_devices;
6271 while (cur_devices) {
6273 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6274 device = find_device(cur_devices, devid, uuid);
6278 cur_devices = cur_devices->seed;
6283 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6284 u64 devid, u8 *dev_uuid)
6286 struct btrfs_device *device;
6287 unsigned int nofs_flag;
6290 * We call this under the chunk_mutex, so we want to use NOFS for this
6291 * allocation, however we don't want to change btrfs_alloc_device() to
6292 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6295 nofs_flag = memalloc_nofs_save();
6296 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6297 memalloc_nofs_restore(nofs_flag);
6301 list_add(&device->dev_list, &fs_devices->devices);
6302 device->fs_devices = fs_devices;
6303 fs_devices->num_devices++;
6305 device->missing = 1;
6306 fs_devices->missing_devices++;
6312 * btrfs_alloc_device - allocate struct btrfs_device
6313 * @fs_info: used only for generating a new devid, can be NULL if
6314 * devid is provided (i.e. @devid != NULL).
6315 * @devid: a pointer to devid for this device. If NULL a new devid
6317 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6320 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6321 * on error. Returned struct is not linked onto any lists and can be
6322 * destroyed with kfree() right away.
6324 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6328 struct btrfs_device *dev;
6331 if (WARN_ON(!devid && !fs_info))
6332 return ERR_PTR(-EINVAL);
6334 dev = __alloc_device();
6343 ret = find_next_devid(fs_info, &tmp);
6346 return ERR_PTR(ret);
6352 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6354 generate_random_uuid(dev->uuid);
6356 btrfs_init_work(&dev->work, btrfs_submit_helper,
6357 pending_bios_fn, NULL, NULL);
6362 /* Return -EIO if any error, otherwise return 0. */
6363 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6364 struct extent_buffer *leaf,
6365 struct btrfs_chunk *chunk, u64 logical)
6375 length = btrfs_chunk_length(leaf, chunk);
6376 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6377 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6378 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6379 type = btrfs_chunk_type(leaf, chunk);
6382 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6386 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6387 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6390 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6391 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6392 btrfs_chunk_sector_size(leaf, chunk));
6395 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6396 btrfs_err(fs_info, "invalid chunk length %llu", length);
6399 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6400 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6404 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6406 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6407 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6408 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6409 btrfs_chunk_type(leaf, chunk));
6413 if (!is_power_of_2(type & BTRFS_BLOCK_GROUP_PROFILE_MASK) &&
6414 (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) != 0) {
6416 "invalid chunk profile flag: 0x%llx, expect 0 or 1 bit set",
6417 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6420 if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == 0) {
6421 btrfs_err(fs_info, "missing chunk type flag: 0x%llx", type);
6425 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) &&
6426 (type & (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA))) {
6428 "system chunk with data or metadata type: 0x%llx", type);
6432 features = btrfs_super_incompat_flags(fs_info->super_copy);
6433 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
6437 if ((type & BTRFS_BLOCK_GROUP_METADATA) &&
6438 (type & BTRFS_BLOCK_GROUP_DATA)) {
6440 "mixed chunk type in non-mixed mode: 0x%llx", type);
6445 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6446 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes != 2) ||
6447 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6448 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6449 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes != 2) ||
6450 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6451 num_stripes != 1)) {
6453 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6454 num_stripes, sub_stripes,
6455 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6462 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6463 struct extent_buffer *leaf,
6464 struct btrfs_chunk *chunk)
6466 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6467 struct map_lookup *map;
6468 struct extent_map *em;
6472 u8 uuid[BTRFS_UUID_SIZE];
6477 logical = key->offset;
6478 length = btrfs_chunk_length(leaf, chunk);
6479 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6481 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6485 read_lock(&map_tree->map_tree.lock);
6486 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6487 read_unlock(&map_tree->map_tree.lock);
6489 /* already mapped? */
6490 if (em && em->start <= logical && em->start + em->len > logical) {
6491 free_extent_map(em);
6494 free_extent_map(em);
6497 em = alloc_extent_map();
6500 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6502 free_extent_map(em);
6506 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6507 em->map_lookup = map;
6508 em->start = logical;
6511 em->block_start = 0;
6512 em->block_len = em->len;
6514 map->num_stripes = num_stripes;
6515 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6516 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6517 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6518 map->type = btrfs_chunk_type(leaf, chunk);
6519 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6520 for (i = 0; i < num_stripes; i++) {
6521 map->stripes[i].physical =
6522 btrfs_stripe_offset_nr(leaf, chunk, i);
6523 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6524 read_extent_buffer(leaf, uuid, (unsigned long)
6525 btrfs_stripe_dev_uuid_nr(chunk, i),
6527 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6529 if (!map->stripes[i].dev &&
6530 !btrfs_test_opt(fs_info, DEGRADED)) {
6531 free_extent_map(em);
6532 btrfs_report_missing_device(fs_info, devid, uuid);
6535 if (!map->stripes[i].dev) {
6536 map->stripes[i].dev =
6537 add_missing_dev(fs_info->fs_devices, devid,
6539 if (!map->stripes[i].dev) {
6540 free_extent_map(em);
6543 btrfs_report_missing_device(fs_info, devid, uuid);
6545 map->stripes[i].dev->in_fs_metadata = 1;
6548 write_lock(&map_tree->map_tree.lock);
6549 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6550 write_unlock(&map_tree->map_tree.lock);
6553 "failed to add chunk map, start=%llu len=%llu: %d",
6554 em->start, em->len, ret);
6556 free_extent_map(em);
6561 static void fill_device_from_item(struct extent_buffer *leaf,
6562 struct btrfs_dev_item *dev_item,
6563 struct btrfs_device *device)
6567 device->devid = btrfs_device_id(leaf, dev_item);
6568 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6569 device->total_bytes = device->disk_total_bytes;
6570 device->commit_total_bytes = device->disk_total_bytes;
6571 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6572 device->commit_bytes_used = device->bytes_used;
6573 device->type = btrfs_device_type(leaf, dev_item);
6574 device->io_align = btrfs_device_io_align(leaf, dev_item);
6575 device->io_width = btrfs_device_io_width(leaf, dev_item);
6576 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6577 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6578 device->is_tgtdev_for_dev_replace = 0;
6580 ptr = btrfs_device_uuid(dev_item);
6581 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6584 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6587 struct btrfs_fs_devices *fs_devices;
6590 BUG_ON(!mutex_is_locked(&uuid_mutex));
6593 fs_devices = fs_info->fs_devices->seed;
6594 while (fs_devices) {
6595 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6598 fs_devices = fs_devices->seed;
6601 fs_devices = find_fsid(fsid);
6603 if (!btrfs_test_opt(fs_info, DEGRADED))
6604 return ERR_PTR(-ENOENT);
6606 fs_devices = alloc_fs_devices(fsid);
6607 if (IS_ERR(fs_devices))
6610 fs_devices->seeding = 1;
6611 fs_devices->opened = 1;
6615 fs_devices = clone_fs_devices(fs_devices);
6616 if (IS_ERR(fs_devices))
6619 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6620 fs_info->bdev_holder);
6622 free_fs_devices(fs_devices);
6623 fs_devices = ERR_PTR(ret);
6627 if (!fs_devices->seeding) {
6628 __btrfs_close_devices(fs_devices);
6629 free_fs_devices(fs_devices);
6630 fs_devices = ERR_PTR(-EINVAL);
6634 fs_devices->seed = fs_info->fs_devices->seed;
6635 fs_info->fs_devices->seed = fs_devices;
6640 static int read_one_dev(struct btrfs_fs_info *fs_info,
6641 struct extent_buffer *leaf,
6642 struct btrfs_dev_item *dev_item)
6644 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6645 struct btrfs_device *device;
6648 u8 fs_uuid[BTRFS_FSID_SIZE];
6649 u8 dev_uuid[BTRFS_UUID_SIZE];
6651 devid = btrfs_device_id(leaf, dev_item);
6652 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6654 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6657 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6658 fs_devices = open_seed_devices(fs_info, fs_uuid);
6659 if (IS_ERR(fs_devices))
6660 return PTR_ERR(fs_devices);
6663 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6665 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6666 btrfs_report_missing_device(fs_info, devid, dev_uuid);
6670 device = add_missing_dev(fs_devices, devid, dev_uuid);
6673 btrfs_report_missing_device(fs_info, devid, dev_uuid);
6675 if (!device->bdev) {
6676 btrfs_report_missing_device(fs_info, devid, dev_uuid);
6677 if (!btrfs_test_opt(fs_info, DEGRADED))
6681 if(!device->bdev && !device->missing) {
6683 * this happens when a device that was properly setup
6684 * in the device info lists suddenly goes bad.
6685 * device->bdev is NULL, and so we have to set
6686 * device->missing to one here
6688 device->fs_devices->missing_devices++;
6689 device->missing = 1;
6692 /* Move the device to its own fs_devices */
6693 if (device->fs_devices != fs_devices) {
6694 ASSERT(device->missing);
6696 list_move(&device->dev_list, &fs_devices->devices);
6697 device->fs_devices->num_devices--;
6698 fs_devices->num_devices++;
6700 device->fs_devices->missing_devices--;
6701 fs_devices->missing_devices++;
6703 device->fs_devices = fs_devices;
6707 if (device->fs_devices != fs_info->fs_devices) {
6708 BUG_ON(device->writeable);
6709 if (device->generation !=
6710 btrfs_device_generation(leaf, dev_item))
6714 fill_device_from_item(leaf, dev_item, device);
6715 device->in_fs_metadata = 1;
6716 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6717 device->fs_devices->total_rw_bytes += device->total_bytes;
6718 atomic64_add(device->total_bytes - device->bytes_used,
6719 &fs_info->free_chunk_space);
6725 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6727 struct btrfs_root *root = fs_info->tree_root;
6728 struct btrfs_super_block *super_copy = fs_info->super_copy;
6729 struct extent_buffer *sb;
6730 struct btrfs_disk_key *disk_key;
6731 struct btrfs_chunk *chunk;
6733 unsigned long sb_array_offset;
6740 struct btrfs_key key;
6742 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6744 * This will create extent buffer of nodesize, superblock size is
6745 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6746 * overallocate but we can keep it as-is, only the first page is used.
6748 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6751 set_extent_buffer_uptodate(sb);
6752 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6754 * The sb extent buffer is artificial and just used to read the system array.
6755 * set_extent_buffer_uptodate() call does not properly mark all it's
6756 * pages up-to-date when the page is larger: extent does not cover the
6757 * whole page and consequently check_page_uptodate does not find all
6758 * the page's extents up-to-date (the hole beyond sb),
6759 * write_extent_buffer then triggers a WARN_ON.
6761 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6762 * but sb spans only this function. Add an explicit SetPageUptodate call
6763 * to silence the warning eg. on PowerPC 64.
6765 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6766 SetPageUptodate(sb->pages[0]);
6768 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6769 array_size = btrfs_super_sys_array_size(super_copy);
6771 array_ptr = super_copy->sys_chunk_array;
6772 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6775 while (cur_offset < array_size) {
6776 disk_key = (struct btrfs_disk_key *)array_ptr;
6777 len = sizeof(*disk_key);
6778 if (cur_offset + len > array_size)
6779 goto out_short_read;
6781 btrfs_disk_key_to_cpu(&key, disk_key);
6784 sb_array_offset += len;
6787 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6788 chunk = (struct btrfs_chunk *)sb_array_offset;
6790 * At least one btrfs_chunk with one stripe must be
6791 * present, exact stripe count check comes afterwards
6793 len = btrfs_chunk_item_size(1);
6794 if (cur_offset + len > array_size)
6795 goto out_short_read;
6797 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6800 "invalid number of stripes %u in sys_array at offset %u",
6801 num_stripes, cur_offset);
6806 type = btrfs_chunk_type(sb, chunk);
6807 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6809 "invalid chunk type %llu in sys_array at offset %u",
6815 len = btrfs_chunk_item_size(num_stripes);
6816 if (cur_offset + len > array_size)
6817 goto out_short_read;
6819 ret = read_one_chunk(fs_info, &key, sb, chunk);
6824 "unexpected item type %u in sys_array at offset %u",
6825 (u32)key.type, cur_offset);
6830 sb_array_offset += len;
6833 clear_extent_buffer_uptodate(sb);
6834 free_extent_buffer_stale(sb);
6838 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6840 clear_extent_buffer_uptodate(sb);
6841 free_extent_buffer_stale(sb);
6845 void btrfs_report_missing_device(struct btrfs_fs_info *fs_info, u64 devid,
6848 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing", devid, uuid);
6852 * Check if all chunks in the fs are OK for read-write degraded mount
6854 * Return true if all chunks meet the minimal RW mount requirements.
6855 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6857 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info)
6859 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6860 struct extent_map *em;
6864 read_lock(&map_tree->map_tree.lock);
6865 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6866 read_unlock(&map_tree->map_tree.lock);
6867 /* No chunk at all? Return false anyway */
6873 struct map_lookup *map;
6878 map = em->map_lookup;
6880 btrfs_get_num_tolerated_disk_barrier_failures(
6882 for (i = 0; i < map->num_stripes; i++) {
6883 struct btrfs_device *dev = map->stripes[i].dev;
6885 if (!dev || !dev->bdev || dev->missing ||
6886 dev->last_flush_error)
6889 if (missing > max_tolerated) {
6891 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6892 em->start, missing, max_tolerated);
6893 free_extent_map(em);
6897 next_start = extent_map_end(em);
6898 free_extent_map(em);
6900 read_lock(&map_tree->map_tree.lock);
6901 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6902 (u64)(-1) - next_start);
6903 read_unlock(&map_tree->map_tree.lock);
6909 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6911 struct btrfs_root *root = fs_info->chunk_root;
6912 struct btrfs_path *path;
6913 struct extent_buffer *leaf;
6914 struct btrfs_key key;
6915 struct btrfs_key found_key;
6920 path = btrfs_alloc_path();
6924 mutex_lock(&uuid_mutex);
6925 mutex_lock(&fs_info->chunk_mutex);
6928 * It is possible for mount and umount to race in such a way that
6929 * we execute this code path, but open_fs_devices failed to clear
6930 * total_rw_bytes. We certainly want it cleared before reading the
6931 * device items, so clear it here.
6933 fs_info->fs_devices->total_rw_bytes = 0;
6936 * Read all device items, and then all the chunk items. All
6937 * device items are found before any chunk item (their object id
6938 * is smaller than the lowest possible object id for a chunk
6939 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6941 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6944 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6948 leaf = path->nodes[0];
6949 slot = path->slots[0];
6950 if (slot >= btrfs_header_nritems(leaf)) {
6951 ret = btrfs_next_leaf(root, path);
6958 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6959 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6960 struct btrfs_dev_item *dev_item;
6961 dev_item = btrfs_item_ptr(leaf, slot,
6962 struct btrfs_dev_item);
6963 ret = read_one_dev(fs_info, leaf, dev_item);
6967 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6968 struct btrfs_chunk *chunk;
6969 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6970 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
6978 * After loading chunk tree, we've got all device information,
6979 * do another round of validation checks.
6981 if (total_dev != fs_info->fs_devices->total_devices) {
6983 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
6984 btrfs_super_num_devices(fs_info->super_copy),
6986 fs_info->fs_devices->total_devices = total_dev;
6987 btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
6989 if (btrfs_super_total_bytes(fs_info->super_copy) <
6990 fs_info->fs_devices->total_rw_bytes) {
6992 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
6993 btrfs_super_total_bytes(fs_info->super_copy),
6994 fs_info->fs_devices->total_rw_bytes);
7000 mutex_unlock(&fs_info->chunk_mutex);
7001 mutex_unlock(&uuid_mutex);
7003 btrfs_free_path(path);
7007 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7009 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7010 struct btrfs_device *device;
7012 while (fs_devices) {
7013 mutex_lock(&fs_devices->device_list_mutex);
7014 list_for_each_entry(device, &fs_devices->devices, dev_list)
7015 device->fs_info = fs_info;
7016 mutex_unlock(&fs_devices->device_list_mutex);
7018 fs_devices = fs_devices->seed;
7022 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7026 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7027 btrfs_dev_stat_reset(dev, i);
7030 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7032 struct btrfs_key key;
7033 struct btrfs_key found_key;
7034 struct btrfs_root *dev_root = fs_info->dev_root;
7035 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7036 struct extent_buffer *eb;
7039 struct btrfs_device *device;
7040 struct btrfs_path *path = NULL;
7043 path = btrfs_alloc_path();
7049 mutex_lock(&fs_devices->device_list_mutex);
7050 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7052 struct btrfs_dev_stats_item *ptr;
7054 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7055 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7056 key.offset = device->devid;
7057 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7059 __btrfs_reset_dev_stats(device);
7060 device->dev_stats_valid = 1;
7061 btrfs_release_path(path);
7064 slot = path->slots[0];
7065 eb = path->nodes[0];
7066 btrfs_item_key_to_cpu(eb, &found_key, slot);
7067 item_size = btrfs_item_size_nr(eb, slot);
7069 ptr = btrfs_item_ptr(eb, slot,
7070 struct btrfs_dev_stats_item);
7072 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7073 if (item_size >= (1 + i) * sizeof(__le64))
7074 btrfs_dev_stat_set(device, i,
7075 btrfs_dev_stats_value(eb, ptr, i));
7077 btrfs_dev_stat_reset(device, i);
7080 device->dev_stats_valid = 1;
7081 btrfs_dev_stat_print_on_load(device);
7082 btrfs_release_path(path);
7084 mutex_unlock(&fs_devices->device_list_mutex);
7087 btrfs_free_path(path);
7088 return ret < 0 ? ret : 0;
7091 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7092 struct btrfs_fs_info *fs_info,
7093 struct btrfs_device *device)
7095 struct btrfs_root *dev_root = fs_info->dev_root;
7096 struct btrfs_path *path;
7097 struct btrfs_key key;
7098 struct extent_buffer *eb;
7099 struct btrfs_dev_stats_item *ptr;
7103 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7104 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7105 key.offset = device->devid;
7107 path = btrfs_alloc_path();
7110 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7112 btrfs_warn_in_rcu(fs_info,
7113 "error %d while searching for dev_stats item for device %s",
7114 ret, rcu_str_deref(device->name));
7119 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7120 /* need to delete old one and insert a new one */
7121 ret = btrfs_del_item(trans, dev_root, path);
7123 btrfs_warn_in_rcu(fs_info,
7124 "delete too small dev_stats item for device %s failed %d",
7125 rcu_str_deref(device->name), ret);
7132 /* need to insert a new item */
7133 btrfs_release_path(path);
7134 ret = btrfs_insert_empty_item(trans, dev_root, path,
7135 &key, sizeof(*ptr));
7137 btrfs_warn_in_rcu(fs_info,
7138 "insert dev_stats item for device %s failed %d",
7139 rcu_str_deref(device->name), ret);
7144 eb = path->nodes[0];
7145 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7146 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7147 btrfs_set_dev_stats_value(eb, ptr, i,
7148 btrfs_dev_stat_read(device, i));
7149 btrfs_mark_buffer_dirty(eb);
7152 btrfs_free_path(path);
7157 * called from commit_transaction. Writes all changed device stats to disk.
7159 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7160 struct btrfs_fs_info *fs_info)
7162 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7163 struct btrfs_device *device;
7167 mutex_lock(&fs_devices->device_list_mutex);
7168 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7169 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7170 if (!device->dev_stats_valid || stats_cnt == 0)
7175 * There is a LOAD-LOAD control dependency between the value of
7176 * dev_stats_ccnt and updating the on-disk values which requires
7177 * reading the in-memory counters. Such control dependencies
7178 * require explicit read memory barriers.
7180 * This memory barriers pairs with smp_mb__before_atomic in
7181 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7182 * barrier implied by atomic_xchg in
7183 * btrfs_dev_stats_read_and_reset
7187 ret = update_dev_stat_item(trans, fs_info, device);
7189 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7191 mutex_unlock(&fs_devices->device_list_mutex);
7196 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7198 btrfs_dev_stat_inc(dev, index);
7199 btrfs_dev_stat_print_on_error(dev);
7202 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7204 if (!dev->dev_stats_valid)
7206 btrfs_err_rl_in_rcu(dev->fs_info,
7207 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7208 rcu_str_deref(dev->name),
7209 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7210 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7211 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7212 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7213 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7216 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7220 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7221 if (btrfs_dev_stat_read(dev, i) != 0)
7223 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7224 return; /* all values == 0, suppress message */
7226 btrfs_info_in_rcu(dev->fs_info,
7227 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7228 rcu_str_deref(dev->name),
7229 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7230 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7231 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7232 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7233 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7236 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7237 struct btrfs_ioctl_get_dev_stats *stats)
7239 struct btrfs_device *dev;
7240 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7243 mutex_lock(&fs_devices->device_list_mutex);
7244 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7245 mutex_unlock(&fs_devices->device_list_mutex);
7248 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7250 } else if (!dev->dev_stats_valid) {
7251 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7253 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7254 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7255 if (stats->nr_items > i)
7257 btrfs_dev_stat_read_and_reset(dev, i);
7259 btrfs_dev_stat_reset(dev, i);
7261 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7262 current->comm, task_pid_nr(current));
7264 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7265 if (stats->nr_items > i)
7266 stats->values[i] = btrfs_dev_stat_read(dev, i);
7268 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7269 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7273 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7275 struct buffer_head *bh;
7276 struct btrfs_super_block *disk_super;
7282 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7285 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7288 disk_super = (struct btrfs_super_block *)bh->b_data;
7290 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7291 set_buffer_dirty(bh);
7292 sync_dirty_buffer(bh);
7296 /* Notify udev that device has changed */
7297 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7299 /* Update ctime/mtime for device path for libblkid */
7300 update_dev_time(device_path);
7304 * Update the size of all devices, which is used for writing out the
7307 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7309 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7310 struct btrfs_device *curr, *next;
7312 if (list_empty(&fs_devices->resized_devices))
7315 mutex_lock(&fs_devices->device_list_mutex);
7316 mutex_lock(&fs_info->chunk_mutex);
7317 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7319 list_del_init(&curr->resized_list);
7320 curr->commit_total_bytes = curr->disk_total_bytes;
7322 mutex_unlock(&fs_info->chunk_mutex);
7323 mutex_unlock(&fs_devices->device_list_mutex);
7326 /* Must be invoked during the transaction commit */
7327 void btrfs_update_commit_device_bytes_used(struct btrfs_fs_info *fs_info,
7328 struct btrfs_transaction *transaction)
7330 struct extent_map *em;
7331 struct map_lookup *map;
7332 struct btrfs_device *dev;
7335 if (list_empty(&transaction->pending_chunks))
7338 /* In order to kick the device replace finish process */
7339 mutex_lock(&fs_info->chunk_mutex);
7340 list_for_each_entry(em, &transaction->pending_chunks, list) {
7341 map = em->map_lookup;
7343 for (i = 0; i < map->num_stripes; i++) {
7344 dev = map->stripes[i].dev;
7345 dev->commit_bytes_used = dev->bytes_used;
7346 dev->has_pending_chunks = false;
7349 mutex_unlock(&fs_info->chunk_mutex);
7352 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7354 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7355 while (fs_devices) {
7356 fs_devices->fs_info = fs_info;
7357 fs_devices = fs_devices->seed;
7361 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7363 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7364 while (fs_devices) {
7365 fs_devices->fs_info = NULL;
7366 fs_devices = fs_devices->seed;