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);
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_start) {
1424 hole_size = key.offset - search_start;
1427 * Have to check before we set max_hole_start, otherwise
1428 * we could end up sending back this offset anyway.
1430 if (contains_pending_extent(transaction, device,
1433 if (key.offset >= search_start) {
1434 hole_size = key.offset - search_start;
1441 if (hole_size > max_hole_size) {
1442 max_hole_start = search_start;
1443 max_hole_size = hole_size;
1447 * If this free space is greater than which we need,
1448 * it must be the max free space that we have found
1449 * until now, so max_hole_start must point to the start
1450 * of this free space and the length of this free space
1451 * is stored in max_hole_size. Thus, we return
1452 * max_hole_start and max_hole_size and go back to the
1455 if (hole_size >= num_bytes) {
1461 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1462 extent_end = key.offset + btrfs_dev_extent_length(l,
1464 if (extent_end > search_start)
1465 search_start = extent_end;
1472 * At this point, search_start should be the end of
1473 * allocated dev extents, and when shrinking the device,
1474 * search_end may be smaller than search_start.
1476 if (search_end > search_start) {
1477 hole_size = search_end - search_start;
1479 if (contains_pending_extent(transaction, device, &search_start,
1481 btrfs_release_path(path);
1485 if (hole_size > max_hole_size) {
1486 max_hole_start = search_start;
1487 max_hole_size = hole_size;
1492 if (max_hole_size < num_bytes)
1498 btrfs_free_path(path);
1499 *start = max_hole_start;
1501 *len = max_hole_size;
1505 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1506 struct btrfs_device *device, u64 num_bytes,
1507 u64 *start, u64 *len)
1509 /* FIXME use last free of some kind */
1510 return find_free_dev_extent_start(trans->transaction, device,
1511 num_bytes, 0, start, len);
1514 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1515 struct btrfs_device *device,
1516 u64 start, u64 *dev_extent_len)
1518 struct btrfs_fs_info *fs_info = device->fs_info;
1519 struct btrfs_root *root = fs_info->dev_root;
1521 struct btrfs_path *path;
1522 struct btrfs_key key;
1523 struct btrfs_key found_key;
1524 struct extent_buffer *leaf = NULL;
1525 struct btrfs_dev_extent *extent = NULL;
1527 path = btrfs_alloc_path();
1531 key.objectid = device->devid;
1533 key.type = BTRFS_DEV_EXTENT_KEY;
1535 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1537 ret = btrfs_previous_item(root, path, key.objectid,
1538 BTRFS_DEV_EXTENT_KEY);
1541 leaf = path->nodes[0];
1542 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1543 extent = btrfs_item_ptr(leaf, path->slots[0],
1544 struct btrfs_dev_extent);
1545 BUG_ON(found_key.offset > start || found_key.offset +
1546 btrfs_dev_extent_length(leaf, extent) < start);
1548 btrfs_release_path(path);
1550 } else if (ret == 0) {
1551 leaf = path->nodes[0];
1552 extent = btrfs_item_ptr(leaf, path->slots[0],
1553 struct btrfs_dev_extent);
1555 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1559 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1561 ret = btrfs_del_item(trans, root, path);
1563 btrfs_handle_fs_error(fs_info, ret,
1564 "Failed to remove dev extent item");
1566 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1569 btrfs_free_path(path);
1573 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1574 struct btrfs_device *device,
1575 u64 chunk_offset, u64 start, u64 num_bytes)
1578 struct btrfs_path *path;
1579 struct btrfs_fs_info *fs_info = device->fs_info;
1580 struct btrfs_root *root = fs_info->dev_root;
1581 struct btrfs_dev_extent *extent;
1582 struct extent_buffer *leaf;
1583 struct btrfs_key key;
1585 WARN_ON(!device->in_fs_metadata);
1586 WARN_ON(device->is_tgtdev_for_dev_replace);
1587 path = btrfs_alloc_path();
1591 key.objectid = device->devid;
1593 key.type = BTRFS_DEV_EXTENT_KEY;
1594 ret = btrfs_insert_empty_item(trans, root, path, &key,
1599 leaf = path->nodes[0];
1600 extent = btrfs_item_ptr(leaf, path->slots[0],
1601 struct btrfs_dev_extent);
1602 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1603 BTRFS_CHUNK_TREE_OBJECTID);
1604 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1605 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1606 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1608 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1609 btrfs_mark_buffer_dirty(leaf);
1611 btrfs_free_path(path);
1615 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1617 struct extent_map_tree *em_tree;
1618 struct extent_map *em;
1622 em_tree = &fs_info->mapping_tree.map_tree;
1623 read_lock(&em_tree->lock);
1624 n = rb_last(&em_tree->map);
1626 em = rb_entry(n, struct extent_map, rb_node);
1627 ret = em->start + em->len;
1629 read_unlock(&em_tree->lock);
1634 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1638 struct btrfs_key key;
1639 struct btrfs_key found_key;
1640 struct btrfs_path *path;
1642 path = btrfs_alloc_path();
1646 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1647 key.type = BTRFS_DEV_ITEM_KEY;
1648 key.offset = (u64)-1;
1650 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1654 BUG_ON(ret == 0); /* Corruption */
1656 ret = btrfs_previous_item(fs_info->chunk_root, path,
1657 BTRFS_DEV_ITEMS_OBJECTID,
1658 BTRFS_DEV_ITEM_KEY);
1662 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1664 *devid_ret = found_key.offset + 1;
1668 btrfs_free_path(path);
1673 * the device information is stored in the chunk root
1674 * the btrfs_device struct should be fully filled in
1676 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1677 struct btrfs_fs_info *fs_info,
1678 struct btrfs_device *device)
1680 struct btrfs_root *root = fs_info->chunk_root;
1682 struct btrfs_path *path;
1683 struct btrfs_dev_item *dev_item;
1684 struct extent_buffer *leaf;
1685 struct btrfs_key key;
1688 path = btrfs_alloc_path();
1692 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1693 key.type = BTRFS_DEV_ITEM_KEY;
1694 key.offset = device->devid;
1696 ret = btrfs_insert_empty_item(trans, root, path, &key,
1701 leaf = path->nodes[0];
1702 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1704 btrfs_set_device_id(leaf, dev_item, device->devid);
1705 btrfs_set_device_generation(leaf, dev_item, 0);
1706 btrfs_set_device_type(leaf, dev_item, device->type);
1707 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1708 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1709 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1710 btrfs_set_device_total_bytes(leaf, dev_item,
1711 btrfs_device_get_disk_total_bytes(device));
1712 btrfs_set_device_bytes_used(leaf, dev_item,
1713 btrfs_device_get_bytes_used(device));
1714 btrfs_set_device_group(leaf, dev_item, 0);
1715 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1716 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1717 btrfs_set_device_start_offset(leaf, dev_item, 0);
1719 ptr = btrfs_device_uuid(dev_item);
1720 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1721 ptr = btrfs_device_fsid(dev_item);
1722 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1723 btrfs_mark_buffer_dirty(leaf);
1727 btrfs_free_path(path);
1732 * Function to update ctime/mtime for a given device path.
1733 * Mainly used for ctime/mtime based probe like libblkid.
1735 static void update_dev_time(const char *path_name)
1739 filp = filp_open(path_name, O_RDWR, 0);
1742 file_update_time(filp);
1743 filp_close(filp, NULL);
1746 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1747 struct btrfs_device *device)
1749 struct btrfs_root *root = fs_info->chunk_root;
1751 struct btrfs_path *path;
1752 struct btrfs_key key;
1753 struct btrfs_trans_handle *trans;
1755 path = btrfs_alloc_path();
1759 trans = btrfs_start_transaction(root, 0);
1760 if (IS_ERR(trans)) {
1761 btrfs_free_path(path);
1762 return PTR_ERR(trans);
1764 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1765 key.type = BTRFS_DEV_ITEM_KEY;
1766 key.offset = device->devid;
1768 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1772 btrfs_abort_transaction(trans, ret);
1773 btrfs_end_transaction(trans);
1777 ret = btrfs_del_item(trans, root, path);
1779 btrfs_abort_transaction(trans, ret);
1780 btrfs_end_transaction(trans);
1784 btrfs_free_path(path);
1786 ret = btrfs_commit_transaction(trans);
1791 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1792 * filesystem. It's up to the caller to adjust that number regarding eg. device
1795 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1803 seq = read_seqbegin(&fs_info->profiles_lock);
1805 all_avail = fs_info->avail_data_alloc_bits |
1806 fs_info->avail_system_alloc_bits |
1807 fs_info->avail_metadata_alloc_bits;
1808 } while (read_seqretry(&fs_info->profiles_lock, seq));
1810 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1811 if (!(all_avail & btrfs_raid_group[i]))
1814 if (num_devices < btrfs_raid_array[i].devs_min) {
1815 int ret = btrfs_raid_mindev_error[i];
1825 struct btrfs_device *btrfs_find_next_active_device(struct btrfs_fs_devices *fs_devs,
1826 struct btrfs_device *device)
1828 struct btrfs_device *next_device;
1830 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1831 if (next_device != device &&
1832 !next_device->missing && next_device->bdev)
1840 * Helper function to check if the given device is part of s_bdev / latest_bdev
1841 * and replace it with the provided or the next active device, in the context
1842 * where this function called, there should be always be another device (or
1843 * this_dev) which is active.
1845 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1846 struct btrfs_device *device, struct btrfs_device *this_dev)
1848 struct btrfs_device *next_device;
1851 next_device = this_dev;
1853 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1855 ASSERT(next_device);
1857 if (fs_info->sb->s_bdev &&
1858 (fs_info->sb->s_bdev == device->bdev))
1859 fs_info->sb->s_bdev = next_device->bdev;
1861 if (fs_info->fs_devices->latest_bdev == device->bdev)
1862 fs_info->fs_devices->latest_bdev = next_device->bdev;
1865 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1868 struct btrfs_device *device;
1869 struct btrfs_fs_devices *cur_devices;
1873 mutex_lock(&uuid_mutex);
1875 num_devices = fs_info->fs_devices->num_devices;
1876 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
1877 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1878 WARN_ON(num_devices < 1);
1881 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
1883 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1887 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1892 if (device->is_tgtdev_for_dev_replace) {
1893 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1897 if (device->writeable && fs_info->fs_devices->rw_devices == 1) {
1898 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1902 if (device->writeable) {
1903 mutex_lock(&fs_info->chunk_mutex);
1904 list_del_init(&device->dev_alloc_list);
1905 device->fs_devices->rw_devices--;
1906 mutex_unlock(&fs_info->chunk_mutex);
1909 mutex_unlock(&uuid_mutex);
1910 ret = btrfs_shrink_device(device, 0);
1911 mutex_lock(&uuid_mutex);
1916 * TODO: the superblock still includes this device in its num_devices
1917 * counter although write_all_supers() is not locked out. This
1918 * could give a filesystem state which requires a degraded mount.
1920 ret = btrfs_rm_dev_item(fs_info, device);
1924 device->in_fs_metadata = 0;
1925 btrfs_scrub_cancel_dev(fs_info, device);
1928 * the device list mutex makes sure that we don't change
1929 * the device list while someone else is writing out all
1930 * the device supers. Whoever is writing all supers, should
1931 * lock the device list mutex before getting the number of
1932 * devices in the super block (super_copy). Conversely,
1933 * whoever updates the number of devices in the super block
1934 * (super_copy) should hold the device list mutex.
1937 cur_devices = device->fs_devices;
1938 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1939 list_del_rcu(&device->dev_list);
1941 device->fs_devices->num_devices--;
1942 device->fs_devices->total_devices--;
1944 if (device->missing)
1945 device->fs_devices->missing_devices--;
1947 btrfs_assign_next_active_device(fs_info, device, NULL);
1950 device->fs_devices->open_devices--;
1951 /* remove sysfs entry */
1952 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
1955 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1956 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
1957 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1960 * at this point, the device is zero sized and detached from
1961 * the devices list. All that's left is to zero out the old
1962 * supers and free the device.
1964 if (device->writeable)
1965 btrfs_scratch_superblocks(device->bdev, device->name->str);
1967 btrfs_close_bdev(device);
1968 call_rcu(&device->rcu, free_device);
1970 if (cur_devices->open_devices == 0) {
1971 struct btrfs_fs_devices *fs_devices;
1972 fs_devices = fs_info->fs_devices;
1973 while (fs_devices) {
1974 if (fs_devices->seed == cur_devices) {
1975 fs_devices->seed = cur_devices->seed;
1978 fs_devices = fs_devices->seed;
1980 cur_devices->seed = NULL;
1981 __btrfs_close_devices(cur_devices);
1982 free_fs_devices(cur_devices);
1986 mutex_unlock(&uuid_mutex);
1990 if (device->writeable) {
1991 mutex_lock(&fs_info->chunk_mutex);
1992 list_add(&device->dev_alloc_list,
1993 &fs_info->fs_devices->alloc_list);
1994 device->fs_devices->rw_devices++;
1995 mutex_unlock(&fs_info->chunk_mutex);
2000 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2001 struct btrfs_device *srcdev)
2003 struct btrfs_fs_devices *fs_devices;
2005 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
2008 * in case of fs with no seed, srcdev->fs_devices will point
2009 * to fs_devices of fs_info. However when the dev being replaced is
2010 * a seed dev it will point to the seed's local fs_devices. In short
2011 * srcdev will have its correct fs_devices in both the cases.
2013 fs_devices = srcdev->fs_devices;
2015 list_del_rcu(&srcdev->dev_list);
2016 list_del_rcu(&srcdev->dev_alloc_list);
2017 fs_devices->num_devices--;
2018 if (srcdev->missing)
2019 fs_devices->missing_devices--;
2021 if (srcdev->writeable)
2022 fs_devices->rw_devices--;
2025 fs_devices->open_devices--;
2028 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2029 struct btrfs_device *srcdev)
2031 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2033 if (srcdev->writeable) {
2034 /* zero out the old super if it is writable */
2035 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2038 btrfs_close_bdev(srcdev);
2040 call_rcu(&srcdev->rcu, free_device);
2043 * unless fs_devices is seed fs, num_devices shouldn't go
2046 BUG_ON(!fs_devices->num_devices && !fs_devices->seeding);
2048 /* if this is no devs we rather delete the fs_devices */
2049 if (!fs_devices->num_devices) {
2050 struct btrfs_fs_devices *tmp_fs_devices;
2052 tmp_fs_devices = fs_info->fs_devices;
2053 while (tmp_fs_devices) {
2054 if (tmp_fs_devices->seed == fs_devices) {
2055 tmp_fs_devices->seed = fs_devices->seed;
2058 tmp_fs_devices = tmp_fs_devices->seed;
2060 fs_devices->seed = NULL;
2061 __btrfs_close_devices(fs_devices);
2062 free_fs_devices(fs_devices);
2066 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2067 struct btrfs_device *tgtdev)
2069 mutex_lock(&uuid_mutex);
2071 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2073 btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2076 fs_info->fs_devices->open_devices--;
2078 fs_info->fs_devices->num_devices--;
2080 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2082 list_del_rcu(&tgtdev->dev_list);
2084 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2085 mutex_unlock(&uuid_mutex);
2088 * The update_dev_time() with in btrfs_scratch_superblocks()
2089 * may lead to a call to btrfs_show_devname() which will try
2090 * to hold device_list_mutex. And here this device
2091 * is already out of device list, so we don't have to hold
2092 * the device_list_mutex lock.
2094 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2096 btrfs_close_bdev(tgtdev);
2097 call_rcu(&tgtdev->rcu, free_device);
2100 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2101 const char *device_path,
2102 struct btrfs_device **device)
2105 struct btrfs_super_block *disk_super;
2108 struct block_device *bdev;
2109 struct buffer_head *bh;
2112 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2113 fs_info->bdev_holder, 0, &bdev, &bh);
2116 disk_super = (struct btrfs_super_block *)bh->b_data;
2117 devid = btrfs_stack_device_id(&disk_super->dev_item);
2118 dev_uuid = disk_super->dev_item.uuid;
2119 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2123 blkdev_put(bdev, FMODE_READ);
2127 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2128 const char *device_path,
2129 struct btrfs_device **device)
2132 if (strcmp(device_path, "missing") == 0) {
2133 struct list_head *devices;
2134 struct btrfs_device *tmp;
2136 devices = &fs_info->fs_devices->devices;
2138 * It is safe to read the devices since the volume_mutex
2139 * is held by the caller.
2141 list_for_each_entry(tmp, devices, dev_list) {
2142 if (tmp->in_fs_metadata && !tmp->bdev) {
2149 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2153 return btrfs_find_device_by_path(fs_info, device_path, device);
2158 * Lookup a device given by device id, or the path if the id is 0.
2160 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2161 const char *devpath,
2162 struct btrfs_device **device)
2168 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2172 if (!devpath || !devpath[0])
2175 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2182 * does all the dirty work required for changing file system's UUID.
2184 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2186 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2187 struct btrfs_fs_devices *old_devices;
2188 struct btrfs_fs_devices *seed_devices;
2189 struct btrfs_super_block *disk_super = fs_info->super_copy;
2190 struct btrfs_device *device;
2193 BUG_ON(!mutex_is_locked(&uuid_mutex));
2194 if (!fs_devices->seeding)
2197 seed_devices = alloc_fs_devices(NULL);
2198 if (IS_ERR(seed_devices))
2199 return PTR_ERR(seed_devices);
2201 old_devices = clone_fs_devices(fs_devices);
2202 if (IS_ERR(old_devices)) {
2203 kfree(seed_devices);
2204 return PTR_ERR(old_devices);
2207 list_add(&old_devices->list, &fs_uuids);
2209 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2210 seed_devices->opened = 1;
2211 INIT_LIST_HEAD(&seed_devices->devices);
2212 INIT_LIST_HEAD(&seed_devices->alloc_list);
2213 mutex_init(&seed_devices->device_list_mutex);
2215 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2216 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2218 list_for_each_entry(device, &seed_devices->devices, dev_list)
2219 device->fs_devices = seed_devices;
2221 mutex_lock(&fs_info->chunk_mutex);
2222 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2223 mutex_unlock(&fs_info->chunk_mutex);
2225 fs_devices->seeding = 0;
2226 fs_devices->num_devices = 0;
2227 fs_devices->open_devices = 0;
2228 fs_devices->missing_devices = 0;
2229 fs_devices->rotating = 0;
2230 fs_devices->seed = seed_devices;
2232 generate_random_uuid(fs_devices->fsid);
2233 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2234 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2235 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2237 super_flags = btrfs_super_flags(disk_super) &
2238 ~BTRFS_SUPER_FLAG_SEEDING;
2239 btrfs_set_super_flags(disk_super, super_flags);
2245 * Store the expected generation for seed devices in device items.
2247 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2248 struct btrfs_fs_info *fs_info)
2250 struct btrfs_root *root = fs_info->chunk_root;
2251 struct btrfs_path *path;
2252 struct extent_buffer *leaf;
2253 struct btrfs_dev_item *dev_item;
2254 struct btrfs_device *device;
2255 struct btrfs_key key;
2256 u8 fs_uuid[BTRFS_FSID_SIZE];
2257 u8 dev_uuid[BTRFS_UUID_SIZE];
2261 path = btrfs_alloc_path();
2265 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2267 key.type = BTRFS_DEV_ITEM_KEY;
2270 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2274 leaf = path->nodes[0];
2276 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2277 ret = btrfs_next_leaf(root, path);
2282 leaf = path->nodes[0];
2283 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2284 btrfs_release_path(path);
2288 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2289 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2290 key.type != BTRFS_DEV_ITEM_KEY)
2293 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2294 struct btrfs_dev_item);
2295 devid = btrfs_device_id(leaf, dev_item);
2296 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2298 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2300 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2301 BUG_ON(!device); /* Logic error */
2303 if (device->fs_devices->seeding) {
2304 btrfs_set_device_generation(leaf, dev_item,
2305 device->generation);
2306 btrfs_mark_buffer_dirty(leaf);
2314 btrfs_free_path(path);
2318 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2320 struct btrfs_root *root = fs_info->dev_root;
2321 struct request_queue *q;
2322 struct btrfs_trans_handle *trans;
2323 struct btrfs_device *device;
2324 struct block_device *bdev;
2325 struct list_head *devices;
2326 struct super_block *sb = fs_info->sb;
2327 struct rcu_string *name;
2329 int seeding_dev = 0;
2332 if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2335 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2336 fs_info->bdev_holder);
2338 return PTR_ERR(bdev);
2340 if (fs_info->fs_devices->seeding) {
2342 down_write(&sb->s_umount);
2343 mutex_lock(&uuid_mutex);
2346 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2348 devices = &fs_info->fs_devices->devices;
2350 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2351 list_for_each_entry(device, devices, dev_list) {
2352 if (device->bdev == bdev) {
2355 &fs_info->fs_devices->device_list_mutex);
2359 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2361 device = btrfs_alloc_device(fs_info, NULL, NULL);
2362 if (IS_ERR(device)) {
2363 /* we can safely leave the fs_devices entry around */
2364 ret = PTR_ERR(device);
2368 name = rcu_string_strdup(device_path, GFP_KERNEL);
2374 rcu_assign_pointer(device->name, name);
2376 trans = btrfs_start_transaction(root, 0);
2377 if (IS_ERR(trans)) {
2378 rcu_string_free(device->name);
2380 ret = PTR_ERR(trans);
2384 q = bdev_get_queue(bdev);
2385 if (blk_queue_discard(q))
2386 device->can_discard = 1;
2387 device->writeable = 1;
2388 device->generation = trans->transid;
2389 device->io_width = fs_info->sectorsize;
2390 device->io_align = fs_info->sectorsize;
2391 device->sector_size = fs_info->sectorsize;
2392 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2393 fs_info->sectorsize);
2394 device->disk_total_bytes = device->total_bytes;
2395 device->commit_total_bytes = device->total_bytes;
2396 device->fs_info = fs_info;
2397 device->bdev = bdev;
2398 device->in_fs_metadata = 1;
2399 device->is_tgtdev_for_dev_replace = 0;
2400 device->mode = FMODE_EXCL;
2401 device->dev_stats_valid = 1;
2402 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2405 sb->s_flags &= ~MS_RDONLY;
2406 ret = btrfs_prepare_sprout(fs_info);
2407 BUG_ON(ret); /* -ENOMEM */
2410 device->fs_devices = fs_info->fs_devices;
2412 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2413 mutex_lock(&fs_info->chunk_mutex);
2414 list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2415 list_add(&device->dev_alloc_list,
2416 &fs_info->fs_devices->alloc_list);
2417 fs_info->fs_devices->num_devices++;
2418 fs_info->fs_devices->open_devices++;
2419 fs_info->fs_devices->rw_devices++;
2420 fs_info->fs_devices->total_devices++;
2421 fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2423 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2425 if (!blk_queue_nonrot(q))
2426 fs_info->fs_devices->rotating = 1;
2428 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2429 btrfs_set_super_total_bytes(fs_info->super_copy,
2430 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2432 tmp = btrfs_super_num_devices(fs_info->super_copy);
2433 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2436 * we've got more storage, clear any full flags on the space
2439 btrfs_clear_space_info_full(fs_info);
2441 mutex_unlock(&fs_info->chunk_mutex);
2443 /* Add sysfs device entry */
2444 btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2446 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2449 mutex_lock(&fs_info->chunk_mutex);
2450 ret = init_first_rw_device(trans, fs_info);
2451 mutex_unlock(&fs_info->chunk_mutex);
2453 btrfs_abort_transaction(trans, ret);
2458 ret = btrfs_add_device(trans, fs_info, device);
2460 btrfs_abort_transaction(trans, ret);
2465 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2467 ret = btrfs_finish_sprout(trans, fs_info);
2469 btrfs_abort_transaction(trans, ret);
2473 /* Sprouting would change fsid of the mounted root,
2474 * so rename the fsid on the sysfs
2476 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2478 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2480 "sysfs: failed to create fsid for sprout");
2483 ret = btrfs_commit_transaction(trans);
2486 mutex_unlock(&uuid_mutex);
2487 up_write(&sb->s_umount);
2489 if (ret) /* transaction commit */
2492 ret = btrfs_relocate_sys_chunks(fs_info);
2494 btrfs_handle_fs_error(fs_info, ret,
2495 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2496 trans = btrfs_attach_transaction(root);
2497 if (IS_ERR(trans)) {
2498 if (PTR_ERR(trans) == -ENOENT)
2500 return PTR_ERR(trans);
2502 ret = btrfs_commit_transaction(trans);
2505 /* Update ctime/mtime for libblkid */
2506 update_dev_time(device_path);
2511 sb->s_flags |= MS_RDONLY;
2512 btrfs_end_transaction(trans);
2513 rcu_string_free(device->name);
2514 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2517 blkdev_put(bdev, FMODE_EXCL);
2519 mutex_unlock(&uuid_mutex);
2520 up_write(&sb->s_umount);
2525 int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2526 const char *device_path,
2527 struct btrfs_device *srcdev,
2528 struct btrfs_device **device_out)
2530 struct request_queue *q;
2531 struct btrfs_device *device;
2532 struct block_device *bdev;
2533 struct list_head *devices;
2534 struct rcu_string *name;
2535 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2539 if (fs_info->fs_devices->seeding) {
2540 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2544 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2545 fs_info->bdev_holder);
2547 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2548 return PTR_ERR(bdev);
2551 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2553 devices = &fs_info->fs_devices->devices;
2554 list_for_each_entry(device, devices, dev_list) {
2555 if (device->bdev == bdev) {
2557 "target device is in the filesystem!");
2564 if (i_size_read(bdev->bd_inode) <
2565 btrfs_device_get_total_bytes(srcdev)) {
2567 "target device is smaller than source device!");
2573 device = btrfs_alloc_device(NULL, &devid, NULL);
2574 if (IS_ERR(device)) {
2575 ret = PTR_ERR(device);
2579 name = rcu_string_strdup(device_path, GFP_KERNEL);
2585 rcu_assign_pointer(device->name, name);
2587 q = bdev_get_queue(bdev);
2588 if (blk_queue_discard(q))
2589 device->can_discard = 1;
2590 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2591 device->writeable = 1;
2592 device->generation = 0;
2593 device->io_width = fs_info->sectorsize;
2594 device->io_align = fs_info->sectorsize;
2595 device->sector_size = fs_info->sectorsize;
2596 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2597 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2598 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2599 ASSERT(list_empty(&srcdev->resized_list));
2600 device->commit_total_bytes = srcdev->commit_total_bytes;
2601 device->commit_bytes_used = device->bytes_used;
2602 device->fs_info = fs_info;
2603 device->bdev = bdev;
2604 device->in_fs_metadata = 1;
2605 device->is_tgtdev_for_dev_replace = 1;
2606 device->mode = FMODE_EXCL;
2607 device->dev_stats_valid = 1;
2608 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2609 device->fs_devices = fs_info->fs_devices;
2610 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2611 fs_info->fs_devices->num_devices++;
2612 fs_info->fs_devices->open_devices++;
2613 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2615 *device_out = device;
2619 blkdev_put(bdev, FMODE_EXCL);
2623 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2624 struct btrfs_device *tgtdev)
2626 u32 sectorsize = fs_info->sectorsize;
2628 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2629 tgtdev->io_width = sectorsize;
2630 tgtdev->io_align = sectorsize;
2631 tgtdev->sector_size = sectorsize;
2632 tgtdev->fs_info = fs_info;
2633 tgtdev->in_fs_metadata = 1;
2636 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2637 struct btrfs_device *device)
2640 struct btrfs_path *path;
2641 struct btrfs_root *root = device->fs_info->chunk_root;
2642 struct btrfs_dev_item *dev_item;
2643 struct extent_buffer *leaf;
2644 struct btrfs_key key;
2646 path = btrfs_alloc_path();
2650 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2651 key.type = BTRFS_DEV_ITEM_KEY;
2652 key.offset = device->devid;
2654 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2663 leaf = path->nodes[0];
2664 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2666 btrfs_set_device_id(leaf, dev_item, device->devid);
2667 btrfs_set_device_type(leaf, dev_item, device->type);
2668 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2669 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2670 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2671 btrfs_set_device_total_bytes(leaf, dev_item,
2672 btrfs_device_get_disk_total_bytes(device));
2673 btrfs_set_device_bytes_used(leaf, dev_item,
2674 btrfs_device_get_bytes_used(device));
2675 btrfs_mark_buffer_dirty(leaf);
2678 btrfs_free_path(path);
2682 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2683 struct btrfs_device *device, u64 new_size)
2685 struct btrfs_fs_info *fs_info = device->fs_info;
2686 struct btrfs_super_block *super_copy = fs_info->super_copy;
2687 struct btrfs_fs_devices *fs_devices;
2691 if (!device->writeable)
2694 new_size = round_down(new_size, fs_info->sectorsize);
2696 mutex_lock(&fs_info->chunk_mutex);
2697 old_total = btrfs_super_total_bytes(super_copy);
2698 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2700 if (new_size <= device->total_bytes ||
2701 device->is_tgtdev_for_dev_replace) {
2702 mutex_unlock(&fs_info->chunk_mutex);
2706 fs_devices = fs_info->fs_devices;
2708 btrfs_set_super_total_bytes(super_copy,
2709 round_down(old_total + diff, fs_info->sectorsize));
2710 device->fs_devices->total_rw_bytes += diff;
2712 btrfs_device_set_total_bytes(device, new_size);
2713 btrfs_device_set_disk_total_bytes(device, new_size);
2714 btrfs_clear_space_info_full(device->fs_info);
2715 if (list_empty(&device->resized_list))
2716 list_add_tail(&device->resized_list,
2717 &fs_devices->resized_devices);
2718 mutex_unlock(&fs_info->chunk_mutex);
2720 return btrfs_update_device(trans, device);
2723 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2724 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2726 struct btrfs_root *root = fs_info->chunk_root;
2728 struct btrfs_path *path;
2729 struct btrfs_key key;
2731 path = btrfs_alloc_path();
2735 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2736 key.offset = chunk_offset;
2737 key.type = BTRFS_CHUNK_ITEM_KEY;
2739 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2742 else if (ret > 0) { /* Logic error or corruption */
2743 btrfs_handle_fs_error(fs_info, -ENOENT,
2744 "Failed lookup while freeing chunk.");
2749 ret = btrfs_del_item(trans, root, path);
2751 btrfs_handle_fs_error(fs_info, ret,
2752 "Failed to delete chunk item.");
2754 btrfs_free_path(path);
2758 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2760 struct btrfs_super_block *super_copy = fs_info->super_copy;
2761 struct btrfs_disk_key *disk_key;
2762 struct btrfs_chunk *chunk;
2769 struct btrfs_key key;
2771 mutex_lock(&fs_info->chunk_mutex);
2772 array_size = btrfs_super_sys_array_size(super_copy);
2774 ptr = super_copy->sys_chunk_array;
2777 while (cur < array_size) {
2778 disk_key = (struct btrfs_disk_key *)ptr;
2779 btrfs_disk_key_to_cpu(&key, disk_key);
2781 len = sizeof(*disk_key);
2783 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2784 chunk = (struct btrfs_chunk *)(ptr + len);
2785 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2786 len += btrfs_chunk_item_size(num_stripes);
2791 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2792 key.offset == chunk_offset) {
2793 memmove(ptr, ptr + len, array_size - (cur + len));
2795 btrfs_set_super_sys_array_size(super_copy, array_size);
2801 mutex_unlock(&fs_info->chunk_mutex);
2805 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2806 u64 logical, u64 length)
2808 struct extent_map_tree *em_tree;
2809 struct extent_map *em;
2811 em_tree = &fs_info->mapping_tree.map_tree;
2812 read_lock(&em_tree->lock);
2813 em = lookup_extent_mapping(em_tree, logical, length);
2814 read_unlock(&em_tree->lock);
2817 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2819 return ERR_PTR(-EINVAL);
2822 if (em->start > logical || em->start + em->len < logical) {
2824 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2825 logical, length, em->start, em->start + em->len);
2826 free_extent_map(em);
2827 return ERR_PTR(-EINVAL);
2830 /* callers are responsible for dropping em's ref. */
2834 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2835 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2837 struct extent_map *em;
2838 struct map_lookup *map;
2839 u64 dev_extent_len = 0;
2841 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2843 em = get_chunk_map(fs_info, chunk_offset, 1);
2846 * This is a logic error, but we don't want to just rely on the
2847 * user having built with ASSERT enabled, so if ASSERT doesn't
2848 * do anything we still error out.
2853 map = em->map_lookup;
2854 mutex_lock(&fs_info->chunk_mutex);
2855 check_system_chunk(trans, fs_info, map->type);
2856 mutex_unlock(&fs_info->chunk_mutex);
2859 * Take the device list mutex to prevent races with the final phase of
2860 * a device replace operation that replaces the device object associated
2861 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2863 mutex_lock(&fs_devices->device_list_mutex);
2864 for (i = 0; i < map->num_stripes; i++) {
2865 struct btrfs_device *device = map->stripes[i].dev;
2866 ret = btrfs_free_dev_extent(trans, device,
2867 map->stripes[i].physical,
2870 mutex_unlock(&fs_devices->device_list_mutex);
2871 btrfs_abort_transaction(trans, ret);
2875 if (device->bytes_used > 0) {
2876 mutex_lock(&fs_info->chunk_mutex);
2877 btrfs_device_set_bytes_used(device,
2878 device->bytes_used - dev_extent_len);
2879 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2880 btrfs_clear_space_info_full(fs_info);
2881 mutex_unlock(&fs_info->chunk_mutex);
2884 if (map->stripes[i].dev) {
2885 ret = btrfs_update_device(trans, map->stripes[i].dev);
2887 mutex_unlock(&fs_devices->device_list_mutex);
2888 btrfs_abort_transaction(trans, ret);
2893 mutex_unlock(&fs_devices->device_list_mutex);
2895 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2897 btrfs_abort_transaction(trans, ret);
2901 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2903 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2904 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2906 btrfs_abort_transaction(trans, ret);
2911 ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2913 btrfs_abort_transaction(trans, ret);
2919 free_extent_map(em);
2923 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2925 struct btrfs_root *root = fs_info->chunk_root;
2926 struct btrfs_trans_handle *trans;
2930 * Prevent races with automatic removal of unused block groups.
2931 * After we relocate and before we remove the chunk with offset
2932 * chunk_offset, automatic removal of the block group can kick in,
2933 * resulting in a failure when calling btrfs_remove_chunk() below.
2935 * Make sure to acquire this mutex before doing a tree search (dev
2936 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2937 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2938 * we release the path used to search the chunk/dev tree and before
2939 * the current task acquires this mutex and calls us.
2941 ASSERT(mutex_is_locked(&fs_info->delete_unused_bgs_mutex));
2943 ret = btrfs_can_relocate(fs_info, chunk_offset);
2947 /* step one, relocate all the extents inside this chunk */
2948 btrfs_scrub_pause(fs_info);
2949 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2950 btrfs_scrub_continue(fs_info);
2954 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2956 if (IS_ERR(trans)) {
2957 ret = PTR_ERR(trans);
2958 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2963 * step two, delete the device extents and the
2964 * chunk tree entries
2966 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
2967 btrfs_end_transaction(trans);
2971 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2973 struct btrfs_root *chunk_root = fs_info->chunk_root;
2974 struct btrfs_path *path;
2975 struct extent_buffer *leaf;
2976 struct btrfs_chunk *chunk;
2977 struct btrfs_key key;
2978 struct btrfs_key found_key;
2980 bool retried = false;
2984 path = btrfs_alloc_path();
2989 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2990 key.offset = (u64)-1;
2991 key.type = BTRFS_CHUNK_ITEM_KEY;
2994 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2995 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2997 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3000 BUG_ON(ret == 0); /* Corruption */
3002 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3005 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3011 leaf = path->nodes[0];
3012 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3014 chunk = btrfs_item_ptr(leaf, path->slots[0],
3015 struct btrfs_chunk);
3016 chunk_type = btrfs_chunk_type(leaf, chunk);
3017 btrfs_release_path(path);
3019 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3020 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3026 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3028 if (found_key.offset == 0)
3030 key.offset = found_key.offset - 1;
3033 if (failed && !retried) {
3037 } else if (WARN_ON(failed && retried)) {
3041 btrfs_free_path(path);
3045 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3046 struct btrfs_balance_control *bctl)
3048 struct btrfs_root *root = fs_info->tree_root;
3049 struct btrfs_trans_handle *trans;
3050 struct btrfs_balance_item *item;
3051 struct btrfs_disk_balance_args disk_bargs;
3052 struct btrfs_path *path;
3053 struct extent_buffer *leaf;
3054 struct btrfs_key key;
3057 path = btrfs_alloc_path();
3061 trans = btrfs_start_transaction(root, 0);
3062 if (IS_ERR(trans)) {
3063 btrfs_free_path(path);
3064 return PTR_ERR(trans);
3067 key.objectid = BTRFS_BALANCE_OBJECTID;
3068 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3071 ret = btrfs_insert_empty_item(trans, root, path, &key,
3076 leaf = path->nodes[0];
3077 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3079 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3081 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3082 btrfs_set_balance_data(leaf, item, &disk_bargs);
3083 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3084 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3085 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3086 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3088 btrfs_set_balance_flags(leaf, item, bctl->flags);
3090 btrfs_mark_buffer_dirty(leaf);
3092 btrfs_free_path(path);
3093 err = btrfs_commit_transaction(trans);
3099 static int del_balance_item(struct btrfs_fs_info *fs_info)
3101 struct btrfs_root *root = fs_info->tree_root;
3102 struct btrfs_trans_handle *trans;
3103 struct btrfs_path *path;
3104 struct btrfs_key key;
3107 path = btrfs_alloc_path();
3111 trans = btrfs_start_transaction(root, 0);
3112 if (IS_ERR(trans)) {
3113 btrfs_free_path(path);
3114 return PTR_ERR(trans);
3117 key.objectid = BTRFS_BALANCE_OBJECTID;
3118 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3121 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3129 ret = btrfs_del_item(trans, root, path);
3131 btrfs_free_path(path);
3132 err = btrfs_commit_transaction(trans);
3139 * This is a heuristic used to reduce the number of chunks balanced on
3140 * resume after balance was interrupted.
3142 static void update_balance_args(struct btrfs_balance_control *bctl)
3145 * Turn on soft mode for chunk types that were being converted.
3147 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3148 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3149 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3150 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3151 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3152 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3155 * Turn on usage filter if is not already used. The idea is
3156 * that chunks that we have already balanced should be
3157 * reasonably full. Don't do it for chunks that are being
3158 * converted - that will keep us from relocating unconverted
3159 * (albeit full) chunks.
3161 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3162 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3163 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3164 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3165 bctl->data.usage = 90;
3167 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3168 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3169 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3170 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3171 bctl->sys.usage = 90;
3173 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3174 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3175 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3176 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3177 bctl->meta.usage = 90;
3182 * Should be called with both balance and volume mutexes held to
3183 * serialize other volume operations (add_dev/rm_dev/resize) with
3184 * restriper. Same goes for unset_balance_control.
3186 static void set_balance_control(struct btrfs_balance_control *bctl)
3188 struct btrfs_fs_info *fs_info = bctl->fs_info;
3190 BUG_ON(fs_info->balance_ctl);
3192 spin_lock(&fs_info->balance_lock);
3193 fs_info->balance_ctl = bctl;
3194 spin_unlock(&fs_info->balance_lock);
3197 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3199 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3201 BUG_ON(!fs_info->balance_ctl);
3203 spin_lock(&fs_info->balance_lock);
3204 fs_info->balance_ctl = NULL;
3205 spin_unlock(&fs_info->balance_lock);
3211 * Balance filters. Return 1 if chunk should be filtered out
3212 * (should not be balanced).
3214 static int chunk_profiles_filter(u64 chunk_type,
3215 struct btrfs_balance_args *bargs)
3217 chunk_type = chunk_to_extended(chunk_type) &
3218 BTRFS_EXTENDED_PROFILE_MASK;
3220 if (bargs->profiles & chunk_type)
3226 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3227 struct btrfs_balance_args *bargs)
3229 struct btrfs_block_group_cache *cache;
3231 u64 user_thresh_min;
3232 u64 user_thresh_max;
3235 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3236 chunk_used = btrfs_block_group_used(&cache->item);
3238 if (bargs->usage_min == 0)
3239 user_thresh_min = 0;
3241 user_thresh_min = div_factor_fine(cache->key.offset,
3244 if (bargs->usage_max == 0)
3245 user_thresh_max = 1;
3246 else if (bargs->usage_max > 100)
3247 user_thresh_max = cache->key.offset;
3249 user_thresh_max = div_factor_fine(cache->key.offset,
3252 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3255 btrfs_put_block_group(cache);
3259 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3260 u64 chunk_offset, struct btrfs_balance_args *bargs)
3262 struct btrfs_block_group_cache *cache;
3263 u64 chunk_used, user_thresh;
3266 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3267 chunk_used = btrfs_block_group_used(&cache->item);
3269 if (bargs->usage_min == 0)
3271 else if (bargs->usage > 100)
3272 user_thresh = cache->key.offset;
3274 user_thresh = div_factor_fine(cache->key.offset,
3277 if (chunk_used < user_thresh)
3280 btrfs_put_block_group(cache);
3284 static int chunk_devid_filter(struct extent_buffer *leaf,
3285 struct btrfs_chunk *chunk,
3286 struct btrfs_balance_args *bargs)
3288 struct btrfs_stripe *stripe;
3289 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3292 for (i = 0; i < num_stripes; i++) {
3293 stripe = btrfs_stripe_nr(chunk, i);
3294 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3301 /* [pstart, pend) */
3302 static int chunk_drange_filter(struct extent_buffer *leaf,
3303 struct btrfs_chunk *chunk,
3304 struct btrfs_balance_args *bargs)
3306 struct btrfs_stripe *stripe;
3307 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3313 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3316 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3317 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3318 factor = num_stripes / 2;
3319 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3320 factor = num_stripes - 1;
3321 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3322 factor = num_stripes - 2;
3324 factor = num_stripes;
3327 for (i = 0; i < num_stripes; i++) {
3328 stripe = btrfs_stripe_nr(chunk, i);
3329 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3332 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3333 stripe_length = btrfs_chunk_length(leaf, chunk);
3334 stripe_length = div_u64(stripe_length, factor);
3336 if (stripe_offset < bargs->pend &&
3337 stripe_offset + stripe_length > bargs->pstart)
3344 /* [vstart, vend) */
3345 static int chunk_vrange_filter(struct extent_buffer *leaf,
3346 struct btrfs_chunk *chunk,
3348 struct btrfs_balance_args *bargs)
3350 if (chunk_offset < bargs->vend &&
3351 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3352 /* at least part of the chunk is inside this vrange */
3358 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3359 struct btrfs_chunk *chunk,
3360 struct btrfs_balance_args *bargs)
3362 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3364 if (bargs->stripes_min <= num_stripes
3365 && num_stripes <= bargs->stripes_max)
3371 static int chunk_soft_convert_filter(u64 chunk_type,
3372 struct btrfs_balance_args *bargs)
3374 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3377 chunk_type = chunk_to_extended(chunk_type) &
3378 BTRFS_EXTENDED_PROFILE_MASK;
3380 if (bargs->target == chunk_type)
3386 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3387 struct extent_buffer *leaf,
3388 struct btrfs_chunk *chunk, u64 chunk_offset)
3390 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3391 struct btrfs_balance_args *bargs = NULL;
3392 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3395 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3396 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3400 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3401 bargs = &bctl->data;
3402 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3404 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3405 bargs = &bctl->meta;
3407 /* profiles filter */
3408 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3409 chunk_profiles_filter(chunk_type, bargs)) {
3414 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3415 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3417 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3418 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3423 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3424 chunk_devid_filter(leaf, chunk, bargs)) {
3428 /* drange filter, makes sense only with devid filter */
3429 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3430 chunk_drange_filter(leaf, chunk, bargs)) {
3435 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3436 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3440 /* stripes filter */
3441 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3442 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3446 /* soft profile changing mode */
3447 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3448 chunk_soft_convert_filter(chunk_type, bargs)) {
3453 * limited by count, must be the last filter
3455 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3456 if (bargs->limit == 0)
3460 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3462 * Same logic as the 'limit' filter; the minimum cannot be
3463 * determined here because we do not have the global information
3464 * about the count of all chunks that satisfy the filters.
3466 if (bargs->limit_max == 0)
3475 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3477 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3478 struct btrfs_root *chunk_root = fs_info->chunk_root;
3479 struct btrfs_root *dev_root = fs_info->dev_root;
3480 struct list_head *devices;
3481 struct btrfs_device *device;
3485 struct btrfs_chunk *chunk;
3486 struct btrfs_path *path = NULL;
3487 struct btrfs_key key;
3488 struct btrfs_key found_key;
3489 struct btrfs_trans_handle *trans;
3490 struct extent_buffer *leaf;
3493 int enospc_errors = 0;
3494 bool counting = true;
3495 /* The single value limit and min/max limits use the same bytes in the */
3496 u64 limit_data = bctl->data.limit;
3497 u64 limit_meta = bctl->meta.limit;
3498 u64 limit_sys = bctl->sys.limit;
3502 int chunk_reserved = 0;
3505 /* step one make some room on all the devices */
3506 devices = &fs_info->fs_devices->devices;
3507 list_for_each_entry(device, devices, dev_list) {
3508 old_size = btrfs_device_get_total_bytes(device);
3509 size_to_free = div_factor(old_size, 1);
3510 size_to_free = min_t(u64, size_to_free, SZ_1M);
3511 if (!device->writeable ||
3512 btrfs_device_get_total_bytes(device) -
3513 btrfs_device_get_bytes_used(device) > size_to_free ||
3514 device->is_tgtdev_for_dev_replace)
3517 ret = btrfs_shrink_device(device, old_size - size_to_free);
3521 /* btrfs_shrink_device never returns ret > 0 */
3526 trans = btrfs_start_transaction(dev_root, 0);
3527 if (IS_ERR(trans)) {
3528 ret = PTR_ERR(trans);
3529 btrfs_info_in_rcu(fs_info,
3530 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3531 rcu_str_deref(device->name), ret,
3532 old_size, old_size - size_to_free);
3536 ret = btrfs_grow_device(trans, device, old_size);
3538 btrfs_end_transaction(trans);
3539 /* btrfs_grow_device never returns ret > 0 */
3541 btrfs_info_in_rcu(fs_info,
3542 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3543 rcu_str_deref(device->name), ret,
3544 old_size, old_size - size_to_free);
3548 btrfs_end_transaction(trans);
3551 /* step two, relocate all the chunks */
3552 path = btrfs_alloc_path();
3558 /* zero out stat counters */
3559 spin_lock(&fs_info->balance_lock);
3560 memset(&bctl->stat, 0, sizeof(bctl->stat));
3561 spin_unlock(&fs_info->balance_lock);
3565 * The single value limit and min/max limits use the same bytes
3568 bctl->data.limit = limit_data;
3569 bctl->meta.limit = limit_meta;
3570 bctl->sys.limit = limit_sys;
3572 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3573 key.offset = (u64)-1;
3574 key.type = BTRFS_CHUNK_ITEM_KEY;
3577 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3578 atomic_read(&fs_info->balance_cancel_req)) {
3583 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3584 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3586 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3591 * this shouldn't happen, it means the last relocate
3595 BUG(); /* FIXME break ? */
3597 ret = btrfs_previous_item(chunk_root, path, 0,
3598 BTRFS_CHUNK_ITEM_KEY);
3600 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3605 leaf = path->nodes[0];
3606 slot = path->slots[0];
3607 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3609 if (found_key.objectid != key.objectid) {
3610 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3614 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3615 chunk_type = btrfs_chunk_type(leaf, chunk);
3618 spin_lock(&fs_info->balance_lock);
3619 bctl->stat.considered++;
3620 spin_unlock(&fs_info->balance_lock);
3623 ret = should_balance_chunk(fs_info, leaf, chunk,
3626 btrfs_release_path(path);
3628 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3633 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3634 spin_lock(&fs_info->balance_lock);
3635 bctl->stat.expected++;
3636 spin_unlock(&fs_info->balance_lock);
3638 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3640 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3642 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3649 * Apply limit_min filter, no need to check if the LIMITS
3650 * filter is used, limit_min is 0 by default
3652 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3653 count_data < bctl->data.limit_min)
3654 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3655 count_meta < bctl->meta.limit_min)
3656 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3657 count_sys < bctl->sys.limit_min)) {
3658 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3662 ASSERT(fs_info->data_sinfo);
3663 spin_lock(&fs_info->data_sinfo->lock);
3664 bytes_used = fs_info->data_sinfo->bytes_used;
3665 spin_unlock(&fs_info->data_sinfo->lock);
3667 if ((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3668 !chunk_reserved && !bytes_used) {
3669 trans = btrfs_start_transaction(chunk_root, 0);
3670 if (IS_ERR(trans)) {
3671 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3672 ret = PTR_ERR(trans);
3676 ret = btrfs_force_chunk_alloc(trans, fs_info,
3677 BTRFS_BLOCK_GROUP_DATA);
3678 btrfs_end_transaction(trans);
3680 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3686 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3687 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3688 if (ret && ret != -ENOSPC)
3690 if (ret == -ENOSPC) {
3693 spin_lock(&fs_info->balance_lock);
3694 bctl->stat.completed++;
3695 spin_unlock(&fs_info->balance_lock);
3698 if (found_key.offset == 0)
3700 key.offset = found_key.offset - 1;
3704 btrfs_release_path(path);
3709 btrfs_free_path(path);
3710 if (enospc_errors) {
3711 btrfs_info(fs_info, "%d enospc errors during balance",
3721 * alloc_profile_is_valid - see if a given profile is valid and reduced
3722 * @flags: profile to validate
3723 * @extended: if true @flags is treated as an extended profile
3725 static int alloc_profile_is_valid(u64 flags, int extended)
3727 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3728 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3730 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3732 /* 1) check that all other bits are zeroed */
3736 /* 2) see if profile is reduced */
3738 return !extended; /* "0" is valid for usual profiles */
3740 /* true if exactly one bit set */
3741 return (flags & (flags - 1)) == 0;
3744 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3746 /* cancel requested || normal exit path */
3747 return atomic_read(&fs_info->balance_cancel_req) ||
3748 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3749 atomic_read(&fs_info->balance_cancel_req) == 0);
3752 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3756 unset_balance_control(fs_info);
3757 ret = del_balance_item(fs_info);
3759 btrfs_handle_fs_error(fs_info, ret, NULL);
3761 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3764 /* Non-zero return value signifies invalidity */
3765 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3768 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3769 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3770 (bctl_arg->target & ~allowed)));
3774 * Should be called with both balance and volume mutexes held
3776 int btrfs_balance(struct btrfs_balance_control *bctl,
3777 struct btrfs_ioctl_balance_args *bargs)
3779 struct btrfs_fs_info *fs_info = bctl->fs_info;
3780 u64 meta_target, data_target;
3787 if (btrfs_fs_closing(fs_info) ||
3788 atomic_read(&fs_info->balance_pause_req) ||
3789 atomic_read(&fs_info->balance_cancel_req)) {
3794 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3795 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3799 * In case of mixed groups both data and meta should be picked,
3800 * and identical options should be given for both of them.
3802 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3803 if (mixed && (bctl->flags & allowed)) {
3804 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3805 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3806 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3808 "with mixed groups data and metadata balance options must be the same");
3814 num_devices = fs_info->fs_devices->num_devices;
3815 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
3816 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3817 BUG_ON(num_devices < 1);
3820 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
3821 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3822 if (num_devices > 1)
3823 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3824 if (num_devices > 2)
3825 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3826 if (num_devices > 3)
3827 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3828 BTRFS_BLOCK_GROUP_RAID6);
3829 if (validate_convert_profile(&bctl->data, allowed)) {
3831 "unable to start balance with target data profile %llu",
3836 if (validate_convert_profile(&bctl->meta, allowed)) {
3838 "unable to start balance with target metadata profile %llu",
3843 if (validate_convert_profile(&bctl->sys, allowed)) {
3845 "unable to start balance with target system profile %llu",
3851 /* allow to reduce meta or sys integrity only if force set */
3852 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3853 BTRFS_BLOCK_GROUP_RAID10 |
3854 BTRFS_BLOCK_GROUP_RAID5 |
3855 BTRFS_BLOCK_GROUP_RAID6;
3857 seq = read_seqbegin(&fs_info->profiles_lock);
3859 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3860 (fs_info->avail_system_alloc_bits & allowed) &&
3861 !(bctl->sys.target & allowed)) ||
3862 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3863 (fs_info->avail_metadata_alloc_bits & allowed) &&
3864 !(bctl->meta.target & allowed))) {
3865 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3867 "force reducing metadata integrity");
3870 "balance will reduce metadata integrity, use force if you want this");
3875 } while (read_seqretry(&fs_info->profiles_lock, seq));
3877 /* if we're not converting, the target field is uninitialized */
3878 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3879 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3880 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3881 bctl->data.target : fs_info->avail_data_alloc_bits;
3882 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3883 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3885 "metadata profile 0x%llx has lower redundancy than data profile 0x%llx",
3886 meta_target, data_target);
3889 ret = insert_balance_item(fs_info, bctl);
3890 if (ret && ret != -EEXIST)
3893 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3894 BUG_ON(ret == -EEXIST);
3895 set_balance_control(bctl);
3897 BUG_ON(ret != -EEXIST);
3898 spin_lock(&fs_info->balance_lock);
3899 update_balance_args(bctl);
3900 spin_unlock(&fs_info->balance_lock);
3903 atomic_inc(&fs_info->balance_running);
3904 mutex_unlock(&fs_info->balance_mutex);
3906 ret = __btrfs_balance(fs_info);
3908 mutex_lock(&fs_info->balance_mutex);
3909 atomic_dec(&fs_info->balance_running);
3912 memset(bargs, 0, sizeof(*bargs));
3913 update_ioctl_balance_args(fs_info, 0, bargs);
3916 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3917 balance_need_close(fs_info)) {
3918 __cancel_balance(fs_info);
3921 wake_up(&fs_info->balance_wait_q);
3925 if (bctl->flags & BTRFS_BALANCE_RESUME)
3926 __cancel_balance(fs_info);
3929 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3934 static int balance_kthread(void *data)
3936 struct btrfs_fs_info *fs_info = data;
3939 mutex_lock(&fs_info->volume_mutex);
3940 mutex_lock(&fs_info->balance_mutex);
3942 if (fs_info->balance_ctl) {
3943 btrfs_info(fs_info, "continuing balance");
3944 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3947 mutex_unlock(&fs_info->balance_mutex);
3948 mutex_unlock(&fs_info->volume_mutex);
3953 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3955 struct task_struct *tsk;
3957 spin_lock(&fs_info->balance_lock);
3958 if (!fs_info->balance_ctl) {
3959 spin_unlock(&fs_info->balance_lock);
3962 spin_unlock(&fs_info->balance_lock);
3964 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
3965 btrfs_info(fs_info, "force skipping balance");
3970 * A ro->rw remount sequence should continue with the paused balance
3971 * regardless of who pauses it, system or the user as of now, so set
3974 spin_lock(&fs_info->balance_lock);
3975 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
3976 spin_unlock(&fs_info->balance_lock);
3978 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3979 return PTR_ERR_OR_ZERO(tsk);
3982 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3984 struct btrfs_balance_control *bctl;
3985 struct btrfs_balance_item *item;
3986 struct btrfs_disk_balance_args disk_bargs;
3987 struct btrfs_path *path;
3988 struct extent_buffer *leaf;
3989 struct btrfs_key key;
3992 path = btrfs_alloc_path();
3996 key.objectid = BTRFS_BALANCE_OBJECTID;
3997 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4000 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4003 if (ret > 0) { /* ret = -ENOENT; */
4008 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4014 leaf = path->nodes[0];
4015 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4017 bctl->fs_info = fs_info;
4018 bctl->flags = btrfs_balance_flags(leaf, item);
4019 bctl->flags |= BTRFS_BALANCE_RESUME;
4021 btrfs_balance_data(leaf, item, &disk_bargs);
4022 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4023 btrfs_balance_meta(leaf, item, &disk_bargs);
4024 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4025 btrfs_balance_sys(leaf, item, &disk_bargs);
4026 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4028 WARN_ON(test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4030 mutex_lock(&fs_info->volume_mutex);
4031 mutex_lock(&fs_info->balance_mutex);
4033 set_balance_control(bctl);
4035 mutex_unlock(&fs_info->balance_mutex);
4036 mutex_unlock(&fs_info->volume_mutex);
4038 btrfs_free_path(path);
4042 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4046 mutex_lock(&fs_info->balance_mutex);
4047 if (!fs_info->balance_ctl) {
4048 mutex_unlock(&fs_info->balance_mutex);
4052 if (atomic_read(&fs_info->balance_running)) {
4053 atomic_inc(&fs_info->balance_pause_req);
4054 mutex_unlock(&fs_info->balance_mutex);
4056 wait_event(fs_info->balance_wait_q,
4057 atomic_read(&fs_info->balance_running) == 0);
4059 mutex_lock(&fs_info->balance_mutex);
4060 /* we are good with balance_ctl ripped off from under us */
4061 BUG_ON(atomic_read(&fs_info->balance_running));
4062 atomic_dec(&fs_info->balance_pause_req);
4067 mutex_unlock(&fs_info->balance_mutex);
4071 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4073 if (sb_rdonly(fs_info->sb))
4076 mutex_lock(&fs_info->balance_mutex);
4077 if (!fs_info->balance_ctl) {
4078 mutex_unlock(&fs_info->balance_mutex);
4082 atomic_inc(&fs_info->balance_cancel_req);
4084 * if we are running just wait and return, balance item is
4085 * deleted in btrfs_balance in this case
4087 if (atomic_read(&fs_info->balance_running)) {
4088 mutex_unlock(&fs_info->balance_mutex);
4089 wait_event(fs_info->balance_wait_q,
4090 atomic_read(&fs_info->balance_running) == 0);
4091 mutex_lock(&fs_info->balance_mutex);
4093 /* __cancel_balance needs volume_mutex */
4094 mutex_unlock(&fs_info->balance_mutex);
4095 mutex_lock(&fs_info->volume_mutex);
4096 mutex_lock(&fs_info->balance_mutex);
4098 if (fs_info->balance_ctl)
4099 __cancel_balance(fs_info);
4101 mutex_unlock(&fs_info->volume_mutex);
4104 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
4105 atomic_dec(&fs_info->balance_cancel_req);
4106 mutex_unlock(&fs_info->balance_mutex);
4110 static int btrfs_uuid_scan_kthread(void *data)
4112 struct btrfs_fs_info *fs_info = data;
4113 struct btrfs_root *root = fs_info->tree_root;
4114 struct btrfs_key key;
4115 struct btrfs_path *path = NULL;
4117 struct extent_buffer *eb;
4119 struct btrfs_root_item root_item;
4121 struct btrfs_trans_handle *trans = NULL;
4123 path = btrfs_alloc_path();
4130 key.type = BTRFS_ROOT_ITEM_KEY;
4134 ret = btrfs_search_forward(root, &key, path, 0);
4141 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4142 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4143 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4144 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4147 eb = path->nodes[0];
4148 slot = path->slots[0];
4149 item_size = btrfs_item_size_nr(eb, slot);
4150 if (item_size < sizeof(root_item))
4153 read_extent_buffer(eb, &root_item,
4154 btrfs_item_ptr_offset(eb, slot),
4155 (int)sizeof(root_item));
4156 if (btrfs_root_refs(&root_item) == 0)
4159 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4160 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4164 btrfs_release_path(path);
4166 * 1 - subvol uuid item
4167 * 1 - received_subvol uuid item
4169 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4170 if (IS_ERR(trans)) {
4171 ret = PTR_ERR(trans);
4179 btrfs_release_path(path);
4180 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4181 ret = btrfs_uuid_tree_add(trans, fs_info,
4183 BTRFS_UUID_KEY_SUBVOL,
4186 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4192 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4193 ret = btrfs_uuid_tree_add(trans, fs_info,
4194 root_item.received_uuid,
4195 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4198 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4205 btrfs_release_path(path);
4207 ret = btrfs_end_transaction(trans);
4213 if (key.offset < (u64)-1) {
4215 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4217 key.type = BTRFS_ROOT_ITEM_KEY;
4218 } else if (key.objectid < (u64)-1) {
4220 key.type = BTRFS_ROOT_ITEM_KEY;
4229 btrfs_free_path(path);
4230 if (trans && !IS_ERR(trans))
4231 btrfs_end_transaction(trans);
4233 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4235 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4236 up(&fs_info->uuid_tree_rescan_sem);
4241 * Callback for btrfs_uuid_tree_iterate().
4243 * 0 check succeeded, the entry is not outdated.
4244 * < 0 if an error occurred.
4245 * > 0 if the check failed, which means the caller shall remove the entry.
4247 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4248 u8 *uuid, u8 type, u64 subid)
4250 struct btrfs_key key;
4252 struct btrfs_root *subvol_root;
4254 if (type != BTRFS_UUID_KEY_SUBVOL &&
4255 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4258 key.objectid = subid;
4259 key.type = BTRFS_ROOT_ITEM_KEY;
4260 key.offset = (u64)-1;
4261 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4262 if (IS_ERR(subvol_root)) {
4263 ret = PTR_ERR(subvol_root);
4270 case BTRFS_UUID_KEY_SUBVOL:
4271 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4274 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4275 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4285 static int btrfs_uuid_rescan_kthread(void *data)
4287 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4291 * 1st step is to iterate through the existing UUID tree and
4292 * to delete all entries that contain outdated data.
4293 * 2nd step is to add all missing entries to the UUID tree.
4295 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4297 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4298 up(&fs_info->uuid_tree_rescan_sem);
4301 return btrfs_uuid_scan_kthread(data);
4304 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4306 struct btrfs_trans_handle *trans;
4307 struct btrfs_root *tree_root = fs_info->tree_root;
4308 struct btrfs_root *uuid_root;
4309 struct task_struct *task;
4316 trans = btrfs_start_transaction(tree_root, 2);
4318 return PTR_ERR(trans);
4320 uuid_root = btrfs_create_tree(trans, fs_info,
4321 BTRFS_UUID_TREE_OBJECTID);
4322 if (IS_ERR(uuid_root)) {
4323 ret = PTR_ERR(uuid_root);
4324 btrfs_abort_transaction(trans, ret);
4325 btrfs_end_transaction(trans);
4329 fs_info->uuid_root = uuid_root;
4331 ret = btrfs_commit_transaction(trans);
4335 down(&fs_info->uuid_tree_rescan_sem);
4336 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4338 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4339 btrfs_warn(fs_info, "failed to start uuid_scan task");
4340 up(&fs_info->uuid_tree_rescan_sem);
4341 return PTR_ERR(task);
4347 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4349 struct task_struct *task;
4351 down(&fs_info->uuid_tree_rescan_sem);
4352 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4354 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4355 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4356 up(&fs_info->uuid_tree_rescan_sem);
4357 return PTR_ERR(task);
4364 * shrinking a device means finding all of the device extents past
4365 * the new size, and then following the back refs to the chunks.
4366 * The chunk relocation code actually frees the device extent
4368 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4370 struct btrfs_fs_info *fs_info = device->fs_info;
4371 struct btrfs_root *root = fs_info->dev_root;
4372 struct btrfs_trans_handle *trans;
4373 struct btrfs_dev_extent *dev_extent = NULL;
4374 struct btrfs_path *path;
4380 bool retried = false;
4381 bool checked_pending_chunks = false;
4382 struct extent_buffer *l;
4383 struct btrfs_key key;
4384 struct btrfs_super_block *super_copy = fs_info->super_copy;
4385 u64 old_total = btrfs_super_total_bytes(super_copy);
4386 u64 old_size = btrfs_device_get_total_bytes(device);
4389 new_size = round_down(new_size, fs_info->sectorsize);
4390 diff = round_down(old_size - new_size, fs_info->sectorsize);
4392 if (device->is_tgtdev_for_dev_replace)
4395 path = btrfs_alloc_path();
4399 path->reada = READA_FORWARD;
4401 mutex_lock(&fs_info->chunk_mutex);
4403 btrfs_device_set_total_bytes(device, new_size);
4404 if (device->writeable) {
4405 device->fs_devices->total_rw_bytes -= diff;
4406 atomic64_sub(diff, &fs_info->free_chunk_space);
4408 mutex_unlock(&fs_info->chunk_mutex);
4411 key.objectid = device->devid;
4412 key.offset = (u64)-1;
4413 key.type = BTRFS_DEV_EXTENT_KEY;
4416 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4417 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4419 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4423 ret = btrfs_previous_item(root, path, 0, key.type);
4425 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4430 btrfs_release_path(path);
4435 slot = path->slots[0];
4436 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4438 if (key.objectid != device->devid) {
4439 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4440 btrfs_release_path(path);
4444 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4445 length = btrfs_dev_extent_length(l, dev_extent);
4447 if (key.offset + length <= new_size) {
4448 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4449 btrfs_release_path(path);
4453 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4454 btrfs_release_path(path);
4456 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4457 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4458 if (ret && ret != -ENOSPC)
4462 } while (key.offset-- > 0);
4464 if (failed && !retried) {
4468 } else if (failed && retried) {
4473 /* Shrinking succeeded, else we would be at "done". */
4474 trans = btrfs_start_transaction(root, 0);
4475 if (IS_ERR(trans)) {
4476 ret = PTR_ERR(trans);
4480 mutex_lock(&fs_info->chunk_mutex);
4483 * We checked in the above loop all device extents that were already in
4484 * the device tree. However before we have updated the device's
4485 * total_bytes to the new size, we might have had chunk allocations that
4486 * have not complete yet (new block groups attached to transaction
4487 * handles), and therefore their device extents were not yet in the
4488 * device tree and we missed them in the loop above. So if we have any
4489 * pending chunk using a device extent that overlaps the device range
4490 * that we can not use anymore, commit the current transaction and
4491 * repeat the search on the device tree - this way we guarantee we will
4492 * not have chunks using device extents that end beyond 'new_size'.
4494 if (!checked_pending_chunks) {
4495 u64 start = new_size;
4496 u64 len = old_size - new_size;
4498 if (contains_pending_extent(trans->transaction, device,
4500 mutex_unlock(&fs_info->chunk_mutex);
4501 checked_pending_chunks = true;
4504 ret = btrfs_commit_transaction(trans);
4511 btrfs_device_set_disk_total_bytes(device, new_size);
4512 if (list_empty(&device->resized_list))
4513 list_add_tail(&device->resized_list,
4514 &fs_info->fs_devices->resized_devices);
4516 WARN_ON(diff > old_total);
4517 btrfs_set_super_total_bytes(super_copy,
4518 round_down(old_total - diff, fs_info->sectorsize));
4519 mutex_unlock(&fs_info->chunk_mutex);
4521 /* Now btrfs_update_device() will change the on-disk size. */
4522 ret = btrfs_update_device(trans, device);
4524 btrfs_abort_transaction(trans, ret);
4525 btrfs_end_transaction(trans);
4527 ret = btrfs_commit_transaction(trans);
4530 btrfs_free_path(path);
4532 mutex_lock(&fs_info->chunk_mutex);
4533 btrfs_device_set_total_bytes(device, old_size);
4534 if (device->writeable)
4535 device->fs_devices->total_rw_bytes += diff;
4536 atomic64_add(diff, &fs_info->free_chunk_space);
4537 mutex_unlock(&fs_info->chunk_mutex);
4542 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4543 struct btrfs_key *key,
4544 struct btrfs_chunk *chunk, int item_size)
4546 struct btrfs_super_block *super_copy = fs_info->super_copy;
4547 struct btrfs_disk_key disk_key;
4551 mutex_lock(&fs_info->chunk_mutex);
4552 array_size = btrfs_super_sys_array_size(super_copy);
4553 if (array_size + item_size + sizeof(disk_key)
4554 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4555 mutex_unlock(&fs_info->chunk_mutex);
4559 ptr = super_copy->sys_chunk_array + array_size;
4560 btrfs_cpu_key_to_disk(&disk_key, key);
4561 memcpy(ptr, &disk_key, sizeof(disk_key));
4562 ptr += sizeof(disk_key);
4563 memcpy(ptr, chunk, item_size);
4564 item_size += sizeof(disk_key);
4565 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4566 mutex_unlock(&fs_info->chunk_mutex);
4572 * sort the devices in descending order by max_avail, total_avail
4574 static int btrfs_cmp_device_info(const void *a, const void *b)
4576 const struct btrfs_device_info *di_a = a;
4577 const struct btrfs_device_info *di_b = b;
4579 if (di_a->max_avail > di_b->max_avail)
4581 if (di_a->max_avail < di_b->max_avail)
4583 if (di_a->total_avail > di_b->total_avail)
4585 if (di_a->total_avail < di_b->total_avail)
4590 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4592 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4595 btrfs_set_fs_incompat(info, RAID56);
4598 #define BTRFS_MAX_DEVS(r) ((BTRFS_MAX_ITEM_SIZE(r->fs_info) \
4599 - sizeof(struct btrfs_chunk)) \
4600 / sizeof(struct btrfs_stripe) + 1)
4602 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4603 - 2 * sizeof(struct btrfs_disk_key) \
4604 - 2 * sizeof(struct btrfs_chunk)) \
4605 / sizeof(struct btrfs_stripe) + 1)
4607 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4608 u64 start, u64 type)
4610 struct btrfs_fs_info *info = trans->fs_info;
4611 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4612 struct btrfs_device *device;
4613 struct map_lookup *map = NULL;
4614 struct extent_map_tree *em_tree;
4615 struct extent_map *em;
4616 struct btrfs_device_info *devices_info = NULL;
4618 int num_stripes; /* total number of stripes to allocate */
4619 int data_stripes; /* number of stripes that count for
4621 int sub_stripes; /* sub_stripes info for map */
4622 int dev_stripes; /* stripes per dev */
4623 int devs_max; /* max devs to use */
4624 int devs_min; /* min devs needed */
4625 int devs_increment; /* ndevs has to be a multiple of this */
4626 int ncopies; /* how many copies to data has */
4628 u64 max_stripe_size;
4637 BUG_ON(!alloc_profile_is_valid(type, 0));
4639 if (list_empty(&fs_devices->alloc_list))
4642 index = __get_raid_index(type);
4644 sub_stripes = btrfs_raid_array[index].sub_stripes;
4645 dev_stripes = btrfs_raid_array[index].dev_stripes;
4646 devs_max = btrfs_raid_array[index].devs_max;
4647 devs_min = btrfs_raid_array[index].devs_min;
4648 devs_increment = btrfs_raid_array[index].devs_increment;
4649 ncopies = btrfs_raid_array[index].ncopies;
4651 if (type & BTRFS_BLOCK_GROUP_DATA) {
4652 max_stripe_size = SZ_1G;
4653 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4655 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4656 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4657 /* for larger filesystems, use larger metadata chunks */
4658 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4659 max_stripe_size = SZ_1G;
4661 max_stripe_size = SZ_256M;
4662 max_chunk_size = max_stripe_size;
4664 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4665 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4666 max_stripe_size = SZ_32M;
4667 max_chunk_size = 2 * max_stripe_size;
4669 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4671 btrfs_err(info, "invalid chunk type 0x%llx requested",
4676 /* we don't want a chunk larger than 10% of writeable space */
4677 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4680 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4686 * in the first pass through the devices list, we gather information
4687 * about the available holes on each device.
4690 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4694 if (!device->writeable) {
4696 "BTRFS: read-only device in alloc_list\n");
4700 if (!device->in_fs_metadata ||
4701 device->is_tgtdev_for_dev_replace)
4704 if (device->total_bytes > device->bytes_used)
4705 total_avail = device->total_bytes - device->bytes_used;
4709 /* If there is no space on this device, skip it. */
4710 if (total_avail == 0)
4713 ret = find_free_dev_extent(trans, device,
4714 max_stripe_size * dev_stripes,
4715 &dev_offset, &max_avail);
4716 if (ret && ret != -ENOSPC)
4720 max_avail = max_stripe_size * dev_stripes;
4722 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4725 if (ndevs == fs_devices->rw_devices) {
4726 WARN(1, "%s: found more than %llu devices\n",
4727 __func__, fs_devices->rw_devices);
4730 devices_info[ndevs].dev_offset = dev_offset;
4731 devices_info[ndevs].max_avail = max_avail;
4732 devices_info[ndevs].total_avail = total_avail;
4733 devices_info[ndevs].dev = device;
4738 * now sort the devices by hole size / available space
4740 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4741 btrfs_cmp_device_info, NULL);
4743 /* round down to number of usable stripes */
4744 ndevs = round_down(ndevs, devs_increment);
4746 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4751 ndevs = min(ndevs, devs_max);
4754 * The primary goal is to maximize the number of stripes, so use as
4755 * many devices as possible, even if the stripes are not maximum sized.
4757 * The DUP profile stores more than one stripe per device, the
4758 * max_avail is the total size so we have to adjust.
4760 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4761 num_stripes = ndevs * dev_stripes;
4764 * this will have to be fixed for RAID1 and RAID10 over
4767 data_stripes = num_stripes / ncopies;
4769 if (type & BTRFS_BLOCK_GROUP_RAID5)
4770 data_stripes = num_stripes - 1;
4772 if (type & BTRFS_BLOCK_GROUP_RAID6)
4773 data_stripes = num_stripes - 2;
4776 * Use the number of data stripes to figure out how big this chunk
4777 * is really going to be in terms of logical address space,
4778 * and compare that answer with the max chunk size
4780 if (stripe_size * data_stripes > max_chunk_size) {
4781 u64 mask = (1ULL << 24) - 1;
4783 stripe_size = div_u64(max_chunk_size, data_stripes);
4785 /* bump the answer up to a 16MB boundary */
4786 stripe_size = (stripe_size + mask) & ~mask;
4788 /* but don't go higher than the limits we found
4789 * while searching for free extents
4791 if (stripe_size > devices_info[ndevs-1].max_avail)
4792 stripe_size = devices_info[ndevs-1].max_avail;
4795 /* align to BTRFS_STRIPE_LEN */
4796 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4798 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4803 map->num_stripes = num_stripes;
4805 for (i = 0; i < ndevs; ++i) {
4806 for (j = 0; j < dev_stripes; ++j) {
4807 int s = i * dev_stripes + j;
4808 map->stripes[s].dev = devices_info[i].dev;
4809 map->stripes[s].physical = devices_info[i].dev_offset +
4813 map->stripe_len = BTRFS_STRIPE_LEN;
4814 map->io_align = BTRFS_STRIPE_LEN;
4815 map->io_width = BTRFS_STRIPE_LEN;
4817 map->sub_stripes = sub_stripes;
4819 num_bytes = stripe_size * data_stripes;
4821 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4823 em = alloc_extent_map();
4829 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4830 em->map_lookup = map;
4832 em->len = num_bytes;
4833 em->block_start = 0;
4834 em->block_len = em->len;
4835 em->orig_block_len = stripe_size;
4837 em_tree = &info->mapping_tree.map_tree;
4838 write_lock(&em_tree->lock);
4839 ret = add_extent_mapping(em_tree, em, 0);
4841 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4842 refcount_inc(&em->refs);
4844 write_unlock(&em_tree->lock);
4846 free_extent_map(em);
4850 ret = btrfs_make_block_group(trans, info, 0, type, start, num_bytes);
4852 goto error_del_extent;
4854 for (i = 0; i < map->num_stripes; i++) {
4855 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4856 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4857 map->stripes[i].dev->has_pending_chunks = true;
4860 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4862 free_extent_map(em);
4863 check_raid56_incompat_flag(info, type);
4865 kfree(devices_info);
4869 write_lock(&em_tree->lock);
4870 remove_extent_mapping(em_tree, em);
4871 write_unlock(&em_tree->lock);
4873 /* One for our allocation */
4874 free_extent_map(em);
4875 /* One for the tree reference */
4876 free_extent_map(em);
4877 /* One for the pending_chunks list reference */
4878 free_extent_map(em);
4880 kfree(devices_info);
4884 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4885 struct btrfs_fs_info *fs_info,
4886 u64 chunk_offset, u64 chunk_size)
4888 struct btrfs_root *extent_root = fs_info->extent_root;
4889 struct btrfs_root *chunk_root = fs_info->chunk_root;
4890 struct btrfs_key key;
4891 struct btrfs_device *device;
4892 struct btrfs_chunk *chunk;
4893 struct btrfs_stripe *stripe;
4894 struct extent_map *em;
4895 struct map_lookup *map;
4902 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4906 map = em->map_lookup;
4907 item_size = btrfs_chunk_item_size(map->num_stripes);
4908 stripe_size = em->orig_block_len;
4910 chunk = kzalloc(item_size, GFP_NOFS);
4917 * Take the device list mutex to prevent races with the final phase of
4918 * a device replace operation that replaces the device object associated
4919 * with the map's stripes, because the device object's id can change
4920 * at any time during that final phase of the device replace operation
4921 * (dev-replace.c:btrfs_dev_replace_finishing()).
4923 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4924 for (i = 0; i < map->num_stripes; i++) {
4925 device = map->stripes[i].dev;
4926 dev_offset = map->stripes[i].physical;
4928 ret = btrfs_update_device(trans, device);
4931 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
4932 dev_offset, stripe_size);
4937 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4941 stripe = &chunk->stripe;
4942 for (i = 0; i < map->num_stripes; i++) {
4943 device = map->stripes[i].dev;
4944 dev_offset = map->stripes[i].physical;
4946 btrfs_set_stack_stripe_devid(stripe, device->devid);
4947 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4948 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4951 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4953 btrfs_set_stack_chunk_length(chunk, chunk_size);
4954 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4955 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4956 btrfs_set_stack_chunk_type(chunk, map->type);
4957 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4958 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4959 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4960 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
4961 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4963 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4964 key.type = BTRFS_CHUNK_ITEM_KEY;
4965 key.offset = chunk_offset;
4967 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4968 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4970 * TODO: Cleanup of inserted chunk root in case of
4973 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
4978 free_extent_map(em);
4983 * Chunk allocation falls into two parts. The first part does works
4984 * that make the new allocated chunk useable, but not do any operation
4985 * that modifies the chunk tree. The second part does the works that
4986 * require modifying the chunk tree. This division is important for the
4987 * bootstrap process of adding storage to a seed btrfs.
4989 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4990 struct btrfs_fs_info *fs_info, u64 type)
4994 ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
4995 chunk_offset = find_next_chunk(fs_info);
4996 return __btrfs_alloc_chunk(trans, chunk_offset, type);
4999 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5000 struct btrfs_fs_info *fs_info)
5003 u64 sys_chunk_offset;
5007 chunk_offset = find_next_chunk(fs_info);
5008 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5009 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5013 sys_chunk_offset = find_next_chunk(fs_info);
5014 alloc_profile = btrfs_system_alloc_profile(fs_info);
5015 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5019 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5023 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5024 BTRFS_BLOCK_GROUP_RAID10 |
5025 BTRFS_BLOCK_GROUP_RAID5)) {
5027 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5036 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5038 struct extent_map *em;
5039 struct map_lookup *map;
5044 em = get_chunk_map(fs_info, chunk_offset, 1);
5048 map = em->map_lookup;
5049 for (i = 0; i < map->num_stripes; i++) {
5050 if (map->stripes[i].dev->missing) {
5055 if (!map->stripes[i].dev->writeable) {
5062 * If the number of missing devices is larger than max errors,
5063 * we can not write the data into that chunk successfully, so
5066 if (miss_ndevs > btrfs_chunk_max_errors(map))
5069 free_extent_map(em);
5073 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5075 extent_map_tree_init(&tree->map_tree);
5078 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5080 struct extent_map *em;
5083 write_lock(&tree->map_tree.lock);
5084 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5086 remove_extent_mapping(&tree->map_tree, em);
5087 write_unlock(&tree->map_tree.lock);
5091 free_extent_map(em);
5092 /* once for the tree */
5093 free_extent_map(em);
5097 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5099 struct extent_map *em;
5100 struct map_lookup *map;
5103 em = get_chunk_map(fs_info, logical, len);
5106 * We could return errors for these cases, but that could get
5107 * ugly and we'd probably do the same thing which is just not do
5108 * anything else and exit, so return 1 so the callers don't try
5109 * to use other copies.
5113 map = em->map_lookup;
5114 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5115 ret = map->num_stripes;
5116 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5117 ret = map->sub_stripes;
5118 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5120 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5122 * There could be two corrupted data stripes, we need
5123 * to loop retry in order to rebuild the correct data.
5125 * Fail a stripe at a time on every retry except the
5126 * stripe under reconstruction.
5128 ret = map->num_stripes;
5131 free_extent_map(em);
5133 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
5134 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5135 fs_info->dev_replace.tgtdev)
5137 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
5142 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5145 struct extent_map *em;
5146 struct map_lookup *map;
5147 unsigned long len = fs_info->sectorsize;
5149 em = get_chunk_map(fs_info, logical, len);
5151 if (!WARN_ON(IS_ERR(em))) {
5152 map = em->map_lookup;
5153 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5154 len = map->stripe_len * nr_data_stripes(map);
5155 free_extent_map(em);
5160 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5162 struct extent_map *em;
5163 struct map_lookup *map;
5166 em = get_chunk_map(fs_info, logical, len);
5168 if(!WARN_ON(IS_ERR(em))) {
5169 map = em->map_lookup;
5170 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5172 free_extent_map(em);
5177 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5178 struct map_lookup *map, int first, int num,
5179 int optimal, int dev_replace_is_ongoing)
5183 struct btrfs_device *srcdev;
5185 if (dev_replace_is_ongoing &&
5186 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5187 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5188 srcdev = fs_info->dev_replace.srcdev;
5193 * try to avoid the drive that is the source drive for a
5194 * dev-replace procedure, only choose it if no other non-missing
5195 * mirror is available
5197 for (tolerance = 0; tolerance < 2; tolerance++) {
5198 if (map->stripes[optimal].dev->bdev &&
5199 (tolerance || map->stripes[optimal].dev != srcdev))
5201 for (i = first; i < first + num; i++) {
5202 if (map->stripes[i].dev->bdev &&
5203 (tolerance || map->stripes[i].dev != srcdev))
5208 /* we couldn't find one that doesn't fail. Just return something
5209 * and the io error handling code will clean up eventually
5214 static inline int parity_smaller(u64 a, u64 b)
5219 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5220 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5222 struct btrfs_bio_stripe s;
5229 for (i = 0; i < num_stripes - 1; i++) {
5230 if (parity_smaller(bbio->raid_map[i],
5231 bbio->raid_map[i+1])) {
5232 s = bbio->stripes[i];
5233 l = bbio->raid_map[i];
5234 bbio->stripes[i] = bbio->stripes[i+1];
5235 bbio->raid_map[i] = bbio->raid_map[i+1];
5236 bbio->stripes[i+1] = s;
5237 bbio->raid_map[i+1] = l;
5245 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5247 struct btrfs_bio *bbio = kzalloc(
5248 /* the size of the btrfs_bio */
5249 sizeof(struct btrfs_bio) +
5250 /* plus the variable array for the stripes */
5251 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5252 /* plus the variable array for the tgt dev */
5253 sizeof(int) * (real_stripes) +
5255 * plus the raid_map, which includes both the tgt dev
5258 sizeof(u64) * (total_stripes),
5259 GFP_NOFS|__GFP_NOFAIL);
5261 atomic_set(&bbio->error, 0);
5262 refcount_set(&bbio->refs, 1);
5267 void btrfs_get_bbio(struct btrfs_bio *bbio)
5269 WARN_ON(!refcount_read(&bbio->refs));
5270 refcount_inc(&bbio->refs);
5273 void btrfs_put_bbio(struct btrfs_bio *bbio)
5277 if (refcount_dec_and_test(&bbio->refs))
5281 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5283 * Please note that, discard won't be sent to target device of device
5286 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5287 u64 logical, u64 length,
5288 struct btrfs_bio **bbio_ret)
5290 struct extent_map *em;
5291 struct map_lookup *map;
5292 struct btrfs_bio *bbio;
5296 u64 stripe_end_offset;
5303 u32 sub_stripes = 0;
5304 u64 stripes_per_dev = 0;
5305 u32 remaining_stripes = 0;
5306 u32 last_stripe = 0;
5310 /* discard always return a bbio */
5313 em = get_chunk_map(fs_info, logical, length);
5317 map = em->map_lookup;
5318 /* we don't discard raid56 yet */
5319 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5324 offset = logical - em->start;
5325 length = min_t(u64, em->len - offset, length);
5327 stripe_len = map->stripe_len;
5329 * stripe_nr counts the total number of stripes we have to stride
5330 * to get to this block
5332 stripe_nr = div64_u64(offset, stripe_len);
5334 /* stripe_offset is the offset of this block in its stripe */
5335 stripe_offset = offset - stripe_nr * stripe_len;
5337 stripe_nr_end = round_up(offset + length, map->stripe_len);
5338 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5339 stripe_cnt = stripe_nr_end - stripe_nr;
5340 stripe_end_offset = stripe_nr_end * map->stripe_len -
5343 * after this, stripe_nr is the number of stripes on this
5344 * device we have to walk to find the data, and stripe_index is
5345 * the number of our device in the stripe array
5349 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5350 BTRFS_BLOCK_GROUP_RAID10)) {
5351 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5354 sub_stripes = map->sub_stripes;
5356 factor = map->num_stripes / sub_stripes;
5357 num_stripes = min_t(u64, map->num_stripes,
5358 sub_stripes * stripe_cnt);
5359 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5360 stripe_index *= sub_stripes;
5361 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5362 &remaining_stripes);
5363 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5364 last_stripe *= sub_stripes;
5365 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5366 BTRFS_BLOCK_GROUP_DUP)) {
5367 num_stripes = map->num_stripes;
5369 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5373 bbio = alloc_btrfs_bio(num_stripes, 0);
5379 for (i = 0; i < num_stripes; i++) {
5380 bbio->stripes[i].physical =
5381 map->stripes[stripe_index].physical +
5382 stripe_offset + stripe_nr * map->stripe_len;
5383 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5385 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5386 BTRFS_BLOCK_GROUP_RAID10)) {
5387 bbio->stripes[i].length = stripes_per_dev *
5390 if (i / sub_stripes < remaining_stripes)
5391 bbio->stripes[i].length +=
5395 * Special for the first stripe and
5398 * |-------|...|-------|
5402 if (i < sub_stripes)
5403 bbio->stripes[i].length -=
5406 if (stripe_index >= last_stripe &&
5407 stripe_index <= (last_stripe +
5409 bbio->stripes[i].length -=
5412 if (i == sub_stripes - 1)
5415 bbio->stripes[i].length = length;
5419 if (stripe_index == map->num_stripes) {
5426 bbio->map_type = map->type;
5427 bbio->num_stripes = num_stripes;
5429 free_extent_map(em);
5434 * In dev-replace case, for repair case (that's the only case where the mirror
5435 * is selected explicitly when calling btrfs_map_block), blocks left of the
5436 * left cursor can also be read from the target drive.
5438 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5440 * For READ, it also needs to be supported using the same mirror number.
5442 * If the requested block is not left of the left cursor, EIO is returned. This
5443 * can happen because btrfs_num_copies() returns one more in the dev-replace
5446 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5447 u64 logical, u64 length,
5448 u64 srcdev_devid, int *mirror_num,
5451 struct btrfs_bio *bbio = NULL;
5453 int index_srcdev = 0;
5455 u64 physical_of_found = 0;
5459 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5460 logical, &length, &bbio, 0, 0);
5462 ASSERT(bbio == NULL);
5466 num_stripes = bbio->num_stripes;
5467 if (*mirror_num > num_stripes) {
5469 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5470 * that means that the requested area is not left of the left
5473 btrfs_put_bbio(bbio);
5478 * process the rest of the function using the mirror_num of the source
5479 * drive. Therefore look it up first. At the end, patch the device
5480 * pointer to the one of the target drive.
5482 for (i = 0; i < num_stripes; i++) {
5483 if (bbio->stripes[i].dev->devid != srcdev_devid)
5487 * In case of DUP, in order to keep it simple, only add the
5488 * mirror with the lowest physical address
5491 physical_of_found <= bbio->stripes[i].physical)
5496 physical_of_found = bbio->stripes[i].physical;
5499 btrfs_put_bbio(bbio);
5505 *mirror_num = index_srcdev + 1;
5506 *physical = physical_of_found;
5510 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5511 struct btrfs_bio **bbio_ret,
5512 struct btrfs_dev_replace *dev_replace,
5513 int *num_stripes_ret, int *max_errors_ret)
5515 struct btrfs_bio *bbio = *bbio_ret;
5516 u64 srcdev_devid = dev_replace->srcdev->devid;
5517 int tgtdev_indexes = 0;
5518 int num_stripes = *num_stripes_ret;
5519 int max_errors = *max_errors_ret;
5522 if (op == BTRFS_MAP_WRITE) {
5523 int index_where_to_add;
5526 * duplicate the write operations while the dev replace
5527 * procedure is running. Since the copying of the old disk to
5528 * the new disk takes place at run time while the filesystem is
5529 * mounted writable, the regular write operations to the old
5530 * disk have to be duplicated to go to the new disk as well.
5532 * Note that device->missing is handled by the caller, and that
5533 * the write to the old disk is already set up in the stripes
5536 index_where_to_add = num_stripes;
5537 for (i = 0; i < num_stripes; i++) {
5538 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5539 /* write to new disk, too */
5540 struct btrfs_bio_stripe *new =
5541 bbio->stripes + index_where_to_add;
5542 struct btrfs_bio_stripe *old =
5545 new->physical = old->physical;
5546 new->length = old->length;
5547 new->dev = dev_replace->tgtdev;
5548 bbio->tgtdev_map[i] = index_where_to_add;
5549 index_where_to_add++;
5554 num_stripes = index_where_to_add;
5555 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5556 int index_srcdev = 0;
5558 u64 physical_of_found = 0;
5561 * During the dev-replace procedure, the target drive can also
5562 * be used to read data in case it is needed to repair a corrupt
5563 * block elsewhere. This is possible if the requested area is
5564 * left of the left cursor. In this area, the target drive is a
5565 * full copy of the source drive.
5567 for (i = 0; i < num_stripes; i++) {
5568 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5570 * In case of DUP, in order to keep it simple,
5571 * only add the mirror with the lowest physical
5575 physical_of_found <=
5576 bbio->stripes[i].physical)
5580 physical_of_found = bbio->stripes[i].physical;
5584 struct btrfs_bio_stripe *tgtdev_stripe =
5585 bbio->stripes + num_stripes;
5587 tgtdev_stripe->physical = physical_of_found;
5588 tgtdev_stripe->length =
5589 bbio->stripes[index_srcdev].length;
5590 tgtdev_stripe->dev = dev_replace->tgtdev;
5591 bbio->tgtdev_map[index_srcdev] = num_stripes;
5598 *num_stripes_ret = num_stripes;
5599 *max_errors_ret = max_errors;
5600 bbio->num_tgtdevs = tgtdev_indexes;
5604 static bool need_full_stripe(enum btrfs_map_op op)
5606 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5609 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5610 enum btrfs_map_op op,
5611 u64 logical, u64 *length,
5612 struct btrfs_bio **bbio_ret,
5613 int mirror_num, int need_raid_map)
5615 struct extent_map *em;
5616 struct map_lookup *map;
5626 int tgtdev_indexes = 0;
5627 struct btrfs_bio *bbio = NULL;
5628 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5629 int dev_replace_is_ongoing = 0;
5630 int num_alloc_stripes;
5631 int patch_the_first_stripe_for_dev_replace = 0;
5632 u64 physical_to_patch_in_first_stripe = 0;
5633 u64 raid56_full_stripe_start = (u64)-1;
5635 if (op == BTRFS_MAP_DISCARD)
5636 return __btrfs_map_block_for_discard(fs_info, logical,
5639 em = get_chunk_map(fs_info, logical, *length);
5643 map = em->map_lookup;
5644 offset = logical - em->start;
5646 stripe_len = map->stripe_len;
5649 * stripe_nr counts the total number of stripes we have to stride
5650 * to get to this block
5652 stripe_nr = div64_u64(stripe_nr, stripe_len);
5654 stripe_offset = stripe_nr * stripe_len;
5655 if (offset < stripe_offset) {
5657 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5658 stripe_offset, offset, em->start, logical,
5660 free_extent_map(em);
5664 /* stripe_offset is the offset of this block in its stripe*/
5665 stripe_offset = offset - stripe_offset;
5667 /* if we're here for raid56, we need to know the stripe aligned start */
5668 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5669 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5670 raid56_full_stripe_start = offset;
5672 /* allow a write of a full stripe, but make sure we don't
5673 * allow straddling of stripes
5675 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5677 raid56_full_stripe_start *= full_stripe_len;
5680 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5682 /* For writes to RAID[56], allow a full stripeset across all disks.
5683 For other RAID types and for RAID[56] reads, just allow a single
5684 stripe (on a single disk). */
5685 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5686 (op == BTRFS_MAP_WRITE)) {
5687 max_len = stripe_len * nr_data_stripes(map) -
5688 (offset - raid56_full_stripe_start);
5690 /* we limit the length of each bio to what fits in a stripe */
5691 max_len = stripe_len - stripe_offset;
5693 *length = min_t(u64, em->len - offset, max_len);
5695 *length = em->len - offset;
5698 /* This is for when we're called from btrfs_merge_bio_hook() and all
5699 it cares about is the length */
5703 btrfs_dev_replace_lock(dev_replace, 0);
5704 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5705 if (!dev_replace_is_ongoing)
5706 btrfs_dev_replace_unlock(dev_replace, 0);
5708 btrfs_dev_replace_set_lock_blocking(dev_replace);
5710 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5711 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5712 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5713 dev_replace->srcdev->devid,
5715 &physical_to_patch_in_first_stripe);
5719 patch_the_first_stripe_for_dev_replace = 1;
5720 } else if (mirror_num > map->num_stripes) {
5726 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5727 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5729 if (op != BTRFS_MAP_WRITE && op != BTRFS_MAP_GET_READ_MIRRORS)
5731 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5732 if (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS)
5733 num_stripes = map->num_stripes;
5734 else if (mirror_num)
5735 stripe_index = mirror_num - 1;
5737 stripe_index = find_live_mirror(fs_info, map, 0,
5739 current->pid % map->num_stripes,
5740 dev_replace_is_ongoing);
5741 mirror_num = stripe_index + 1;
5744 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5745 if (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS) {
5746 num_stripes = map->num_stripes;
5747 } else if (mirror_num) {
5748 stripe_index = mirror_num - 1;
5753 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5754 u32 factor = map->num_stripes / map->sub_stripes;
5756 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5757 stripe_index *= map->sub_stripes;
5759 if (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS)
5760 num_stripes = map->sub_stripes;
5761 else if (mirror_num)
5762 stripe_index += mirror_num - 1;
5764 int old_stripe_index = stripe_index;
5765 stripe_index = find_live_mirror(fs_info, map,
5767 map->sub_stripes, stripe_index +
5768 current->pid % map->sub_stripes,
5769 dev_replace_is_ongoing);
5770 mirror_num = stripe_index - old_stripe_index + 1;
5773 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5774 if (need_raid_map &&
5775 (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS ||
5777 /* push stripe_nr back to the start of the full stripe */
5778 stripe_nr = div64_u64(raid56_full_stripe_start,
5779 stripe_len * nr_data_stripes(map));
5781 /* RAID[56] write or recovery. Return all stripes */
5782 num_stripes = map->num_stripes;
5783 max_errors = nr_parity_stripes(map);
5785 *length = map->stripe_len;
5790 * Mirror #0 or #1 means the original data block.
5791 * Mirror #2 is RAID5 parity block.
5792 * Mirror #3 is RAID6 Q block.
5794 stripe_nr = div_u64_rem(stripe_nr,
5795 nr_data_stripes(map), &stripe_index);
5797 stripe_index = nr_data_stripes(map) +
5800 /* We distribute the parity blocks across stripes */
5801 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5803 if ((op != BTRFS_MAP_WRITE &&
5804 op != BTRFS_MAP_GET_READ_MIRRORS) &&
5810 * after this, stripe_nr is the number of stripes on this
5811 * device we have to walk to find the data, and stripe_index is
5812 * the number of our device in the stripe array
5814 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5816 mirror_num = stripe_index + 1;
5818 if (stripe_index >= map->num_stripes) {
5820 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5821 stripe_index, map->num_stripes);
5826 num_alloc_stripes = num_stripes;
5827 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5828 if (op == BTRFS_MAP_WRITE)
5829 num_alloc_stripes <<= 1;
5830 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5831 num_alloc_stripes++;
5832 tgtdev_indexes = num_stripes;
5835 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5840 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5841 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5843 /* build raid_map */
5844 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5845 (need_full_stripe(op) || mirror_num > 1)) {
5849 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5850 sizeof(struct btrfs_bio_stripe) *
5852 sizeof(int) * tgtdev_indexes);
5854 /* Work out the disk rotation on this stripe-set */
5855 div_u64_rem(stripe_nr, num_stripes, &rot);
5857 /* Fill in the logical address of each stripe */
5858 tmp = stripe_nr * nr_data_stripes(map);
5859 for (i = 0; i < nr_data_stripes(map); i++)
5860 bbio->raid_map[(i+rot) % num_stripes] =
5861 em->start + (tmp + i) * map->stripe_len;
5863 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5864 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5865 bbio->raid_map[(i+rot+1) % num_stripes] =
5870 for (i = 0; i < num_stripes; i++) {
5871 bbio->stripes[i].physical =
5872 map->stripes[stripe_index].physical +
5874 stripe_nr * map->stripe_len;
5875 bbio->stripes[i].dev =
5876 map->stripes[stripe_index].dev;
5880 if (need_full_stripe(op))
5881 max_errors = btrfs_chunk_max_errors(map);
5884 sort_parity_stripes(bbio, num_stripes);
5886 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5887 need_full_stripe(op)) {
5888 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5893 bbio->map_type = map->type;
5894 bbio->num_stripes = num_stripes;
5895 bbio->max_errors = max_errors;
5896 bbio->mirror_num = mirror_num;
5899 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5900 * mirror_num == num_stripes + 1 && dev_replace target drive is
5901 * available as a mirror
5903 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5904 WARN_ON(num_stripes > 1);
5905 bbio->stripes[0].dev = dev_replace->tgtdev;
5906 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5907 bbio->mirror_num = map->num_stripes + 1;
5910 if (dev_replace_is_ongoing) {
5911 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5912 btrfs_dev_replace_unlock(dev_replace, 0);
5914 free_extent_map(em);
5918 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5919 u64 logical, u64 *length,
5920 struct btrfs_bio **bbio_ret, int mirror_num)
5922 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
5926 /* For Scrub/replace */
5927 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5928 u64 logical, u64 *length,
5929 struct btrfs_bio **bbio_ret)
5931 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
5934 int btrfs_rmap_block(struct btrfs_fs_info *fs_info,
5935 u64 chunk_start, u64 physical, u64 devid,
5936 u64 **logical, int *naddrs, int *stripe_len)
5938 struct extent_map *em;
5939 struct map_lookup *map;
5947 em = get_chunk_map(fs_info, chunk_start, 1);
5951 map = em->map_lookup;
5953 rmap_len = map->stripe_len;
5955 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5956 length = div_u64(length, map->num_stripes / map->sub_stripes);
5957 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5958 length = div_u64(length, map->num_stripes);
5959 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5960 length = div_u64(length, nr_data_stripes(map));
5961 rmap_len = map->stripe_len * nr_data_stripes(map);
5964 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5965 BUG_ON(!buf); /* -ENOMEM */
5967 for (i = 0; i < map->num_stripes; i++) {
5968 if (devid && map->stripes[i].dev->devid != devid)
5970 if (map->stripes[i].physical > physical ||
5971 map->stripes[i].physical + length <= physical)
5974 stripe_nr = physical - map->stripes[i].physical;
5975 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
5977 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5978 stripe_nr = stripe_nr * map->num_stripes + i;
5979 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
5980 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5981 stripe_nr = stripe_nr * map->num_stripes + i;
5982 } /* else if RAID[56], multiply by nr_data_stripes().
5983 * Alternatively, just use rmap_len below instead of
5984 * map->stripe_len */
5986 bytenr = chunk_start + stripe_nr * rmap_len;
5987 WARN_ON(nr >= map->num_stripes);
5988 for (j = 0; j < nr; j++) {
5989 if (buf[j] == bytenr)
5993 WARN_ON(nr >= map->num_stripes);
6000 *stripe_len = rmap_len;
6002 free_extent_map(em);
6006 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6008 bio->bi_private = bbio->private;
6009 bio->bi_end_io = bbio->end_io;
6012 btrfs_put_bbio(bbio);
6015 static void btrfs_end_bio(struct bio *bio)
6017 struct btrfs_bio *bbio = bio->bi_private;
6018 int is_orig_bio = 0;
6020 if (bio->bi_status) {
6021 atomic_inc(&bbio->error);
6022 if (bio->bi_status == BLK_STS_IOERR ||
6023 bio->bi_status == BLK_STS_TARGET) {
6024 unsigned int stripe_index =
6025 btrfs_io_bio(bio)->stripe_index;
6026 struct btrfs_device *dev;
6028 BUG_ON(stripe_index >= bbio->num_stripes);
6029 dev = bbio->stripes[stripe_index].dev;
6031 if (bio_op(bio) == REQ_OP_WRITE)
6032 btrfs_dev_stat_inc(dev,
6033 BTRFS_DEV_STAT_WRITE_ERRS);
6035 btrfs_dev_stat_inc(dev,
6036 BTRFS_DEV_STAT_READ_ERRS);
6037 if (bio->bi_opf & REQ_PREFLUSH)
6038 btrfs_dev_stat_inc(dev,
6039 BTRFS_DEV_STAT_FLUSH_ERRS);
6040 btrfs_dev_stat_print_on_error(dev);
6045 if (bio == bbio->orig_bio)
6048 btrfs_bio_counter_dec(bbio->fs_info);
6050 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6053 bio = bbio->orig_bio;
6056 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6057 /* only send an error to the higher layers if it is
6058 * beyond the tolerance of the btrfs bio
6060 if (atomic_read(&bbio->error) > bbio->max_errors) {
6061 bio->bi_status = BLK_STS_IOERR;
6064 * this bio is actually up to date, we didn't
6065 * go over the max number of errors
6070 btrfs_end_bbio(bbio, bio);
6071 } else if (!is_orig_bio) {
6077 * see run_scheduled_bios for a description of why bios are collected for
6080 * This will add one bio to the pending list for a device and make sure
6081 * the work struct is scheduled.
6083 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6086 struct btrfs_fs_info *fs_info = device->fs_info;
6087 int should_queue = 1;
6088 struct btrfs_pending_bios *pending_bios;
6090 if (device->missing || !device->bdev) {
6095 /* don't bother with additional async steps for reads, right now */
6096 if (bio_op(bio) == REQ_OP_READ) {
6098 btrfsic_submit_bio(bio);
6104 * nr_async_bios allows us to reliably return congestion to the
6105 * higher layers. Otherwise, the async bio makes it appear we have
6106 * made progress against dirty pages when we've really just put it
6107 * on a queue for later
6109 atomic_inc(&fs_info->nr_async_bios);
6110 WARN_ON(bio->bi_next);
6111 bio->bi_next = NULL;
6113 spin_lock(&device->io_lock);
6114 if (op_is_sync(bio->bi_opf))
6115 pending_bios = &device->pending_sync_bios;
6117 pending_bios = &device->pending_bios;
6119 if (pending_bios->tail)
6120 pending_bios->tail->bi_next = bio;
6122 pending_bios->tail = bio;
6123 if (!pending_bios->head)
6124 pending_bios->head = bio;
6125 if (device->running_pending)
6128 spin_unlock(&device->io_lock);
6131 btrfs_queue_work(fs_info->submit_workers, &device->work);
6134 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6135 u64 physical, int dev_nr, int async)
6137 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6138 struct btrfs_fs_info *fs_info = bbio->fs_info;
6140 bio->bi_private = bbio;
6141 btrfs_io_bio(bio)->stripe_index = dev_nr;
6142 bio->bi_end_io = btrfs_end_bio;
6143 bio->bi_iter.bi_sector = physical >> 9;
6146 struct rcu_string *name;
6149 name = rcu_dereference(dev->name);
6150 btrfs_debug(fs_info,
6151 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6152 bio_op(bio), bio->bi_opf,
6153 (u64)bio->bi_iter.bi_sector,
6154 (u_long)dev->bdev->bd_dev, name->str, dev->devid,
6155 bio->bi_iter.bi_size);
6159 bio_set_dev(bio, dev->bdev);
6161 btrfs_bio_counter_inc_noblocked(fs_info);
6164 btrfs_schedule_bio(dev, bio);
6166 btrfsic_submit_bio(bio);
6169 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6171 atomic_inc(&bbio->error);
6172 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6173 /* Should be the original bio. */
6174 WARN_ON(bio != bbio->orig_bio);
6176 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6177 bio->bi_iter.bi_sector = logical >> 9;
6178 if (atomic_read(&bbio->error) > bbio->max_errors)
6179 bio->bi_status = BLK_STS_IOERR;
6181 bio->bi_status = BLK_STS_OK;
6182 btrfs_end_bbio(bbio, bio);
6186 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6187 int mirror_num, int async_submit)
6189 struct btrfs_device *dev;
6190 struct bio *first_bio = bio;
6191 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6197 struct btrfs_bio *bbio = NULL;
6199 length = bio->bi_iter.bi_size;
6200 map_length = length;
6202 btrfs_bio_counter_inc_blocked(fs_info);
6203 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6204 &map_length, &bbio, mirror_num, 1);
6206 btrfs_bio_counter_dec(fs_info);
6207 return errno_to_blk_status(ret);
6210 total_devs = bbio->num_stripes;
6211 bbio->orig_bio = first_bio;
6212 bbio->private = first_bio->bi_private;
6213 bbio->end_io = first_bio->bi_end_io;
6214 bbio->fs_info = fs_info;
6215 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6217 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6218 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6219 /* In this case, map_length has been set to the length of
6220 a single stripe; not the whole write */
6221 if (bio_op(bio) == REQ_OP_WRITE) {
6222 ret = raid56_parity_write(fs_info, bio, bbio,
6225 ret = raid56_parity_recover(fs_info, bio, bbio,
6226 map_length, mirror_num, 1);
6229 btrfs_bio_counter_dec(fs_info);
6230 return errno_to_blk_status(ret);
6233 if (map_length < length) {
6235 "mapping failed logical %llu bio len %llu len %llu",
6236 logical, length, map_length);
6240 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6241 dev = bbio->stripes[dev_nr].dev;
6242 if (!dev || !dev->bdev ||
6243 (bio_op(first_bio) == REQ_OP_WRITE && !dev->writeable)) {
6244 bbio_error(bbio, first_bio, logical);
6248 if (dev_nr < total_devs - 1)
6249 bio = btrfs_bio_clone(first_bio);
6253 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6254 dev_nr, async_submit);
6256 btrfs_bio_counter_dec(fs_info);
6260 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6263 struct btrfs_device *device;
6264 struct btrfs_fs_devices *cur_devices;
6266 cur_devices = fs_info->fs_devices;
6267 while (cur_devices) {
6269 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6270 device = find_device(cur_devices, devid, uuid);
6274 cur_devices = cur_devices->seed;
6279 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6280 u64 devid, u8 *dev_uuid)
6282 struct btrfs_device *device;
6283 unsigned int nofs_flag;
6286 * We call this under the chunk_mutex, so we want to use NOFS for this
6287 * allocation, however we don't want to change btrfs_alloc_device() to
6288 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6291 nofs_flag = memalloc_nofs_save();
6292 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6293 memalloc_nofs_restore(nofs_flag);
6297 list_add(&device->dev_list, &fs_devices->devices);
6298 device->fs_devices = fs_devices;
6299 fs_devices->num_devices++;
6301 device->missing = 1;
6302 fs_devices->missing_devices++;
6308 * btrfs_alloc_device - allocate struct btrfs_device
6309 * @fs_info: used only for generating a new devid, can be NULL if
6310 * devid is provided (i.e. @devid != NULL).
6311 * @devid: a pointer to devid for this device. If NULL a new devid
6313 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6316 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6317 * on error. Returned struct is not linked onto any lists and can be
6318 * destroyed with kfree() right away.
6320 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6324 struct btrfs_device *dev;
6327 if (WARN_ON(!devid && !fs_info))
6328 return ERR_PTR(-EINVAL);
6330 dev = __alloc_device();
6339 ret = find_next_devid(fs_info, &tmp);
6342 return ERR_PTR(ret);
6348 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6350 generate_random_uuid(dev->uuid);
6352 btrfs_init_work(&dev->work, btrfs_submit_helper,
6353 pending_bios_fn, NULL, NULL);
6358 /* Return -EIO if any error, otherwise return 0. */
6359 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6360 struct extent_buffer *leaf,
6361 struct btrfs_chunk *chunk, u64 logical)
6371 length = btrfs_chunk_length(leaf, chunk);
6372 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6373 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6374 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6375 type = btrfs_chunk_type(leaf, chunk);
6378 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6382 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6383 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6386 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6387 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6388 btrfs_chunk_sector_size(leaf, chunk));
6391 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6392 btrfs_err(fs_info, "invalid chunk length %llu", length);
6395 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6396 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6400 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6402 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6403 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6404 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6405 btrfs_chunk_type(leaf, chunk));
6409 if (!is_power_of_2(type & BTRFS_BLOCK_GROUP_PROFILE_MASK) &&
6410 (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) != 0) {
6412 "invalid chunk profile flag: 0x%llx, expect 0 or 1 bit set",
6413 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6416 if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == 0) {
6417 btrfs_err(fs_info, "missing chunk type flag: 0x%llx", type);
6421 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) &&
6422 (type & (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA))) {
6424 "system chunk with data or metadata type: 0x%llx", type);
6428 features = btrfs_super_incompat_flags(fs_info->super_copy);
6429 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
6433 if ((type & BTRFS_BLOCK_GROUP_METADATA) &&
6434 (type & BTRFS_BLOCK_GROUP_DATA)) {
6436 "mixed chunk type in non-mixed mode: 0x%llx", type);
6441 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6442 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes != 2) ||
6443 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6444 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6445 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes != 2) ||
6446 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6447 num_stripes != 1)) {
6449 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6450 num_stripes, sub_stripes,
6451 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6458 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6459 struct extent_buffer *leaf,
6460 struct btrfs_chunk *chunk)
6462 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6463 struct map_lookup *map;
6464 struct extent_map *em;
6468 u8 uuid[BTRFS_UUID_SIZE];
6473 logical = key->offset;
6474 length = btrfs_chunk_length(leaf, chunk);
6475 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6477 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6481 read_lock(&map_tree->map_tree.lock);
6482 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6483 read_unlock(&map_tree->map_tree.lock);
6485 /* already mapped? */
6486 if (em && em->start <= logical && em->start + em->len > logical) {
6487 free_extent_map(em);
6490 free_extent_map(em);
6493 em = alloc_extent_map();
6496 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6498 free_extent_map(em);
6502 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6503 em->map_lookup = map;
6504 em->start = logical;
6507 em->block_start = 0;
6508 em->block_len = em->len;
6510 map->num_stripes = num_stripes;
6511 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6512 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6513 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6514 map->type = btrfs_chunk_type(leaf, chunk);
6515 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6516 for (i = 0; i < num_stripes; i++) {
6517 map->stripes[i].physical =
6518 btrfs_stripe_offset_nr(leaf, chunk, i);
6519 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6520 read_extent_buffer(leaf, uuid, (unsigned long)
6521 btrfs_stripe_dev_uuid_nr(chunk, i),
6523 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6525 if (!map->stripes[i].dev &&
6526 !btrfs_test_opt(fs_info, DEGRADED)) {
6527 free_extent_map(em);
6528 btrfs_report_missing_device(fs_info, devid, uuid);
6531 if (!map->stripes[i].dev) {
6532 map->stripes[i].dev =
6533 add_missing_dev(fs_info->fs_devices, devid,
6535 if (!map->stripes[i].dev) {
6536 free_extent_map(em);
6539 btrfs_report_missing_device(fs_info, devid, uuid);
6541 map->stripes[i].dev->in_fs_metadata = 1;
6544 write_lock(&map_tree->map_tree.lock);
6545 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6546 write_unlock(&map_tree->map_tree.lock);
6549 "failed to add chunk map, start=%llu len=%llu: %d",
6550 em->start, em->len, ret);
6552 free_extent_map(em);
6557 static void fill_device_from_item(struct extent_buffer *leaf,
6558 struct btrfs_dev_item *dev_item,
6559 struct btrfs_device *device)
6563 device->devid = btrfs_device_id(leaf, dev_item);
6564 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6565 device->total_bytes = device->disk_total_bytes;
6566 device->commit_total_bytes = device->disk_total_bytes;
6567 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6568 device->commit_bytes_used = device->bytes_used;
6569 device->type = btrfs_device_type(leaf, dev_item);
6570 device->io_align = btrfs_device_io_align(leaf, dev_item);
6571 device->io_width = btrfs_device_io_width(leaf, dev_item);
6572 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6573 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6574 device->is_tgtdev_for_dev_replace = 0;
6576 ptr = btrfs_device_uuid(dev_item);
6577 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6580 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6583 struct btrfs_fs_devices *fs_devices;
6586 BUG_ON(!mutex_is_locked(&uuid_mutex));
6589 fs_devices = fs_info->fs_devices->seed;
6590 while (fs_devices) {
6591 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6594 fs_devices = fs_devices->seed;
6597 fs_devices = find_fsid(fsid);
6599 if (!btrfs_test_opt(fs_info, DEGRADED))
6600 return ERR_PTR(-ENOENT);
6602 fs_devices = alloc_fs_devices(fsid);
6603 if (IS_ERR(fs_devices))
6606 fs_devices->seeding = 1;
6607 fs_devices->opened = 1;
6611 fs_devices = clone_fs_devices(fs_devices);
6612 if (IS_ERR(fs_devices))
6615 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6616 fs_info->bdev_holder);
6618 free_fs_devices(fs_devices);
6619 fs_devices = ERR_PTR(ret);
6623 if (!fs_devices->seeding) {
6624 __btrfs_close_devices(fs_devices);
6625 free_fs_devices(fs_devices);
6626 fs_devices = ERR_PTR(-EINVAL);
6630 fs_devices->seed = fs_info->fs_devices->seed;
6631 fs_info->fs_devices->seed = fs_devices;
6636 static int read_one_dev(struct btrfs_fs_info *fs_info,
6637 struct extent_buffer *leaf,
6638 struct btrfs_dev_item *dev_item)
6640 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6641 struct btrfs_device *device;
6644 u8 fs_uuid[BTRFS_FSID_SIZE];
6645 u8 dev_uuid[BTRFS_UUID_SIZE];
6647 devid = btrfs_device_id(leaf, dev_item);
6648 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6650 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6653 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6654 fs_devices = open_seed_devices(fs_info, fs_uuid);
6655 if (IS_ERR(fs_devices))
6656 return PTR_ERR(fs_devices);
6659 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6661 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6662 btrfs_report_missing_device(fs_info, devid, dev_uuid);
6666 device = add_missing_dev(fs_devices, devid, dev_uuid);
6669 btrfs_report_missing_device(fs_info, devid, dev_uuid);
6671 if (!device->bdev) {
6672 btrfs_report_missing_device(fs_info, devid, dev_uuid);
6673 if (!btrfs_test_opt(fs_info, DEGRADED))
6677 if(!device->bdev && !device->missing) {
6679 * this happens when a device that was properly setup
6680 * in the device info lists suddenly goes bad.
6681 * device->bdev is NULL, and so we have to set
6682 * device->missing to one here
6684 device->fs_devices->missing_devices++;
6685 device->missing = 1;
6688 /* Move the device to its own fs_devices */
6689 if (device->fs_devices != fs_devices) {
6690 ASSERT(device->missing);
6692 list_move(&device->dev_list, &fs_devices->devices);
6693 device->fs_devices->num_devices--;
6694 fs_devices->num_devices++;
6696 device->fs_devices->missing_devices--;
6697 fs_devices->missing_devices++;
6699 device->fs_devices = fs_devices;
6703 if (device->fs_devices != fs_info->fs_devices) {
6704 BUG_ON(device->writeable);
6705 if (device->generation !=
6706 btrfs_device_generation(leaf, dev_item))
6710 fill_device_from_item(leaf, dev_item, device);
6711 device->in_fs_metadata = 1;
6712 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6713 device->fs_devices->total_rw_bytes += device->total_bytes;
6714 atomic64_add(device->total_bytes - device->bytes_used,
6715 &fs_info->free_chunk_space);
6721 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6723 struct btrfs_root *root = fs_info->tree_root;
6724 struct btrfs_super_block *super_copy = fs_info->super_copy;
6725 struct extent_buffer *sb;
6726 struct btrfs_disk_key *disk_key;
6727 struct btrfs_chunk *chunk;
6729 unsigned long sb_array_offset;
6736 struct btrfs_key key;
6738 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6740 * This will create extent buffer of nodesize, superblock size is
6741 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6742 * overallocate but we can keep it as-is, only the first page is used.
6744 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6747 set_extent_buffer_uptodate(sb);
6748 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6750 * The sb extent buffer is artificial and just used to read the system array.
6751 * set_extent_buffer_uptodate() call does not properly mark all it's
6752 * pages up-to-date when the page is larger: extent does not cover the
6753 * whole page and consequently check_page_uptodate does not find all
6754 * the page's extents up-to-date (the hole beyond sb),
6755 * write_extent_buffer then triggers a WARN_ON.
6757 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6758 * but sb spans only this function. Add an explicit SetPageUptodate call
6759 * to silence the warning eg. on PowerPC 64.
6761 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6762 SetPageUptodate(sb->pages[0]);
6764 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6765 array_size = btrfs_super_sys_array_size(super_copy);
6767 array_ptr = super_copy->sys_chunk_array;
6768 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6771 while (cur_offset < array_size) {
6772 disk_key = (struct btrfs_disk_key *)array_ptr;
6773 len = sizeof(*disk_key);
6774 if (cur_offset + len > array_size)
6775 goto out_short_read;
6777 btrfs_disk_key_to_cpu(&key, disk_key);
6780 sb_array_offset += len;
6783 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6784 chunk = (struct btrfs_chunk *)sb_array_offset;
6786 * At least one btrfs_chunk with one stripe must be
6787 * present, exact stripe count check comes afterwards
6789 len = btrfs_chunk_item_size(1);
6790 if (cur_offset + len > array_size)
6791 goto out_short_read;
6793 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6796 "invalid number of stripes %u in sys_array at offset %u",
6797 num_stripes, cur_offset);
6802 type = btrfs_chunk_type(sb, chunk);
6803 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6805 "invalid chunk type %llu in sys_array at offset %u",
6811 len = btrfs_chunk_item_size(num_stripes);
6812 if (cur_offset + len > array_size)
6813 goto out_short_read;
6815 ret = read_one_chunk(fs_info, &key, sb, chunk);
6820 "unexpected item type %u in sys_array at offset %u",
6821 (u32)key.type, cur_offset);
6826 sb_array_offset += len;
6829 clear_extent_buffer_uptodate(sb);
6830 free_extent_buffer_stale(sb);
6834 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6836 clear_extent_buffer_uptodate(sb);
6837 free_extent_buffer_stale(sb);
6841 void btrfs_report_missing_device(struct btrfs_fs_info *fs_info, u64 devid,
6844 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing", devid, uuid);
6848 * Check if all chunks in the fs are OK for read-write degraded mount
6850 * Return true if all chunks meet the minimal RW mount requirements.
6851 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6853 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info)
6855 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6856 struct extent_map *em;
6860 read_lock(&map_tree->map_tree.lock);
6861 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6862 read_unlock(&map_tree->map_tree.lock);
6863 /* No chunk at all? Return false anyway */
6869 struct map_lookup *map;
6874 map = em->map_lookup;
6876 btrfs_get_num_tolerated_disk_barrier_failures(
6878 for (i = 0; i < map->num_stripes; i++) {
6879 struct btrfs_device *dev = map->stripes[i].dev;
6881 if (!dev || !dev->bdev || dev->missing ||
6882 dev->last_flush_error)
6885 if (missing > max_tolerated) {
6887 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6888 em->start, missing, max_tolerated);
6889 free_extent_map(em);
6893 next_start = extent_map_end(em);
6894 free_extent_map(em);
6896 read_lock(&map_tree->map_tree.lock);
6897 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6898 (u64)(-1) - next_start);
6899 read_unlock(&map_tree->map_tree.lock);
6905 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6907 struct btrfs_root *root = fs_info->chunk_root;
6908 struct btrfs_path *path;
6909 struct extent_buffer *leaf;
6910 struct btrfs_key key;
6911 struct btrfs_key found_key;
6916 path = btrfs_alloc_path();
6920 mutex_lock(&uuid_mutex);
6921 mutex_lock(&fs_info->chunk_mutex);
6924 * It is possible for mount and umount to race in such a way that
6925 * we execute this code path, but open_fs_devices failed to clear
6926 * total_rw_bytes. We certainly want it cleared before reading the
6927 * device items, so clear it here.
6929 fs_info->fs_devices->total_rw_bytes = 0;
6932 * Read all device items, and then all the chunk items. All
6933 * device items are found before any chunk item (their object id
6934 * is smaller than the lowest possible object id for a chunk
6935 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6937 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6940 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6944 leaf = path->nodes[0];
6945 slot = path->slots[0];
6946 if (slot >= btrfs_header_nritems(leaf)) {
6947 ret = btrfs_next_leaf(root, path);
6954 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6955 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6956 struct btrfs_dev_item *dev_item;
6957 dev_item = btrfs_item_ptr(leaf, slot,
6958 struct btrfs_dev_item);
6959 ret = read_one_dev(fs_info, leaf, dev_item);
6963 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6964 struct btrfs_chunk *chunk;
6965 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6966 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
6974 * After loading chunk tree, we've got all device information,
6975 * do another round of validation checks.
6977 if (total_dev != fs_info->fs_devices->total_devices) {
6979 "super_num_devices %llu mismatch with num_devices %llu found here",
6980 btrfs_super_num_devices(fs_info->super_copy),
6985 if (btrfs_super_total_bytes(fs_info->super_copy) <
6986 fs_info->fs_devices->total_rw_bytes) {
6988 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
6989 btrfs_super_total_bytes(fs_info->super_copy),
6990 fs_info->fs_devices->total_rw_bytes);
6996 mutex_unlock(&fs_info->chunk_mutex);
6997 mutex_unlock(&uuid_mutex);
6999 btrfs_free_path(path);
7003 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7005 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7006 struct btrfs_device *device;
7008 while (fs_devices) {
7009 mutex_lock(&fs_devices->device_list_mutex);
7010 list_for_each_entry(device, &fs_devices->devices, dev_list)
7011 device->fs_info = fs_info;
7012 mutex_unlock(&fs_devices->device_list_mutex);
7014 fs_devices = fs_devices->seed;
7018 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7022 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7023 btrfs_dev_stat_reset(dev, i);
7026 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7028 struct btrfs_key key;
7029 struct btrfs_key found_key;
7030 struct btrfs_root *dev_root = fs_info->dev_root;
7031 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7032 struct extent_buffer *eb;
7035 struct btrfs_device *device;
7036 struct btrfs_path *path = NULL;
7039 path = btrfs_alloc_path();
7045 mutex_lock(&fs_devices->device_list_mutex);
7046 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7048 struct btrfs_dev_stats_item *ptr;
7050 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7051 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7052 key.offset = device->devid;
7053 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7055 __btrfs_reset_dev_stats(device);
7056 device->dev_stats_valid = 1;
7057 btrfs_release_path(path);
7060 slot = path->slots[0];
7061 eb = path->nodes[0];
7062 btrfs_item_key_to_cpu(eb, &found_key, slot);
7063 item_size = btrfs_item_size_nr(eb, slot);
7065 ptr = btrfs_item_ptr(eb, slot,
7066 struct btrfs_dev_stats_item);
7068 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7069 if (item_size >= (1 + i) * sizeof(__le64))
7070 btrfs_dev_stat_set(device, i,
7071 btrfs_dev_stats_value(eb, ptr, i));
7073 btrfs_dev_stat_reset(device, i);
7076 device->dev_stats_valid = 1;
7077 btrfs_dev_stat_print_on_load(device);
7078 btrfs_release_path(path);
7080 mutex_unlock(&fs_devices->device_list_mutex);
7083 btrfs_free_path(path);
7084 return ret < 0 ? ret : 0;
7087 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7088 struct btrfs_fs_info *fs_info,
7089 struct btrfs_device *device)
7091 struct btrfs_root *dev_root = fs_info->dev_root;
7092 struct btrfs_path *path;
7093 struct btrfs_key key;
7094 struct extent_buffer *eb;
7095 struct btrfs_dev_stats_item *ptr;
7099 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7100 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7101 key.offset = device->devid;
7103 path = btrfs_alloc_path();
7106 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7108 btrfs_warn_in_rcu(fs_info,
7109 "error %d while searching for dev_stats item for device %s",
7110 ret, rcu_str_deref(device->name));
7115 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7116 /* need to delete old one and insert a new one */
7117 ret = btrfs_del_item(trans, dev_root, path);
7119 btrfs_warn_in_rcu(fs_info,
7120 "delete too small dev_stats item for device %s failed %d",
7121 rcu_str_deref(device->name), ret);
7128 /* need to insert a new item */
7129 btrfs_release_path(path);
7130 ret = btrfs_insert_empty_item(trans, dev_root, path,
7131 &key, sizeof(*ptr));
7133 btrfs_warn_in_rcu(fs_info,
7134 "insert dev_stats item for device %s failed %d",
7135 rcu_str_deref(device->name), ret);
7140 eb = path->nodes[0];
7141 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7142 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7143 btrfs_set_dev_stats_value(eb, ptr, i,
7144 btrfs_dev_stat_read(device, i));
7145 btrfs_mark_buffer_dirty(eb);
7148 btrfs_free_path(path);
7153 * called from commit_transaction. Writes all changed device stats to disk.
7155 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7156 struct btrfs_fs_info *fs_info)
7158 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7159 struct btrfs_device *device;
7163 mutex_lock(&fs_devices->device_list_mutex);
7164 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7165 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7166 if (!device->dev_stats_valid || stats_cnt == 0)
7171 * There is a LOAD-LOAD control dependency between the value of
7172 * dev_stats_ccnt and updating the on-disk values which requires
7173 * reading the in-memory counters. Such control dependencies
7174 * require explicit read memory barriers.
7176 * This memory barriers pairs with smp_mb__before_atomic in
7177 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7178 * barrier implied by atomic_xchg in
7179 * btrfs_dev_stats_read_and_reset
7183 ret = update_dev_stat_item(trans, fs_info, device);
7185 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7187 mutex_unlock(&fs_devices->device_list_mutex);
7192 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7194 btrfs_dev_stat_inc(dev, index);
7195 btrfs_dev_stat_print_on_error(dev);
7198 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7200 if (!dev->dev_stats_valid)
7202 btrfs_err_rl_in_rcu(dev->fs_info,
7203 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7204 rcu_str_deref(dev->name),
7205 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7206 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7207 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7208 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7209 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7212 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7216 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7217 if (btrfs_dev_stat_read(dev, i) != 0)
7219 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7220 return; /* all values == 0, suppress message */
7222 btrfs_info_in_rcu(dev->fs_info,
7223 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7224 rcu_str_deref(dev->name),
7225 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7226 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7227 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7228 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7229 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7232 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7233 struct btrfs_ioctl_get_dev_stats *stats)
7235 struct btrfs_device *dev;
7236 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7239 mutex_lock(&fs_devices->device_list_mutex);
7240 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7241 mutex_unlock(&fs_devices->device_list_mutex);
7244 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7246 } else if (!dev->dev_stats_valid) {
7247 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7249 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7250 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7251 if (stats->nr_items > i)
7253 btrfs_dev_stat_read_and_reset(dev, i);
7255 btrfs_dev_stat_reset(dev, i);
7257 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7258 current->comm, task_pid_nr(current));
7260 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7261 if (stats->nr_items > i)
7262 stats->values[i] = btrfs_dev_stat_read(dev, i);
7264 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7265 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7269 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7271 struct buffer_head *bh;
7272 struct btrfs_super_block *disk_super;
7278 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7281 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7284 disk_super = (struct btrfs_super_block *)bh->b_data;
7286 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7287 set_buffer_dirty(bh);
7288 sync_dirty_buffer(bh);
7292 /* Notify udev that device has changed */
7293 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7295 /* Update ctime/mtime for device path for libblkid */
7296 update_dev_time(device_path);
7300 * Update the size of all devices, which is used for writing out the
7303 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7305 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7306 struct btrfs_device *curr, *next;
7308 if (list_empty(&fs_devices->resized_devices))
7311 mutex_lock(&fs_devices->device_list_mutex);
7312 mutex_lock(&fs_info->chunk_mutex);
7313 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7315 list_del_init(&curr->resized_list);
7316 curr->commit_total_bytes = curr->disk_total_bytes;
7318 mutex_unlock(&fs_info->chunk_mutex);
7319 mutex_unlock(&fs_devices->device_list_mutex);
7322 /* Must be invoked during the transaction commit */
7323 void btrfs_update_commit_device_bytes_used(struct btrfs_fs_info *fs_info,
7324 struct btrfs_transaction *transaction)
7326 struct extent_map *em;
7327 struct map_lookup *map;
7328 struct btrfs_device *dev;
7331 if (list_empty(&transaction->pending_chunks))
7334 /* In order to kick the device replace finish process */
7335 mutex_lock(&fs_info->chunk_mutex);
7336 list_for_each_entry(em, &transaction->pending_chunks, list) {
7337 map = em->map_lookup;
7339 for (i = 0; i < map->num_stripes; i++) {
7340 dev = map->stripes[i].dev;
7341 dev->commit_bytes_used = dev->bytes_used;
7342 dev->has_pending_chunks = false;
7345 mutex_unlock(&fs_info->chunk_mutex);
7348 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7350 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7351 while (fs_devices) {
7352 fs_devices->fs_info = fs_info;
7353 fs_devices = fs_devices->seed;
7357 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7359 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7360 while (fs_devices) {
7361 fs_devices->fs_info = NULL;
7362 fs_devices = fs_devices->seed;