1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
8 #include <linux/slab.h>
9 #include <linux/buffer_head.h>
10 #include <linux/blkdev.h>
11 #include <linux/ratelimit.h>
12 #include <linux/kthread.h>
13 #include <linux/raid/pq.h>
14 #include <linux/semaphore.h>
15 #include <linux/uuid.h>
16 #include <linux/list_sort.h>
18 #include "extent_map.h"
20 #include "transaction.h"
21 #include "print-tree.h"
24 #include "async-thread.h"
25 #include "check-integrity.h"
26 #include "rcu-string.h"
28 #include "dev-replace.h"
31 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
32 [BTRFS_RAID_RAID10] = {
35 .devs_max = 0, /* 0 == as many as possible */
37 .tolerated_failures = 1,
40 .raid_name = "raid10",
41 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
42 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
44 [BTRFS_RAID_RAID1] = {
49 .tolerated_failures = 1,
53 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
54 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
61 .tolerated_failures = 0,
65 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
68 [BTRFS_RAID_RAID0] = {
73 .tolerated_failures = 0,
77 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
80 [BTRFS_RAID_SINGLE] = {
85 .tolerated_failures = 0,
88 .raid_name = "single",
92 [BTRFS_RAID_RAID5] = {
97 .tolerated_failures = 1,
100 .raid_name = "raid5",
101 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
102 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
104 [BTRFS_RAID_RAID6] = {
109 .tolerated_failures = 2,
112 .raid_name = "raid6",
113 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
114 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
118 const char *get_raid_name(enum btrfs_raid_types type)
120 if (type >= BTRFS_NR_RAID_TYPES)
123 return btrfs_raid_array[type].raid_name;
126 static int init_first_rw_device(struct btrfs_trans_handle *trans,
127 struct btrfs_fs_info *fs_info);
128 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
129 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
130 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
131 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
132 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
133 enum btrfs_map_op op,
134 u64 logical, u64 *length,
135 struct btrfs_bio **bbio_ret,
136 int mirror_num, int need_raid_map);
142 * There are several mutexes that protect manipulation of devices and low-level
143 * structures like chunks but not block groups, extents or files
145 * uuid_mutex (global lock)
146 * ------------------------
147 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
148 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
149 * device) or requested by the device= mount option
151 * the mutex can be very coarse and can cover long-running operations
153 * protects: updates to fs_devices counters like missing devices, rw devices,
154 * seeding, structure cloning, openning/closing devices at mount/umount time
156 * global::fs_devs - add, remove, updates to the global list
158 * does not protect: manipulation of the fs_devices::devices list!
160 * btrfs_device::name - renames (write side), read is RCU
162 * fs_devices::device_list_mutex (per-fs, with RCU)
163 * ------------------------------------------------
164 * protects updates to fs_devices::devices, ie. adding and deleting
166 * simple list traversal with read-only actions can be done with RCU protection
168 * may be used to exclude some operations from running concurrently without any
169 * modifications to the list (see write_all_supers)
173 * protects balance structures (status, state) and context accessed from
174 * several places (internally, ioctl)
178 * protects chunks, adding or removing during allocation, trim or when a new
179 * device is added/removed
183 * a big lock that is held by the cleaner thread and prevents running subvolume
184 * cleaning together with relocation or delayed iputs
197 * Exclusive operations, BTRFS_FS_EXCL_OP
198 * ======================================
200 * Maintains the exclusivity of the following operations that apply to the
201 * whole filesystem and cannot run in parallel.
206 * - Device replace (*)
209 * The device operations (as above) can be in one of the following states:
215 * Only device operations marked with (*) can go into the Paused state for the
218 * - ioctl (only Balance can be Paused through ioctl)
219 * - filesystem remounted as read-only
220 * - filesystem unmounted and mounted as read-only
221 * - system power-cycle and filesystem mounted as read-only
222 * - filesystem or device errors leading to forced read-only
224 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
225 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
226 * A device operation in Paused or Running state can be canceled or resumed
227 * either by ioctl (Balance only) or when remounted as read-write.
228 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
232 DEFINE_MUTEX(uuid_mutex);
233 static LIST_HEAD(fs_uuids);
234 struct list_head *btrfs_get_fs_uuids(void)
240 * alloc_fs_devices - allocate struct btrfs_fs_devices
241 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
243 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
244 * The returned struct is not linked onto any lists and can be destroyed with
245 * kfree() right away.
247 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
249 struct btrfs_fs_devices *fs_devs;
251 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
253 return ERR_PTR(-ENOMEM);
255 mutex_init(&fs_devs->device_list_mutex);
257 INIT_LIST_HEAD(&fs_devs->devices);
258 INIT_LIST_HEAD(&fs_devs->resized_devices);
259 INIT_LIST_HEAD(&fs_devs->alloc_list);
260 INIT_LIST_HEAD(&fs_devs->fs_list);
262 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
267 void btrfs_free_device(struct btrfs_device *device)
269 rcu_string_free(device->name);
270 bio_put(device->flush_bio);
274 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
276 struct btrfs_device *device;
277 WARN_ON(fs_devices->opened);
278 while (!list_empty(&fs_devices->devices)) {
279 device = list_entry(fs_devices->devices.next,
280 struct btrfs_device, dev_list);
281 list_del(&device->dev_list);
282 btrfs_free_device(device);
287 static void btrfs_kobject_uevent(struct block_device *bdev,
288 enum kobject_action action)
292 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
294 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
296 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
297 &disk_to_dev(bdev->bd_disk)->kobj);
300 void __exit btrfs_cleanup_fs_uuids(void)
302 struct btrfs_fs_devices *fs_devices;
304 while (!list_empty(&fs_uuids)) {
305 fs_devices = list_entry(fs_uuids.next,
306 struct btrfs_fs_devices, fs_list);
307 list_del(&fs_devices->fs_list);
308 free_fs_devices(fs_devices);
313 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
314 * Returned struct is not linked onto any lists and must be destroyed using
317 static struct btrfs_device *__alloc_device(void)
319 struct btrfs_device *dev;
321 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
323 return ERR_PTR(-ENOMEM);
326 * Preallocate a bio that's always going to be used for flushing device
327 * barriers and matches the device lifespan
329 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
330 if (!dev->flush_bio) {
332 return ERR_PTR(-ENOMEM);
335 INIT_LIST_HEAD(&dev->dev_list);
336 INIT_LIST_HEAD(&dev->dev_alloc_list);
337 INIT_LIST_HEAD(&dev->resized_list);
339 spin_lock_init(&dev->io_lock);
341 atomic_set(&dev->reada_in_flight, 0);
342 atomic_set(&dev->dev_stats_ccnt, 0);
343 btrfs_device_data_ordered_init(dev);
344 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
345 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
351 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
354 * If devid and uuid are both specified, the match must be exact, otherwise
355 * only devid is used.
357 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
358 u64 devid, const u8 *uuid)
360 struct btrfs_device *dev;
362 list_for_each_entry(dev, &fs_devices->devices, dev_list) {
363 if (dev->devid == devid &&
364 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
371 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
373 struct btrfs_fs_devices *fs_devices;
375 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
376 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
383 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
384 int flush, struct block_device **bdev,
385 struct buffer_head **bh)
389 *bdev = blkdev_get_by_path(device_path, flags, holder);
392 ret = PTR_ERR(*bdev);
397 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
398 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
400 blkdev_put(*bdev, flags);
403 invalidate_bdev(*bdev);
404 *bh = btrfs_read_dev_super(*bdev);
407 blkdev_put(*bdev, flags);
419 static void requeue_list(struct btrfs_pending_bios *pending_bios,
420 struct bio *head, struct bio *tail)
423 struct bio *old_head;
425 old_head = pending_bios->head;
426 pending_bios->head = head;
427 if (pending_bios->tail)
428 tail->bi_next = old_head;
430 pending_bios->tail = tail;
434 * we try to collect pending bios for a device so we don't get a large
435 * number of procs sending bios down to the same device. This greatly
436 * improves the schedulers ability to collect and merge the bios.
438 * But, it also turns into a long list of bios to process and that is sure
439 * to eventually make the worker thread block. The solution here is to
440 * make some progress and then put this work struct back at the end of
441 * the list if the block device is congested. This way, multiple devices
442 * can make progress from a single worker thread.
444 static noinline void run_scheduled_bios(struct btrfs_device *device)
446 struct btrfs_fs_info *fs_info = device->fs_info;
448 struct backing_dev_info *bdi;
449 struct btrfs_pending_bios *pending_bios;
453 unsigned long num_run;
454 unsigned long batch_run = 0;
455 unsigned long last_waited = 0;
457 int sync_pending = 0;
458 struct blk_plug plug;
461 * this function runs all the bios we've collected for
462 * a particular device. We don't want to wander off to
463 * another device without first sending all of these down.
464 * So, setup a plug here and finish it off before we return
466 blk_start_plug(&plug);
468 bdi = device->bdev->bd_bdi;
471 spin_lock(&device->io_lock);
476 /* take all the bios off the list at once and process them
477 * later on (without the lock held). But, remember the
478 * tail and other pointers so the bios can be properly reinserted
479 * into the list if we hit congestion
481 if (!force_reg && device->pending_sync_bios.head) {
482 pending_bios = &device->pending_sync_bios;
485 pending_bios = &device->pending_bios;
489 pending = pending_bios->head;
490 tail = pending_bios->tail;
491 WARN_ON(pending && !tail);
494 * if pending was null this time around, no bios need processing
495 * at all and we can stop. Otherwise it'll loop back up again
496 * and do an additional check so no bios are missed.
498 * device->running_pending is used to synchronize with the
501 if (device->pending_sync_bios.head == NULL &&
502 device->pending_bios.head == NULL) {
504 device->running_pending = 0;
507 device->running_pending = 1;
510 pending_bios->head = NULL;
511 pending_bios->tail = NULL;
513 spin_unlock(&device->io_lock);
518 /* we want to work on both lists, but do more bios on the
519 * sync list than the regular list
522 pending_bios != &device->pending_sync_bios &&
523 device->pending_sync_bios.head) ||
524 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
525 device->pending_bios.head)) {
526 spin_lock(&device->io_lock);
527 requeue_list(pending_bios, pending, tail);
532 pending = pending->bi_next;
535 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
538 * if we're doing the sync list, record that our
539 * plug has some sync requests on it
541 * If we're doing the regular list and there are
542 * sync requests sitting around, unplug before
545 if (pending_bios == &device->pending_sync_bios) {
547 } else if (sync_pending) {
548 blk_finish_plug(&plug);
549 blk_start_plug(&plug);
553 btrfsic_submit_bio(cur);
560 * we made progress, there is more work to do and the bdi
561 * is now congested. Back off and let other work structs
564 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
565 fs_info->fs_devices->open_devices > 1) {
566 struct io_context *ioc;
568 ioc = current->io_context;
571 * the main goal here is that we don't want to
572 * block if we're going to be able to submit
573 * more requests without blocking.
575 * This code does two great things, it pokes into
576 * the elevator code from a filesystem _and_
577 * it makes assumptions about how batching works.
579 if (ioc && ioc->nr_batch_requests > 0 &&
580 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
582 ioc->last_waited == last_waited)) {
584 * we want to go through our batch of
585 * requests and stop. So, we copy out
586 * the ioc->last_waited time and test
587 * against it before looping
589 last_waited = ioc->last_waited;
593 spin_lock(&device->io_lock);
594 requeue_list(pending_bios, pending, tail);
595 device->running_pending = 1;
597 spin_unlock(&device->io_lock);
598 btrfs_queue_work(fs_info->submit_workers,
608 spin_lock(&device->io_lock);
609 if (device->pending_bios.head || device->pending_sync_bios.head)
611 spin_unlock(&device->io_lock);
614 blk_finish_plug(&plug);
617 static void pending_bios_fn(struct btrfs_work *work)
619 struct btrfs_device *device;
621 device = container_of(work, struct btrfs_device, work);
622 run_scheduled_bios(device);
626 * Search and remove all stale (devices which are not mounted) devices.
627 * When both inputs are NULL, it will search and release all stale devices.
628 * path: Optional. When provided will it release all unmounted devices
629 * matching this path only.
630 * skip_dev: Optional. Will skip this device when searching for the stale
633 static void btrfs_free_stale_devices(const char *path,
634 struct btrfs_device *skip_device)
636 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
637 struct btrfs_device *device, *tmp_device;
639 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
640 mutex_lock(&fs_devices->device_list_mutex);
641 if (fs_devices->opened) {
642 mutex_unlock(&fs_devices->device_list_mutex);
646 list_for_each_entry_safe(device, tmp_device,
647 &fs_devices->devices, dev_list) {
650 if (skip_device && skip_device == device)
652 if (path && !device->name)
657 not_found = strcmp(rcu_str_deref(device->name),
663 /* delete the stale device */
664 fs_devices->num_devices--;
665 list_del(&device->dev_list);
666 btrfs_free_device(device);
668 if (fs_devices->num_devices == 0)
671 mutex_unlock(&fs_devices->device_list_mutex);
672 if (fs_devices->num_devices == 0) {
673 btrfs_sysfs_remove_fsid(fs_devices);
674 list_del(&fs_devices->fs_list);
675 free_fs_devices(fs_devices);
680 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
681 struct btrfs_device *device, fmode_t flags,
684 struct request_queue *q;
685 struct block_device *bdev;
686 struct buffer_head *bh;
687 struct btrfs_super_block *disk_super;
696 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
701 disk_super = (struct btrfs_super_block *)bh->b_data;
702 devid = btrfs_stack_device_id(&disk_super->dev_item);
703 if (devid != device->devid)
706 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
709 device->generation = btrfs_super_generation(disk_super);
711 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
712 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
713 fs_devices->seeding = 1;
715 if (bdev_read_only(bdev))
716 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
718 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
721 q = bdev_get_queue(bdev);
722 if (!blk_queue_nonrot(q))
723 fs_devices->rotating = 1;
726 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
727 device->mode = flags;
729 fs_devices->open_devices++;
730 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
731 device->devid != BTRFS_DEV_REPLACE_DEVID) {
732 fs_devices->rw_devices++;
733 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
741 blkdev_put(bdev, flags);
747 * Add new device to list of registered devices
750 * device pointer which was just added or updated when successful
751 * error pointer when failed
753 static noinline struct btrfs_device *device_list_add(const char *path,
754 struct btrfs_super_block *disk_super,
755 bool *new_device_added)
757 struct btrfs_device *device;
758 struct btrfs_fs_devices *fs_devices;
759 struct rcu_string *name;
760 u64 found_transid = btrfs_super_generation(disk_super);
761 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
763 fs_devices = find_fsid(disk_super->fsid);
765 fs_devices = alloc_fs_devices(disk_super->fsid);
766 if (IS_ERR(fs_devices))
767 return ERR_CAST(fs_devices);
769 mutex_lock(&fs_devices->device_list_mutex);
770 list_add(&fs_devices->fs_list, &fs_uuids);
774 mutex_lock(&fs_devices->device_list_mutex);
775 device = find_device(fs_devices, devid,
776 disk_super->dev_item.uuid);
780 if (fs_devices->opened) {
781 mutex_unlock(&fs_devices->device_list_mutex);
782 return ERR_PTR(-EBUSY);
785 device = btrfs_alloc_device(NULL, &devid,
786 disk_super->dev_item.uuid);
787 if (IS_ERR(device)) {
788 mutex_unlock(&fs_devices->device_list_mutex);
789 /* we can safely leave the fs_devices entry around */
793 name = rcu_string_strdup(path, GFP_NOFS);
795 btrfs_free_device(device);
796 mutex_unlock(&fs_devices->device_list_mutex);
797 return ERR_PTR(-ENOMEM);
799 rcu_assign_pointer(device->name, name);
801 list_add_rcu(&device->dev_list, &fs_devices->devices);
802 fs_devices->num_devices++;
804 device->fs_devices = fs_devices;
805 *new_device_added = true;
807 if (disk_super->label[0])
808 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
809 disk_super->label, devid, found_transid, path);
811 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
812 disk_super->fsid, devid, found_transid, path);
814 } else if (!device->name || strcmp(device->name->str, path)) {
816 * When FS is already mounted.
817 * 1. If you are here and if the device->name is NULL that
818 * means this device was missing at time of FS mount.
819 * 2. If you are here and if the device->name is different
820 * from 'path' that means either
821 * a. The same device disappeared and reappeared with
823 * b. The missing-disk-which-was-replaced, has
826 * We must allow 1 and 2a above. But 2b would be a spurious
829 * Further in case of 1 and 2a above, the disk at 'path'
830 * would have missed some transaction when it was away and
831 * in case of 2a the stale bdev has to be updated as well.
832 * 2b must not be allowed at all time.
836 * For now, we do allow update to btrfs_fs_device through the
837 * btrfs dev scan cli after FS has been mounted. We're still
838 * tracking a problem where systems fail mount by subvolume id
839 * when we reject replacement on a mounted FS.
841 if (!fs_devices->opened && found_transid < device->generation) {
843 * That is if the FS is _not_ mounted and if you
844 * are here, that means there is more than one
845 * disk with same uuid and devid.We keep the one
846 * with larger generation number or the last-in if
847 * generation are equal.
849 mutex_unlock(&fs_devices->device_list_mutex);
850 return ERR_PTR(-EEXIST);
853 name = rcu_string_strdup(path, GFP_NOFS);
855 mutex_unlock(&fs_devices->device_list_mutex);
856 return ERR_PTR(-ENOMEM);
858 rcu_string_free(device->name);
859 rcu_assign_pointer(device->name, name);
860 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
861 fs_devices->missing_devices--;
862 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
867 * Unmount does not free the btrfs_device struct but would zero
868 * generation along with most of the other members. So just update
869 * it back. We need it to pick the disk with largest generation
872 if (!fs_devices->opened)
873 device->generation = found_transid;
875 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
877 mutex_unlock(&fs_devices->device_list_mutex);
881 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
883 struct btrfs_fs_devices *fs_devices;
884 struct btrfs_device *device;
885 struct btrfs_device *orig_dev;
887 fs_devices = alloc_fs_devices(orig->fsid);
888 if (IS_ERR(fs_devices))
891 mutex_lock(&orig->device_list_mutex);
892 fs_devices->total_devices = orig->total_devices;
894 /* We have held the volume lock, it is safe to get the devices. */
895 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
896 struct rcu_string *name;
898 device = btrfs_alloc_device(NULL, &orig_dev->devid,
904 * This is ok to do without rcu read locked because we hold the
905 * uuid mutex so nothing we touch in here is going to disappear.
907 if (orig_dev->name) {
908 name = rcu_string_strdup(orig_dev->name->str,
911 btrfs_free_device(device);
914 rcu_assign_pointer(device->name, name);
917 list_add(&device->dev_list, &fs_devices->devices);
918 device->fs_devices = fs_devices;
919 fs_devices->num_devices++;
921 mutex_unlock(&orig->device_list_mutex);
924 mutex_unlock(&orig->device_list_mutex);
925 free_fs_devices(fs_devices);
926 return ERR_PTR(-ENOMEM);
930 * After we have read the system tree and know devids belonging to
931 * this filesystem, remove the device which does not belong there.
933 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
935 struct btrfs_device *device, *next;
936 struct btrfs_device *latest_dev = NULL;
938 mutex_lock(&uuid_mutex);
940 /* This is the initialized path, it is safe to release the devices. */
941 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
942 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
943 &device->dev_state)) {
944 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
945 &device->dev_state) &&
947 device->generation > latest_dev->generation)) {
953 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
955 * In the first step, keep the device which has
956 * the correct fsid and the devid that is used
957 * for the dev_replace procedure.
958 * In the second step, the dev_replace state is
959 * read from the device tree and it is known
960 * whether the procedure is really active or
961 * not, which means whether this device is
962 * used or whether it should be removed.
964 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
965 &device->dev_state)) {
970 blkdev_put(device->bdev, device->mode);
972 fs_devices->open_devices--;
974 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
975 list_del_init(&device->dev_alloc_list);
976 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
977 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
979 fs_devices->rw_devices--;
981 list_del_init(&device->dev_list);
982 fs_devices->num_devices--;
983 btrfs_free_device(device);
986 if (fs_devices->seed) {
987 fs_devices = fs_devices->seed;
991 fs_devices->latest_bdev = latest_dev->bdev;
993 mutex_unlock(&uuid_mutex);
996 static void free_device_rcu(struct rcu_head *head)
998 struct btrfs_device *device;
1000 device = container_of(head, struct btrfs_device, rcu);
1001 btrfs_free_device(device);
1004 static void btrfs_close_bdev(struct btrfs_device *device)
1009 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1010 sync_blockdev(device->bdev);
1011 invalidate_bdev(device->bdev);
1014 blkdev_put(device->bdev, device->mode);
1017 static void btrfs_close_one_device(struct btrfs_device *device)
1019 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1020 struct btrfs_device *new_device;
1021 struct rcu_string *name;
1024 fs_devices->open_devices--;
1026 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1027 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1028 list_del_init(&device->dev_alloc_list);
1029 fs_devices->rw_devices--;
1032 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1033 fs_devices->missing_devices--;
1035 btrfs_close_bdev(device);
1037 new_device = btrfs_alloc_device(NULL, &device->devid,
1039 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1041 /* Safe because we are under uuid_mutex */
1043 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1044 BUG_ON(!name); /* -ENOMEM */
1045 rcu_assign_pointer(new_device->name, name);
1048 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1049 new_device->fs_devices = device->fs_devices;
1051 call_rcu(&device->rcu, free_device_rcu);
1054 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1056 struct btrfs_device *device, *tmp;
1058 if (--fs_devices->opened > 0)
1061 mutex_lock(&fs_devices->device_list_mutex);
1062 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1063 btrfs_close_one_device(device);
1065 mutex_unlock(&fs_devices->device_list_mutex);
1067 WARN_ON(fs_devices->open_devices);
1068 WARN_ON(fs_devices->rw_devices);
1069 fs_devices->opened = 0;
1070 fs_devices->seeding = 0;
1075 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1077 struct btrfs_fs_devices *seed_devices = NULL;
1080 mutex_lock(&uuid_mutex);
1081 ret = close_fs_devices(fs_devices);
1082 if (!fs_devices->opened) {
1083 seed_devices = fs_devices->seed;
1084 fs_devices->seed = NULL;
1086 mutex_unlock(&uuid_mutex);
1088 while (seed_devices) {
1089 fs_devices = seed_devices;
1090 seed_devices = fs_devices->seed;
1091 close_fs_devices(fs_devices);
1092 free_fs_devices(fs_devices);
1097 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1098 fmode_t flags, void *holder)
1100 struct btrfs_device *device;
1101 struct btrfs_device *latest_dev = NULL;
1104 flags |= FMODE_EXCL;
1106 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1107 /* Just open everything we can; ignore failures here */
1108 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1112 device->generation > latest_dev->generation)
1113 latest_dev = device;
1115 if (fs_devices->open_devices == 0) {
1119 fs_devices->opened = 1;
1120 fs_devices->latest_bdev = latest_dev->bdev;
1121 fs_devices->total_rw_bytes = 0;
1126 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1128 struct btrfs_device *dev1, *dev2;
1130 dev1 = list_entry(a, struct btrfs_device, dev_list);
1131 dev2 = list_entry(b, struct btrfs_device, dev_list);
1133 if (dev1->devid < dev2->devid)
1135 else if (dev1->devid > dev2->devid)
1140 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1141 fmode_t flags, void *holder)
1145 lockdep_assert_held(&uuid_mutex);
1147 mutex_lock(&fs_devices->device_list_mutex);
1148 if (fs_devices->opened) {
1149 fs_devices->opened++;
1152 list_sort(NULL, &fs_devices->devices, devid_cmp);
1153 ret = open_fs_devices(fs_devices, flags, holder);
1155 mutex_unlock(&fs_devices->device_list_mutex);
1160 static void btrfs_release_disk_super(struct page *page)
1166 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1168 struct btrfs_super_block **disk_super)
1173 /* make sure our super fits in the device */
1174 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1177 /* make sure our super fits in the page */
1178 if (sizeof(**disk_super) > PAGE_SIZE)
1181 /* make sure our super doesn't straddle pages on disk */
1182 index = bytenr >> PAGE_SHIFT;
1183 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1186 /* pull in the page with our super */
1187 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1190 if (IS_ERR_OR_NULL(*page))
1195 /* align our pointer to the offset of the super block */
1196 *disk_super = p + (bytenr & ~PAGE_MASK);
1198 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1199 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1200 btrfs_release_disk_super(*page);
1204 if ((*disk_super)->label[0] &&
1205 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1206 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1212 * Look for a btrfs signature on a device. This may be called out of the mount path
1213 * and we are not allowed to call set_blocksize during the scan. The superblock
1214 * is read via pagecache
1216 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1219 struct btrfs_super_block *disk_super;
1220 bool new_device_added = false;
1221 struct btrfs_device *device = NULL;
1222 struct block_device *bdev;
1226 lockdep_assert_held(&uuid_mutex);
1229 * we would like to check all the supers, but that would make
1230 * a btrfs mount succeed after a mkfs from a different FS.
1231 * So, we need to add a special mount option to scan for
1232 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1234 bytenr = btrfs_sb_offset(0);
1235 flags |= FMODE_EXCL;
1237 bdev = blkdev_get_by_path(path, flags, holder);
1239 return ERR_CAST(bdev);
1241 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1242 device = ERR_PTR(-EINVAL);
1243 goto error_bdev_put;
1246 device = device_list_add(path, disk_super, &new_device_added);
1247 if (!IS_ERR(device)) {
1248 if (new_device_added)
1249 btrfs_free_stale_devices(path, device);
1252 btrfs_release_disk_super(page);
1255 blkdev_put(bdev, flags);
1260 static int contains_pending_extent(struct btrfs_transaction *transaction,
1261 struct btrfs_device *device,
1262 u64 *start, u64 len)
1264 struct btrfs_fs_info *fs_info = device->fs_info;
1265 struct extent_map *em;
1266 struct list_head *search_list = &fs_info->pinned_chunks;
1268 u64 physical_start = *start;
1271 search_list = &transaction->pending_chunks;
1273 list_for_each_entry(em, search_list, list) {
1274 struct map_lookup *map;
1277 map = em->map_lookup;
1278 for (i = 0; i < map->num_stripes; i++) {
1281 if (map->stripes[i].dev != device)
1283 if (map->stripes[i].physical >= physical_start + len ||
1284 map->stripes[i].physical + em->orig_block_len <=
1288 * Make sure that while processing the pinned list we do
1289 * not override our *start with a lower value, because
1290 * we can have pinned chunks that fall within this
1291 * device hole and that have lower physical addresses
1292 * than the pending chunks we processed before. If we
1293 * do not take this special care we can end up getting
1294 * 2 pending chunks that start at the same physical
1295 * device offsets because the end offset of a pinned
1296 * chunk can be equal to the start offset of some
1299 end = map->stripes[i].physical + em->orig_block_len;
1306 if (search_list != &fs_info->pinned_chunks) {
1307 search_list = &fs_info->pinned_chunks;
1316 * find_free_dev_extent_start - find free space in the specified device
1317 * @device: the device which we search the free space in
1318 * @num_bytes: the size of the free space that we need
1319 * @search_start: the position from which to begin the search
1320 * @start: store the start of the free space.
1321 * @len: the size of the free space. that we find, or the size
1322 * of the max free space if we don't find suitable free space
1324 * this uses a pretty simple search, the expectation is that it is
1325 * called very infrequently and that a given device has a small number
1328 * @start is used to store the start of the free space if we find. But if we
1329 * don't find suitable free space, it will be used to store the start position
1330 * of the max free space.
1332 * @len is used to store the size of the free space that we find.
1333 * But if we don't find suitable free space, it is used to store the size of
1334 * the max free space.
1336 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1337 struct btrfs_device *device, u64 num_bytes,
1338 u64 search_start, u64 *start, u64 *len)
1340 struct btrfs_fs_info *fs_info = device->fs_info;
1341 struct btrfs_root *root = fs_info->dev_root;
1342 struct btrfs_key key;
1343 struct btrfs_dev_extent *dev_extent;
1344 struct btrfs_path *path;
1349 u64 search_end = device->total_bytes;
1352 struct extent_buffer *l;
1355 * We don't want to overwrite the superblock on the drive nor any area
1356 * used by the boot loader (grub for example), so we make sure to start
1357 * at an offset of at least 1MB.
1359 search_start = max_t(u64, search_start, SZ_1M);
1361 path = btrfs_alloc_path();
1365 max_hole_start = search_start;
1369 if (search_start >= search_end ||
1370 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1375 path->reada = READA_FORWARD;
1376 path->search_commit_root = 1;
1377 path->skip_locking = 1;
1379 key.objectid = device->devid;
1380 key.offset = search_start;
1381 key.type = BTRFS_DEV_EXTENT_KEY;
1383 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1387 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1394 slot = path->slots[0];
1395 if (slot >= btrfs_header_nritems(l)) {
1396 ret = btrfs_next_leaf(root, path);
1404 btrfs_item_key_to_cpu(l, &key, slot);
1406 if (key.objectid < device->devid)
1409 if (key.objectid > device->devid)
1412 if (key.type != BTRFS_DEV_EXTENT_KEY)
1415 if (key.offset > search_start) {
1416 hole_size = key.offset - search_start;
1419 * Have to check before we set max_hole_start, otherwise
1420 * we could end up sending back this offset anyway.
1422 if (contains_pending_extent(transaction, device,
1425 if (key.offset >= search_start) {
1426 hole_size = key.offset - search_start;
1433 if (hole_size > max_hole_size) {
1434 max_hole_start = search_start;
1435 max_hole_size = hole_size;
1439 * If this free space is greater than which we need,
1440 * it must be the max free space that we have found
1441 * until now, so max_hole_start must point to the start
1442 * of this free space and the length of this free space
1443 * is stored in max_hole_size. Thus, we return
1444 * max_hole_start and max_hole_size and go back to the
1447 if (hole_size >= num_bytes) {
1453 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1454 extent_end = key.offset + btrfs_dev_extent_length(l,
1456 if (extent_end > search_start)
1457 search_start = extent_end;
1464 * At this point, search_start should be the end of
1465 * allocated dev extents, and when shrinking the device,
1466 * search_end may be smaller than search_start.
1468 if (search_end > search_start) {
1469 hole_size = search_end - search_start;
1471 if (contains_pending_extent(transaction, device, &search_start,
1473 btrfs_release_path(path);
1477 if (hole_size > max_hole_size) {
1478 max_hole_start = search_start;
1479 max_hole_size = hole_size;
1484 if (max_hole_size < num_bytes)
1490 btrfs_free_path(path);
1491 *start = max_hole_start;
1493 *len = max_hole_size;
1497 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1498 struct btrfs_device *device, u64 num_bytes,
1499 u64 *start, u64 *len)
1501 /* FIXME use last free of some kind */
1502 return find_free_dev_extent_start(trans->transaction, device,
1503 num_bytes, 0, start, len);
1506 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1507 struct btrfs_device *device,
1508 u64 start, u64 *dev_extent_len)
1510 struct btrfs_fs_info *fs_info = device->fs_info;
1511 struct btrfs_root *root = fs_info->dev_root;
1513 struct btrfs_path *path;
1514 struct btrfs_key key;
1515 struct btrfs_key found_key;
1516 struct extent_buffer *leaf = NULL;
1517 struct btrfs_dev_extent *extent = NULL;
1519 path = btrfs_alloc_path();
1523 key.objectid = device->devid;
1525 key.type = BTRFS_DEV_EXTENT_KEY;
1527 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1529 ret = btrfs_previous_item(root, path, key.objectid,
1530 BTRFS_DEV_EXTENT_KEY);
1533 leaf = path->nodes[0];
1534 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1535 extent = btrfs_item_ptr(leaf, path->slots[0],
1536 struct btrfs_dev_extent);
1537 BUG_ON(found_key.offset > start || found_key.offset +
1538 btrfs_dev_extent_length(leaf, extent) < start);
1540 btrfs_release_path(path);
1542 } else if (ret == 0) {
1543 leaf = path->nodes[0];
1544 extent = btrfs_item_ptr(leaf, path->slots[0],
1545 struct btrfs_dev_extent);
1547 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1551 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1553 ret = btrfs_del_item(trans, root, path);
1555 btrfs_handle_fs_error(fs_info, ret,
1556 "Failed to remove dev extent item");
1558 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1561 btrfs_free_path(path);
1565 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1566 struct btrfs_device *device,
1567 u64 chunk_offset, u64 start, u64 num_bytes)
1570 struct btrfs_path *path;
1571 struct btrfs_fs_info *fs_info = device->fs_info;
1572 struct btrfs_root *root = fs_info->dev_root;
1573 struct btrfs_dev_extent *extent;
1574 struct extent_buffer *leaf;
1575 struct btrfs_key key;
1577 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1578 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1579 path = btrfs_alloc_path();
1583 key.objectid = device->devid;
1585 key.type = BTRFS_DEV_EXTENT_KEY;
1586 ret = btrfs_insert_empty_item(trans, root, path, &key,
1591 leaf = path->nodes[0];
1592 extent = btrfs_item_ptr(leaf, path->slots[0],
1593 struct btrfs_dev_extent);
1594 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1595 BTRFS_CHUNK_TREE_OBJECTID);
1596 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1597 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1598 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1600 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1601 btrfs_mark_buffer_dirty(leaf);
1603 btrfs_free_path(path);
1607 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1609 struct extent_map_tree *em_tree;
1610 struct extent_map *em;
1614 em_tree = &fs_info->mapping_tree.map_tree;
1615 read_lock(&em_tree->lock);
1616 n = rb_last(&em_tree->map);
1618 em = rb_entry(n, struct extent_map, rb_node);
1619 ret = em->start + em->len;
1621 read_unlock(&em_tree->lock);
1626 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1630 struct btrfs_key key;
1631 struct btrfs_key found_key;
1632 struct btrfs_path *path;
1634 path = btrfs_alloc_path();
1638 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1639 key.type = BTRFS_DEV_ITEM_KEY;
1640 key.offset = (u64)-1;
1642 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1646 BUG_ON(ret == 0); /* Corruption */
1648 ret = btrfs_previous_item(fs_info->chunk_root, path,
1649 BTRFS_DEV_ITEMS_OBJECTID,
1650 BTRFS_DEV_ITEM_KEY);
1654 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1656 *devid_ret = found_key.offset + 1;
1660 btrfs_free_path(path);
1665 * the device information is stored in the chunk root
1666 * the btrfs_device struct should be fully filled in
1668 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1669 struct btrfs_device *device)
1672 struct btrfs_path *path;
1673 struct btrfs_dev_item *dev_item;
1674 struct extent_buffer *leaf;
1675 struct btrfs_key key;
1678 path = btrfs_alloc_path();
1682 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1683 key.type = BTRFS_DEV_ITEM_KEY;
1684 key.offset = device->devid;
1686 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1687 &key, sizeof(*dev_item));
1691 leaf = path->nodes[0];
1692 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1694 btrfs_set_device_id(leaf, dev_item, device->devid);
1695 btrfs_set_device_generation(leaf, dev_item, 0);
1696 btrfs_set_device_type(leaf, dev_item, device->type);
1697 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1698 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1699 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1700 btrfs_set_device_total_bytes(leaf, dev_item,
1701 btrfs_device_get_disk_total_bytes(device));
1702 btrfs_set_device_bytes_used(leaf, dev_item,
1703 btrfs_device_get_bytes_used(device));
1704 btrfs_set_device_group(leaf, dev_item, 0);
1705 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1706 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1707 btrfs_set_device_start_offset(leaf, dev_item, 0);
1709 ptr = btrfs_device_uuid(dev_item);
1710 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1711 ptr = btrfs_device_fsid(dev_item);
1712 write_extent_buffer(leaf, trans->fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1713 btrfs_mark_buffer_dirty(leaf);
1717 btrfs_free_path(path);
1722 * Function to update ctime/mtime for a given device path.
1723 * Mainly used for ctime/mtime based probe like libblkid.
1725 static void update_dev_time(const char *path_name)
1729 filp = filp_open(path_name, O_RDWR, 0);
1732 file_update_time(filp);
1733 filp_close(filp, NULL);
1736 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1737 struct btrfs_device *device)
1739 struct btrfs_root *root = fs_info->chunk_root;
1741 struct btrfs_path *path;
1742 struct btrfs_key key;
1743 struct btrfs_trans_handle *trans;
1745 path = btrfs_alloc_path();
1749 trans = btrfs_start_transaction(root, 0);
1750 if (IS_ERR(trans)) {
1751 btrfs_free_path(path);
1752 return PTR_ERR(trans);
1754 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1755 key.type = BTRFS_DEV_ITEM_KEY;
1756 key.offset = device->devid;
1758 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1762 btrfs_abort_transaction(trans, ret);
1763 btrfs_end_transaction(trans);
1767 ret = btrfs_del_item(trans, root, path);
1769 btrfs_abort_transaction(trans, ret);
1770 btrfs_end_transaction(trans);
1774 btrfs_free_path(path);
1776 ret = btrfs_commit_transaction(trans);
1781 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1782 * filesystem. It's up to the caller to adjust that number regarding eg. device
1785 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1793 seq = read_seqbegin(&fs_info->profiles_lock);
1795 all_avail = fs_info->avail_data_alloc_bits |
1796 fs_info->avail_system_alloc_bits |
1797 fs_info->avail_metadata_alloc_bits;
1798 } while (read_seqretry(&fs_info->profiles_lock, seq));
1800 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1801 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1804 if (num_devices < btrfs_raid_array[i].devs_min) {
1805 int ret = btrfs_raid_array[i].mindev_error;
1815 static struct btrfs_device * btrfs_find_next_active_device(
1816 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1818 struct btrfs_device *next_device;
1820 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1821 if (next_device != device &&
1822 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1823 && next_device->bdev)
1831 * Helper function to check if the given device is part of s_bdev / latest_bdev
1832 * and replace it with the provided or the next active device, in the context
1833 * where this function called, there should be always be another device (or
1834 * this_dev) which is active.
1836 void btrfs_assign_next_active_device(struct btrfs_device *device,
1837 struct btrfs_device *this_dev)
1839 struct btrfs_fs_info *fs_info = device->fs_info;
1840 struct btrfs_device *next_device;
1843 next_device = this_dev;
1845 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1847 ASSERT(next_device);
1849 if (fs_info->sb->s_bdev &&
1850 (fs_info->sb->s_bdev == device->bdev))
1851 fs_info->sb->s_bdev = next_device->bdev;
1853 if (fs_info->fs_devices->latest_bdev == device->bdev)
1854 fs_info->fs_devices->latest_bdev = next_device->bdev;
1857 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1860 struct btrfs_device *device;
1861 struct btrfs_fs_devices *cur_devices;
1862 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1866 mutex_lock(&uuid_mutex);
1868 num_devices = fs_devices->num_devices;
1869 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1870 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1871 WARN_ON(num_devices < 1);
1874 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1876 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1880 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1885 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1886 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1890 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1891 fs_info->fs_devices->rw_devices == 1) {
1892 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1896 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1897 mutex_lock(&fs_info->chunk_mutex);
1898 list_del_init(&device->dev_alloc_list);
1899 device->fs_devices->rw_devices--;
1900 mutex_unlock(&fs_info->chunk_mutex);
1903 mutex_unlock(&uuid_mutex);
1904 ret = btrfs_shrink_device(device, 0);
1905 mutex_lock(&uuid_mutex);
1910 * TODO: the superblock still includes this device in its num_devices
1911 * counter although write_all_supers() is not locked out. This
1912 * could give a filesystem state which requires a degraded mount.
1914 ret = btrfs_rm_dev_item(fs_info, device);
1918 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
1919 btrfs_scrub_cancel_dev(fs_info, device);
1922 * the device list mutex makes sure that we don't change
1923 * the device list while someone else is writing out all
1924 * the device supers. Whoever is writing all supers, should
1925 * lock the device list mutex before getting the number of
1926 * devices in the super block (super_copy). Conversely,
1927 * whoever updates the number of devices in the super block
1928 * (super_copy) should hold the device list mutex.
1932 * In normal cases the cur_devices == fs_devices. But in case
1933 * of deleting a seed device, the cur_devices should point to
1934 * its own fs_devices listed under the fs_devices->seed.
1936 cur_devices = device->fs_devices;
1937 mutex_lock(&fs_devices->device_list_mutex);
1938 list_del_rcu(&device->dev_list);
1940 cur_devices->num_devices--;
1941 cur_devices->total_devices--;
1942 /* Update total_devices of the parent fs_devices if it's seed */
1943 if (cur_devices != fs_devices)
1944 fs_devices->total_devices--;
1946 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1947 cur_devices->missing_devices--;
1949 btrfs_assign_next_active_device(device, NULL);
1952 cur_devices->open_devices--;
1953 /* remove sysfs entry */
1954 btrfs_sysfs_rm_device_link(fs_devices, device);
1957 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1958 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
1959 mutex_unlock(&fs_devices->device_list_mutex);
1962 * at this point, the device is zero sized and detached from
1963 * the devices list. All that's left is to zero out the old
1964 * supers and free the device.
1966 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
1967 btrfs_scratch_superblocks(device->bdev, device->name->str);
1969 btrfs_close_bdev(device);
1970 call_rcu(&device->rcu, free_device_rcu);
1972 if (cur_devices->open_devices == 0) {
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 close_fs_devices(cur_devices);
1982 free_fs_devices(cur_devices);
1986 mutex_unlock(&uuid_mutex);
1990 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1991 mutex_lock(&fs_info->chunk_mutex);
1992 list_add(&device->dev_alloc_list,
1993 &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_device *srcdev)
2002 struct btrfs_fs_devices *fs_devices;
2004 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2007 * in case of fs with no seed, srcdev->fs_devices will point
2008 * to fs_devices of fs_info. However when the dev being replaced is
2009 * a seed dev it will point to the seed's local fs_devices. In short
2010 * srcdev will have its correct fs_devices in both the cases.
2012 fs_devices = srcdev->fs_devices;
2014 list_del_rcu(&srcdev->dev_list);
2015 list_del(&srcdev->dev_alloc_list);
2016 fs_devices->num_devices--;
2017 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2018 fs_devices->missing_devices--;
2020 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2021 fs_devices->rw_devices--;
2024 fs_devices->open_devices--;
2027 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2028 struct btrfs_device *srcdev)
2030 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2032 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2033 /* zero out the old super if it is writable */
2034 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2037 btrfs_close_bdev(srcdev);
2038 call_rcu(&srcdev->rcu, free_device_rcu);
2040 /* if this is no devs we rather delete the fs_devices */
2041 if (!fs_devices->num_devices) {
2042 struct btrfs_fs_devices *tmp_fs_devices;
2045 * On a mounted FS, num_devices can't be zero unless it's a
2046 * seed. In case of a seed device being replaced, the replace
2047 * target added to the sprout FS, so there will be no more
2048 * device left under the seed FS.
2050 ASSERT(fs_devices->seeding);
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 close_fs_devices(fs_devices);
2062 free_fs_devices(fs_devices);
2066 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2068 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2071 mutex_lock(&fs_devices->device_list_mutex);
2073 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2076 fs_devices->open_devices--;
2078 fs_devices->num_devices--;
2080 btrfs_assign_next_active_device(tgtdev, NULL);
2082 list_del_rcu(&tgtdev->dev_list);
2084 mutex_unlock(&fs_devices->device_list_mutex);
2087 * The update_dev_time() with in btrfs_scratch_superblocks()
2088 * may lead to a call to btrfs_show_devname() which will try
2089 * to hold device_list_mutex. And here this device
2090 * is already out of device list, so we don't have to hold
2091 * the device_list_mutex lock.
2093 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2095 btrfs_close_bdev(tgtdev);
2096 call_rcu(&tgtdev->rcu, free_device_rcu);
2099 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2100 const char *device_path,
2101 struct btrfs_device **device)
2104 struct btrfs_super_block *disk_super;
2107 struct block_device *bdev;
2108 struct buffer_head *bh;
2111 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2112 fs_info->bdev_holder, 0, &bdev, &bh);
2115 disk_super = (struct btrfs_super_block *)bh->b_data;
2116 devid = btrfs_stack_device_id(&disk_super->dev_item);
2117 dev_uuid = disk_super->dev_item.uuid;
2118 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2122 blkdev_put(bdev, FMODE_READ);
2126 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2127 const char *device_path,
2128 struct btrfs_device **device)
2131 if (strcmp(device_path, "missing") == 0) {
2132 struct list_head *devices;
2133 struct btrfs_device *tmp;
2135 devices = &fs_info->fs_devices->devices;
2136 list_for_each_entry(tmp, devices, dev_list) {
2137 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2138 &tmp->dev_state) && !tmp->bdev) {
2145 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2149 return btrfs_find_device_by_path(fs_info, device_path, device);
2154 * Lookup a device given by device id, or the path if the id is 0.
2156 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2157 const char *devpath,
2158 struct btrfs_device **device)
2164 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2168 if (!devpath || !devpath[0])
2171 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2178 * does all the dirty work required for changing file system's UUID.
2180 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2182 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2183 struct btrfs_fs_devices *old_devices;
2184 struct btrfs_fs_devices *seed_devices;
2185 struct btrfs_super_block *disk_super = fs_info->super_copy;
2186 struct btrfs_device *device;
2189 lockdep_assert_held(&uuid_mutex);
2190 if (!fs_devices->seeding)
2193 seed_devices = alloc_fs_devices(NULL);
2194 if (IS_ERR(seed_devices))
2195 return PTR_ERR(seed_devices);
2197 old_devices = clone_fs_devices(fs_devices);
2198 if (IS_ERR(old_devices)) {
2199 kfree(seed_devices);
2200 return PTR_ERR(old_devices);
2203 list_add(&old_devices->fs_list, &fs_uuids);
2205 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2206 seed_devices->opened = 1;
2207 INIT_LIST_HEAD(&seed_devices->devices);
2208 INIT_LIST_HEAD(&seed_devices->alloc_list);
2209 mutex_init(&seed_devices->device_list_mutex);
2211 mutex_lock(&fs_devices->device_list_mutex);
2212 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2214 list_for_each_entry(device, &seed_devices->devices, dev_list)
2215 device->fs_devices = seed_devices;
2217 mutex_lock(&fs_info->chunk_mutex);
2218 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2219 mutex_unlock(&fs_info->chunk_mutex);
2221 fs_devices->seeding = 0;
2222 fs_devices->num_devices = 0;
2223 fs_devices->open_devices = 0;
2224 fs_devices->missing_devices = 0;
2225 fs_devices->rotating = 0;
2226 fs_devices->seed = seed_devices;
2228 generate_random_uuid(fs_devices->fsid);
2229 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2230 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2231 mutex_unlock(&fs_devices->device_list_mutex);
2233 super_flags = btrfs_super_flags(disk_super) &
2234 ~BTRFS_SUPER_FLAG_SEEDING;
2235 btrfs_set_super_flags(disk_super, super_flags);
2241 * Store the expected generation for seed devices in device items.
2243 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2244 struct btrfs_fs_info *fs_info)
2246 struct btrfs_root *root = fs_info->chunk_root;
2247 struct btrfs_path *path;
2248 struct extent_buffer *leaf;
2249 struct btrfs_dev_item *dev_item;
2250 struct btrfs_device *device;
2251 struct btrfs_key key;
2252 u8 fs_uuid[BTRFS_FSID_SIZE];
2253 u8 dev_uuid[BTRFS_UUID_SIZE];
2257 path = btrfs_alloc_path();
2261 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2263 key.type = BTRFS_DEV_ITEM_KEY;
2266 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2270 leaf = path->nodes[0];
2272 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2273 ret = btrfs_next_leaf(root, path);
2278 leaf = path->nodes[0];
2279 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2280 btrfs_release_path(path);
2284 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2285 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2286 key.type != BTRFS_DEV_ITEM_KEY)
2289 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2290 struct btrfs_dev_item);
2291 devid = btrfs_device_id(leaf, dev_item);
2292 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2294 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2296 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2297 BUG_ON(!device); /* Logic error */
2299 if (device->fs_devices->seeding) {
2300 btrfs_set_device_generation(leaf, dev_item,
2301 device->generation);
2302 btrfs_mark_buffer_dirty(leaf);
2310 btrfs_free_path(path);
2314 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2316 struct btrfs_root *root = fs_info->dev_root;
2317 struct request_queue *q;
2318 struct btrfs_trans_handle *trans;
2319 struct btrfs_device *device;
2320 struct block_device *bdev;
2321 struct super_block *sb = fs_info->sb;
2322 struct rcu_string *name;
2323 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2325 int seeding_dev = 0;
2327 bool unlocked = false;
2329 if (sb_rdonly(sb) && !fs_devices->seeding)
2332 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2333 fs_info->bdev_holder);
2335 return PTR_ERR(bdev);
2337 if (fs_devices->seeding) {
2339 down_write(&sb->s_umount);
2340 mutex_lock(&uuid_mutex);
2343 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2345 mutex_lock(&fs_devices->device_list_mutex);
2346 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2347 if (device->bdev == bdev) {
2350 &fs_devices->device_list_mutex);
2354 mutex_unlock(&fs_devices->device_list_mutex);
2356 device = btrfs_alloc_device(fs_info, NULL, NULL);
2357 if (IS_ERR(device)) {
2358 /* we can safely leave the fs_devices entry around */
2359 ret = PTR_ERR(device);
2363 name = rcu_string_strdup(device_path, GFP_KERNEL);
2366 goto error_free_device;
2368 rcu_assign_pointer(device->name, name);
2370 trans = btrfs_start_transaction(root, 0);
2371 if (IS_ERR(trans)) {
2372 ret = PTR_ERR(trans);
2373 goto error_free_device;
2376 q = bdev_get_queue(bdev);
2377 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2378 device->generation = trans->transid;
2379 device->io_width = fs_info->sectorsize;
2380 device->io_align = fs_info->sectorsize;
2381 device->sector_size = fs_info->sectorsize;
2382 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2383 fs_info->sectorsize);
2384 device->disk_total_bytes = device->total_bytes;
2385 device->commit_total_bytes = device->total_bytes;
2386 device->fs_info = fs_info;
2387 device->bdev = bdev;
2388 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2389 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2390 device->mode = FMODE_EXCL;
2391 device->dev_stats_valid = 1;
2392 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2395 sb->s_flags &= ~SB_RDONLY;
2396 ret = btrfs_prepare_sprout(fs_info);
2398 btrfs_abort_transaction(trans, ret);
2403 device->fs_devices = fs_devices;
2405 mutex_lock(&fs_devices->device_list_mutex);
2406 mutex_lock(&fs_info->chunk_mutex);
2407 list_add_rcu(&device->dev_list, &fs_devices->devices);
2408 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2409 fs_devices->num_devices++;
2410 fs_devices->open_devices++;
2411 fs_devices->rw_devices++;
2412 fs_devices->total_devices++;
2413 fs_devices->total_rw_bytes += device->total_bytes;
2415 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2417 if (!blk_queue_nonrot(q))
2418 fs_devices->rotating = 1;
2420 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2421 btrfs_set_super_total_bytes(fs_info->super_copy,
2422 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2424 tmp = btrfs_super_num_devices(fs_info->super_copy);
2425 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2427 /* add sysfs device entry */
2428 btrfs_sysfs_add_device_link(fs_devices, device);
2431 * we've got more storage, clear any full flags on the space
2434 btrfs_clear_space_info_full(fs_info);
2436 mutex_unlock(&fs_info->chunk_mutex);
2437 mutex_unlock(&fs_devices->device_list_mutex);
2440 mutex_lock(&fs_info->chunk_mutex);
2441 ret = init_first_rw_device(trans, fs_info);
2442 mutex_unlock(&fs_info->chunk_mutex);
2444 btrfs_abort_transaction(trans, ret);
2449 ret = btrfs_add_dev_item(trans, device);
2451 btrfs_abort_transaction(trans, ret);
2456 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2458 ret = btrfs_finish_sprout(trans, fs_info);
2460 btrfs_abort_transaction(trans, ret);
2464 /* Sprouting would change fsid of the mounted root,
2465 * so rename the fsid on the sysfs
2467 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2469 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2471 "sysfs: failed to create fsid for sprout");
2474 ret = btrfs_commit_transaction(trans);
2477 mutex_unlock(&uuid_mutex);
2478 up_write(&sb->s_umount);
2481 if (ret) /* transaction commit */
2484 ret = btrfs_relocate_sys_chunks(fs_info);
2486 btrfs_handle_fs_error(fs_info, ret,
2487 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2488 trans = btrfs_attach_transaction(root);
2489 if (IS_ERR(trans)) {
2490 if (PTR_ERR(trans) == -ENOENT)
2492 ret = PTR_ERR(trans);
2496 ret = btrfs_commit_transaction(trans);
2499 /* Update ctime/mtime for libblkid */
2500 update_dev_time(device_path);
2504 btrfs_sysfs_rm_device_link(fs_devices, device);
2507 sb->s_flags |= SB_RDONLY;
2509 btrfs_end_transaction(trans);
2511 btrfs_free_device(device);
2513 blkdev_put(bdev, FMODE_EXCL);
2514 if (seeding_dev && !unlocked) {
2515 mutex_unlock(&uuid_mutex);
2516 up_write(&sb->s_umount);
2521 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2522 struct btrfs_device *device)
2525 struct btrfs_path *path;
2526 struct btrfs_root *root = device->fs_info->chunk_root;
2527 struct btrfs_dev_item *dev_item;
2528 struct extent_buffer *leaf;
2529 struct btrfs_key key;
2531 path = btrfs_alloc_path();
2535 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2536 key.type = BTRFS_DEV_ITEM_KEY;
2537 key.offset = device->devid;
2539 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2548 leaf = path->nodes[0];
2549 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2551 btrfs_set_device_id(leaf, dev_item, device->devid);
2552 btrfs_set_device_type(leaf, dev_item, device->type);
2553 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2554 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2555 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2556 btrfs_set_device_total_bytes(leaf, dev_item,
2557 btrfs_device_get_disk_total_bytes(device));
2558 btrfs_set_device_bytes_used(leaf, dev_item,
2559 btrfs_device_get_bytes_used(device));
2560 btrfs_mark_buffer_dirty(leaf);
2563 btrfs_free_path(path);
2567 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2568 struct btrfs_device *device, u64 new_size)
2570 struct btrfs_fs_info *fs_info = device->fs_info;
2571 struct btrfs_super_block *super_copy = fs_info->super_copy;
2572 struct btrfs_fs_devices *fs_devices;
2576 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2579 new_size = round_down(new_size, fs_info->sectorsize);
2581 mutex_lock(&fs_info->chunk_mutex);
2582 old_total = btrfs_super_total_bytes(super_copy);
2583 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2585 if (new_size <= device->total_bytes ||
2586 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2587 mutex_unlock(&fs_info->chunk_mutex);
2591 fs_devices = fs_info->fs_devices;
2593 btrfs_set_super_total_bytes(super_copy,
2594 round_down(old_total + diff, fs_info->sectorsize));
2595 device->fs_devices->total_rw_bytes += diff;
2597 btrfs_device_set_total_bytes(device, new_size);
2598 btrfs_device_set_disk_total_bytes(device, new_size);
2599 btrfs_clear_space_info_full(device->fs_info);
2600 if (list_empty(&device->resized_list))
2601 list_add_tail(&device->resized_list,
2602 &fs_devices->resized_devices);
2603 mutex_unlock(&fs_info->chunk_mutex);
2605 return btrfs_update_device(trans, device);
2608 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2610 struct btrfs_fs_info *fs_info = trans->fs_info;
2611 struct btrfs_root *root = fs_info->chunk_root;
2613 struct btrfs_path *path;
2614 struct btrfs_key key;
2616 path = btrfs_alloc_path();
2620 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2621 key.offset = chunk_offset;
2622 key.type = BTRFS_CHUNK_ITEM_KEY;
2624 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2627 else if (ret > 0) { /* Logic error or corruption */
2628 btrfs_handle_fs_error(fs_info, -ENOENT,
2629 "Failed lookup while freeing chunk.");
2634 ret = btrfs_del_item(trans, root, path);
2636 btrfs_handle_fs_error(fs_info, ret,
2637 "Failed to delete chunk item.");
2639 btrfs_free_path(path);
2643 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2645 struct btrfs_super_block *super_copy = fs_info->super_copy;
2646 struct btrfs_disk_key *disk_key;
2647 struct btrfs_chunk *chunk;
2654 struct btrfs_key key;
2656 mutex_lock(&fs_info->chunk_mutex);
2657 array_size = btrfs_super_sys_array_size(super_copy);
2659 ptr = super_copy->sys_chunk_array;
2662 while (cur < array_size) {
2663 disk_key = (struct btrfs_disk_key *)ptr;
2664 btrfs_disk_key_to_cpu(&key, disk_key);
2666 len = sizeof(*disk_key);
2668 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2669 chunk = (struct btrfs_chunk *)(ptr + len);
2670 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2671 len += btrfs_chunk_item_size(num_stripes);
2676 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2677 key.offset == chunk_offset) {
2678 memmove(ptr, ptr + len, array_size - (cur + len));
2680 btrfs_set_super_sys_array_size(super_copy, array_size);
2686 mutex_unlock(&fs_info->chunk_mutex);
2690 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2691 u64 logical, u64 length)
2693 struct extent_map_tree *em_tree;
2694 struct extent_map *em;
2696 em_tree = &fs_info->mapping_tree.map_tree;
2697 read_lock(&em_tree->lock);
2698 em = lookup_extent_mapping(em_tree, logical, length);
2699 read_unlock(&em_tree->lock);
2702 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2704 return ERR_PTR(-EINVAL);
2707 if (em->start > logical || em->start + em->len < logical) {
2709 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2710 logical, length, em->start, em->start + em->len);
2711 free_extent_map(em);
2712 return ERR_PTR(-EINVAL);
2715 /* callers are responsible for dropping em's ref. */
2719 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2721 struct btrfs_fs_info *fs_info = trans->fs_info;
2722 struct extent_map *em;
2723 struct map_lookup *map;
2724 u64 dev_extent_len = 0;
2726 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2728 em = get_chunk_map(fs_info, chunk_offset, 1);
2731 * This is a logic error, but we don't want to just rely on the
2732 * user having built with ASSERT enabled, so if ASSERT doesn't
2733 * do anything we still error out.
2738 map = em->map_lookup;
2739 mutex_lock(&fs_info->chunk_mutex);
2740 check_system_chunk(trans, map->type);
2741 mutex_unlock(&fs_info->chunk_mutex);
2744 * Take the device list mutex to prevent races with the final phase of
2745 * a device replace operation that replaces the device object associated
2746 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2748 mutex_lock(&fs_devices->device_list_mutex);
2749 for (i = 0; i < map->num_stripes; i++) {
2750 struct btrfs_device *device = map->stripes[i].dev;
2751 ret = btrfs_free_dev_extent(trans, device,
2752 map->stripes[i].physical,
2755 mutex_unlock(&fs_devices->device_list_mutex);
2756 btrfs_abort_transaction(trans, ret);
2760 if (device->bytes_used > 0) {
2761 mutex_lock(&fs_info->chunk_mutex);
2762 btrfs_device_set_bytes_used(device,
2763 device->bytes_used - dev_extent_len);
2764 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2765 btrfs_clear_space_info_full(fs_info);
2766 mutex_unlock(&fs_info->chunk_mutex);
2769 if (map->stripes[i].dev) {
2770 ret = btrfs_update_device(trans, map->stripes[i].dev);
2772 mutex_unlock(&fs_devices->device_list_mutex);
2773 btrfs_abort_transaction(trans, ret);
2778 mutex_unlock(&fs_devices->device_list_mutex);
2780 ret = btrfs_free_chunk(trans, chunk_offset);
2782 btrfs_abort_transaction(trans, ret);
2786 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2788 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2789 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2791 btrfs_abort_transaction(trans, ret);
2796 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2798 btrfs_abort_transaction(trans, ret);
2804 free_extent_map(em);
2808 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2810 struct btrfs_root *root = fs_info->chunk_root;
2811 struct btrfs_trans_handle *trans;
2815 * Prevent races with automatic removal of unused block groups.
2816 * After we relocate and before we remove the chunk with offset
2817 * chunk_offset, automatic removal of the block group can kick in,
2818 * resulting in a failure when calling btrfs_remove_chunk() below.
2820 * Make sure to acquire this mutex before doing a tree search (dev
2821 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2822 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2823 * we release the path used to search the chunk/dev tree and before
2824 * the current task acquires this mutex and calls us.
2826 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2828 ret = btrfs_can_relocate(fs_info, chunk_offset);
2832 /* step one, relocate all the extents inside this chunk */
2833 btrfs_scrub_pause(fs_info);
2834 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2835 btrfs_scrub_continue(fs_info);
2840 * We add the kobjects here (and after forcing data chunk creation)
2841 * since relocation is the only place we'll create chunks of a new
2842 * type at runtime. The only place where we'll remove the last
2843 * chunk of a type is the call immediately below this one. Even
2844 * so, we're protected against races with the cleaner thread since
2845 * we're covered by the delete_unused_bgs_mutex.
2847 btrfs_add_raid_kobjects(fs_info);
2849 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2851 if (IS_ERR(trans)) {
2852 ret = PTR_ERR(trans);
2853 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2858 * step two, delete the device extents and the
2859 * chunk tree entries
2861 ret = btrfs_remove_chunk(trans, chunk_offset);
2862 btrfs_end_transaction(trans);
2866 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2868 struct btrfs_root *chunk_root = fs_info->chunk_root;
2869 struct btrfs_path *path;
2870 struct extent_buffer *leaf;
2871 struct btrfs_chunk *chunk;
2872 struct btrfs_key key;
2873 struct btrfs_key found_key;
2875 bool retried = false;
2879 path = btrfs_alloc_path();
2884 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2885 key.offset = (u64)-1;
2886 key.type = BTRFS_CHUNK_ITEM_KEY;
2889 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2890 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2892 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2895 BUG_ON(ret == 0); /* Corruption */
2897 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2900 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2906 leaf = path->nodes[0];
2907 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2909 chunk = btrfs_item_ptr(leaf, path->slots[0],
2910 struct btrfs_chunk);
2911 chunk_type = btrfs_chunk_type(leaf, chunk);
2912 btrfs_release_path(path);
2914 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2915 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
2921 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2923 if (found_key.offset == 0)
2925 key.offset = found_key.offset - 1;
2928 if (failed && !retried) {
2932 } else if (WARN_ON(failed && retried)) {
2936 btrfs_free_path(path);
2941 * return 1 : allocate a data chunk successfully,
2942 * return <0: errors during allocating a data chunk,
2943 * return 0 : no need to allocate a data chunk.
2945 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
2948 struct btrfs_block_group_cache *cache;
2952 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2954 chunk_type = cache->flags;
2955 btrfs_put_block_group(cache);
2957 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
2958 spin_lock(&fs_info->data_sinfo->lock);
2959 bytes_used = fs_info->data_sinfo->bytes_used;
2960 spin_unlock(&fs_info->data_sinfo->lock);
2963 struct btrfs_trans_handle *trans;
2966 trans = btrfs_join_transaction(fs_info->tree_root);
2968 return PTR_ERR(trans);
2970 ret = btrfs_force_chunk_alloc(trans,
2971 BTRFS_BLOCK_GROUP_DATA);
2972 btrfs_end_transaction(trans);
2976 btrfs_add_raid_kobjects(fs_info);
2984 static int insert_balance_item(struct btrfs_fs_info *fs_info,
2985 struct btrfs_balance_control *bctl)
2987 struct btrfs_root *root = fs_info->tree_root;
2988 struct btrfs_trans_handle *trans;
2989 struct btrfs_balance_item *item;
2990 struct btrfs_disk_balance_args disk_bargs;
2991 struct btrfs_path *path;
2992 struct extent_buffer *leaf;
2993 struct btrfs_key key;
2996 path = btrfs_alloc_path();
3000 trans = btrfs_start_transaction(root, 0);
3001 if (IS_ERR(trans)) {
3002 btrfs_free_path(path);
3003 return PTR_ERR(trans);
3006 key.objectid = BTRFS_BALANCE_OBJECTID;
3007 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3010 ret = btrfs_insert_empty_item(trans, root, path, &key,
3015 leaf = path->nodes[0];
3016 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3018 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3020 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3021 btrfs_set_balance_data(leaf, item, &disk_bargs);
3022 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3023 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3024 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3025 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3027 btrfs_set_balance_flags(leaf, item, bctl->flags);
3029 btrfs_mark_buffer_dirty(leaf);
3031 btrfs_free_path(path);
3032 err = btrfs_commit_transaction(trans);
3038 static int del_balance_item(struct btrfs_fs_info *fs_info)
3040 struct btrfs_root *root = fs_info->tree_root;
3041 struct btrfs_trans_handle *trans;
3042 struct btrfs_path *path;
3043 struct btrfs_key key;
3046 path = btrfs_alloc_path();
3050 trans = btrfs_start_transaction(root, 0);
3051 if (IS_ERR(trans)) {
3052 btrfs_free_path(path);
3053 return PTR_ERR(trans);
3056 key.objectid = BTRFS_BALANCE_OBJECTID;
3057 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3060 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3068 ret = btrfs_del_item(trans, root, path);
3070 btrfs_free_path(path);
3071 err = btrfs_commit_transaction(trans);
3078 * This is a heuristic used to reduce the number of chunks balanced on
3079 * resume after balance was interrupted.
3081 static void update_balance_args(struct btrfs_balance_control *bctl)
3084 * Turn on soft mode for chunk types that were being converted.
3086 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3087 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3088 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3089 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3090 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3091 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3094 * Turn on usage filter if is not already used. The idea is
3095 * that chunks that we have already balanced should be
3096 * reasonably full. Don't do it for chunks that are being
3097 * converted - that will keep us from relocating unconverted
3098 * (albeit full) chunks.
3100 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3101 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3102 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3103 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3104 bctl->data.usage = 90;
3106 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3107 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3108 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3109 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3110 bctl->sys.usage = 90;
3112 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3113 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3114 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3115 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3116 bctl->meta.usage = 90;
3121 * Clear the balance status in fs_info and delete the balance item from disk.
3123 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3125 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3128 BUG_ON(!fs_info->balance_ctl);
3130 spin_lock(&fs_info->balance_lock);
3131 fs_info->balance_ctl = NULL;
3132 spin_unlock(&fs_info->balance_lock);
3135 ret = del_balance_item(fs_info);
3137 btrfs_handle_fs_error(fs_info, ret, NULL);
3141 * Balance filters. Return 1 if chunk should be filtered out
3142 * (should not be balanced).
3144 static int chunk_profiles_filter(u64 chunk_type,
3145 struct btrfs_balance_args *bargs)
3147 chunk_type = chunk_to_extended(chunk_type) &
3148 BTRFS_EXTENDED_PROFILE_MASK;
3150 if (bargs->profiles & chunk_type)
3156 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3157 struct btrfs_balance_args *bargs)
3159 struct btrfs_block_group_cache *cache;
3161 u64 user_thresh_min;
3162 u64 user_thresh_max;
3165 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3166 chunk_used = btrfs_block_group_used(&cache->item);
3168 if (bargs->usage_min == 0)
3169 user_thresh_min = 0;
3171 user_thresh_min = div_factor_fine(cache->key.offset,
3174 if (bargs->usage_max == 0)
3175 user_thresh_max = 1;
3176 else if (bargs->usage_max > 100)
3177 user_thresh_max = cache->key.offset;
3179 user_thresh_max = div_factor_fine(cache->key.offset,
3182 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3185 btrfs_put_block_group(cache);
3189 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3190 u64 chunk_offset, struct btrfs_balance_args *bargs)
3192 struct btrfs_block_group_cache *cache;
3193 u64 chunk_used, user_thresh;
3196 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3197 chunk_used = btrfs_block_group_used(&cache->item);
3199 if (bargs->usage_min == 0)
3201 else if (bargs->usage > 100)
3202 user_thresh = cache->key.offset;
3204 user_thresh = div_factor_fine(cache->key.offset,
3207 if (chunk_used < user_thresh)
3210 btrfs_put_block_group(cache);
3214 static int chunk_devid_filter(struct extent_buffer *leaf,
3215 struct btrfs_chunk *chunk,
3216 struct btrfs_balance_args *bargs)
3218 struct btrfs_stripe *stripe;
3219 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3222 for (i = 0; i < num_stripes; i++) {
3223 stripe = btrfs_stripe_nr(chunk, i);
3224 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3231 /* [pstart, pend) */
3232 static int chunk_drange_filter(struct extent_buffer *leaf,
3233 struct btrfs_chunk *chunk,
3234 struct btrfs_balance_args *bargs)
3236 struct btrfs_stripe *stripe;
3237 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3243 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3246 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3247 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3248 factor = num_stripes / 2;
3249 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3250 factor = num_stripes - 1;
3251 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3252 factor = num_stripes - 2;
3254 factor = num_stripes;
3257 for (i = 0; i < num_stripes; i++) {
3258 stripe = btrfs_stripe_nr(chunk, i);
3259 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3262 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3263 stripe_length = btrfs_chunk_length(leaf, chunk);
3264 stripe_length = div_u64(stripe_length, factor);
3266 if (stripe_offset < bargs->pend &&
3267 stripe_offset + stripe_length > bargs->pstart)
3274 /* [vstart, vend) */
3275 static int chunk_vrange_filter(struct extent_buffer *leaf,
3276 struct btrfs_chunk *chunk,
3278 struct btrfs_balance_args *bargs)
3280 if (chunk_offset < bargs->vend &&
3281 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3282 /* at least part of the chunk is inside this vrange */
3288 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3289 struct btrfs_chunk *chunk,
3290 struct btrfs_balance_args *bargs)
3292 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3294 if (bargs->stripes_min <= num_stripes
3295 && num_stripes <= bargs->stripes_max)
3301 static int chunk_soft_convert_filter(u64 chunk_type,
3302 struct btrfs_balance_args *bargs)
3304 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3307 chunk_type = chunk_to_extended(chunk_type) &
3308 BTRFS_EXTENDED_PROFILE_MASK;
3310 if (bargs->target == chunk_type)
3316 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3317 struct extent_buffer *leaf,
3318 struct btrfs_chunk *chunk, u64 chunk_offset)
3320 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3321 struct btrfs_balance_args *bargs = NULL;
3322 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3325 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3326 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3330 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3331 bargs = &bctl->data;
3332 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3334 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3335 bargs = &bctl->meta;
3337 /* profiles filter */
3338 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3339 chunk_profiles_filter(chunk_type, bargs)) {
3344 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3345 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3347 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3348 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3353 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3354 chunk_devid_filter(leaf, chunk, bargs)) {
3358 /* drange filter, makes sense only with devid filter */
3359 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3360 chunk_drange_filter(leaf, chunk, bargs)) {
3365 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3366 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3370 /* stripes filter */
3371 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3372 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3376 /* soft profile changing mode */
3377 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3378 chunk_soft_convert_filter(chunk_type, bargs)) {
3383 * limited by count, must be the last filter
3385 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3386 if (bargs->limit == 0)
3390 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3392 * Same logic as the 'limit' filter; the minimum cannot be
3393 * determined here because we do not have the global information
3394 * about the count of all chunks that satisfy the filters.
3396 if (bargs->limit_max == 0)
3405 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3407 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3408 struct btrfs_root *chunk_root = fs_info->chunk_root;
3409 struct btrfs_root *dev_root = fs_info->dev_root;
3410 struct list_head *devices;
3411 struct btrfs_device *device;
3415 struct btrfs_chunk *chunk;
3416 struct btrfs_path *path = NULL;
3417 struct btrfs_key key;
3418 struct btrfs_key found_key;
3419 struct btrfs_trans_handle *trans;
3420 struct extent_buffer *leaf;
3423 int enospc_errors = 0;
3424 bool counting = true;
3425 /* The single value limit and min/max limits use the same bytes in the */
3426 u64 limit_data = bctl->data.limit;
3427 u64 limit_meta = bctl->meta.limit;
3428 u64 limit_sys = bctl->sys.limit;
3432 int chunk_reserved = 0;
3434 /* step one make some room on all the devices */
3435 devices = &fs_info->fs_devices->devices;
3436 list_for_each_entry(device, devices, dev_list) {
3437 old_size = btrfs_device_get_total_bytes(device);
3438 size_to_free = div_factor(old_size, 1);
3439 size_to_free = min_t(u64, size_to_free, SZ_1M);
3440 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3441 btrfs_device_get_total_bytes(device) -
3442 btrfs_device_get_bytes_used(device) > size_to_free ||
3443 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3446 ret = btrfs_shrink_device(device, old_size - size_to_free);
3450 /* btrfs_shrink_device never returns ret > 0 */
3455 trans = btrfs_start_transaction(dev_root, 0);
3456 if (IS_ERR(trans)) {
3457 ret = PTR_ERR(trans);
3458 btrfs_info_in_rcu(fs_info,
3459 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3460 rcu_str_deref(device->name), ret,
3461 old_size, old_size - size_to_free);
3465 ret = btrfs_grow_device(trans, device, old_size);
3467 btrfs_end_transaction(trans);
3468 /* btrfs_grow_device never returns ret > 0 */
3470 btrfs_info_in_rcu(fs_info,
3471 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3472 rcu_str_deref(device->name), ret,
3473 old_size, old_size - size_to_free);
3477 btrfs_end_transaction(trans);
3480 /* step two, relocate all the chunks */
3481 path = btrfs_alloc_path();
3487 /* zero out stat counters */
3488 spin_lock(&fs_info->balance_lock);
3489 memset(&bctl->stat, 0, sizeof(bctl->stat));
3490 spin_unlock(&fs_info->balance_lock);
3494 * The single value limit and min/max limits use the same bytes
3497 bctl->data.limit = limit_data;
3498 bctl->meta.limit = limit_meta;
3499 bctl->sys.limit = limit_sys;
3501 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3502 key.offset = (u64)-1;
3503 key.type = BTRFS_CHUNK_ITEM_KEY;
3506 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3507 atomic_read(&fs_info->balance_cancel_req)) {
3512 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3513 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3515 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3520 * this shouldn't happen, it means the last relocate
3524 BUG(); /* FIXME break ? */
3526 ret = btrfs_previous_item(chunk_root, path, 0,
3527 BTRFS_CHUNK_ITEM_KEY);
3529 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3534 leaf = path->nodes[0];
3535 slot = path->slots[0];
3536 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3538 if (found_key.objectid != key.objectid) {
3539 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3543 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3544 chunk_type = btrfs_chunk_type(leaf, chunk);
3547 spin_lock(&fs_info->balance_lock);
3548 bctl->stat.considered++;
3549 spin_unlock(&fs_info->balance_lock);
3552 ret = should_balance_chunk(fs_info, leaf, chunk,
3555 btrfs_release_path(path);
3557 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3562 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3563 spin_lock(&fs_info->balance_lock);
3564 bctl->stat.expected++;
3565 spin_unlock(&fs_info->balance_lock);
3567 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3569 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3571 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3578 * Apply limit_min filter, no need to check if the LIMITS
3579 * filter is used, limit_min is 0 by default
3581 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3582 count_data < bctl->data.limit_min)
3583 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3584 count_meta < bctl->meta.limit_min)
3585 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3586 count_sys < bctl->sys.limit_min)) {
3587 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3591 if (!chunk_reserved) {
3593 * We may be relocating the only data chunk we have,
3594 * which could potentially end up with losing data's
3595 * raid profile, so lets allocate an empty one in
3598 ret = btrfs_may_alloc_data_chunk(fs_info,
3601 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3603 } else if (ret == 1) {
3608 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3609 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3610 if (ret && ret != -ENOSPC)
3612 if (ret == -ENOSPC) {
3615 spin_lock(&fs_info->balance_lock);
3616 bctl->stat.completed++;
3617 spin_unlock(&fs_info->balance_lock);
3620 if (found_key.offset == 0)
3622 key.offset = found_key.offset - 1;
3626 btrfs_release_path(path);
3631 btrfs_free_path(path);
3632 if (enospc_errors) {
3633 btrfs_info(fs_info, "%d enospc errors during balance",
3643 * alloc_profile_is_valid - see if a given profile is valid and reduced
3644 * @flags: profile to validate
3645 * @extended: if true @flags is treated as an extended profile
3647 static int alloc_profile_is_valid(u64 flags, int extended)
3649 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3650 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3652 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3654 /* 1) check that all other bits are zeroed */
3658 /* 2) see if profile is reduced */
3660 return !extended; /* "0" is valid for usual profiles */
3662 /* true if exactly one bit set */
3663 return (flags & (flags - 1)) == 0;
3666 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3668 /* cancel requested || normal exit path */
3669 return atomic_read(&fs_info->balance_cancel_req) ||
3670 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3671 atomic_read(&fs_info->balance_cancel_req) == 0);
3674 /* Non-zero return value signifies invalidity */
3675 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3678 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3679 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3680 (bctl_arg->target & ~allowed)));
3684 * Should be called with balance mutexe held
3686 int btrfs_balance(struct btrfs_fs_info *fs_info,
3687 struct btrfs_balance_control *bctl,
3688 struct btrfs_ioctl_balance_args *bargs)
3690 u64 meta_target, data_target;
3697 if (btrfs_fs_closing(fs_info) ||
3698 atomic_read(&fs_info->balance_pause_req) ||
3699 atomic_read(&fs_info->balance_cancel_req)) {
3704 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3705 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3709 * In case of mixed groups both data and meta should be picked,
3710 * and identical options should be given for both of them.
3712 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3713 if (mixed && (bctl->flags & allowed)) {
3714 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3715 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3716 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3718 "balance: mixed groups data and metadata options must be the same");
3724 num_devices = fs_info->fs_devices->num_devices;
3725 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
3726 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3727 BUG_ON(num_devices < 1);
3730 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
3731 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3732 if (num_devices > 1)
3733 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3734 if (num_devices > 2)
3735 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3736 if (num_devices > 3)
3737 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3738 BTRFS_BLOCK_GROUP_RAID6);
3739 if (validate_convert_profile(&bctl->data, allowed)) {
3740 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
3743 "balance: invalid convert data profile %s",