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,
41 .raid_name = "raid10",
42 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
43 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
45 [BTRFS_RAID_RAID1] = {
50 .tolerated_failures = 1,
55 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
56 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
63 .tolerated_failures = 0,
68 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
71 [BTRFS_RAID_RAID0] = {
76 .tolerated_failures = 0,
81 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
84 [BTRFS_RAID_SINGLE] = {
89 .tolerated_failures = 0,
93 .raid_name = "single",
97 [BTRFS_RAID_RAID5] = {
102 .tolerated_failures = 1,
106 .raid_name = "raid5",
107 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
108 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
110 [BTRFS_RAID_RAID6] = {
115 .tolerated_failures = 2,
119 .raid_name = "raid6",
120 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
121 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
125 const char *get_raid_name(enum btrfs_raid_types type)
127 if (type >= BTRFS_NR_RAID_TYPES)
130 return btrfs_raid_array[type].raid_name;
133 static int init_first_rw_device(struct btrfs_trans_handle *trans,
134 struct btrfs_fs_info *fs_info);
135 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
136 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
137 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
138 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
139 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
140 enum btrfs_map_op op,
141 u64 logical, u64 *length,
142 struct btrfs_bio **bbio_ret,
143 int mirror_num, int need_raid_map);
149 * There are several mutexes that protect manipulation of devices and low-level
150 * structures like chunks but not block groups, extents or files
152 * uuid_mutex (global lock)
153 * ------------------------
154 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
155 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
156 * device) or requested by the device= mount option
158 * the mutex can be very coarse and can cover long-running operations
160 * protects: updates to fs_devices counters like missing devices, rw devices,
161 * seeding, structure cloning, openning/closing devices at mount/umount time
163 * global::fs_devs - add, remove, updates to the global list
165 * does not protect: manipulation of the fs_devices::devices list!
167 * btrfs_device::name - renames (write side), read is RCU
169 * fs_devices::device_list_mutex (per-fs, with RCU)
170 * ------------------------------------------------
171 * protects updates to fs_devices::devices, ie. adding and deleting
173 * simple list traversal with read-only actions can be done with RCU protection
175 * may be used to exclude some operations from running concurrently without any
176 * modifications to the list (see write_all_supers)
180 * protects balance structures (status, state) and context accessed from
181 * several places (internally, ioctl)
185 * protects chunks, adding or removing during allocation, trim or when a new
186 * device is added/removed
190 * a big lock that is held by the cleaner thread and prevents running subvolume
191 * cleaning together with relocation or delayed iputs
204 * Exclusive operations, BTRFS_FS_EXCL_OP
205 * ======================================
207 * Maintains the exclusivity of the following operations that apply to the
208 * whole filesystem and cannot run in parallel.
213 * - Device replace (*)
216 * The device operations (as above) can be in one of the following states:
222 * Only device operations marked with (*) can go into the Paused state for the
225 * - ioctl (only Balance can be Paused through ioctl)
226 * - filesystem remounted as read-only
227 * - filesystem unmounted and mounted as read-only
228 * - system power-cycle and filesystem mounted as read-only
229 * - filesystem or device errors leading to forced read-only
231 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
232 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
233 * A device operation in Paused or Running state can be canceled or resumed
234 * either by ioctl (Balance only) or when remounted as read-write.
235 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
239 DEFINE_MUTEX(uuid_mutex);
240 static LIST_HEAD(fs_uuids);
241 struct list_head *btrfs_get_fs_uuids(void)
247 * alloc_fs_devices - allocate struct btrfs_fs_devices
248 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
249 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
251 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
252 * The returned struct is not linked onto any lists and can be destroyed with
253 * kfree() right away.
255 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
256 const u8 *metadata_fsid)
258 struct btrfs_fs_devices *fs_devs;
260 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
262 return ERR_PTR(-ENOMEM);
264 mutex_init(&fs_devs->device_list_mutex);
266 INIT_LIST_HEAD(&fs_devs->devices);
267 INIT_LIST_HEAD(&fs_devs->resized_devices);
268 INIT_LIST_HEAD(&fs_devs->alloc_list);
269 INIT_LIST_HEAD(&fs_devs->fs_list);
271 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
274 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
276 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
281 void btrfs_free_device(struct btrfs_device *device)
283 rcu_string_free(device->name);
284 bio_put(device->flush_bio);
288 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
290 struct btrfs_device *device;
291 WARN_ON(fs_devices->opened);
292 while (!list_empty(&fs_devices->devices)) {
293 device = list_entry(fs_devices->devices.next,
294 struct btrfs_device, dev_list);
295 list_del(&device->dev_list);
296 btrfs_free_device(device);
301 static void btrfs_kobject_uevent(struct block_device *bdev,
302 enum kobject_action action)
306 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
308 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
310 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
311 &disk_to_dev(bdev->bd_disk)->kobj);
314 void __exit btrfs_cleanup_fs_uuids(void)
316 struct btrfs_fs_devices *fs_devices;
318 while (!list_empty(&fs_uuids)) {
319 fs_devices = list_entry(fs_uuids.next,
320 struct btrfs_fs_devices, fs_list);
321 list_del(&fs_devices->fs_list);
322 free_fs_devices(fs_devices);
327 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
328 * Returned struct is not linked onto any lists and must be destroyed using
331 static struct btrfs_device *__alloc_device(void)
333 struct btrfs_device *dev;
335 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
337 return ERR_PTR(-ENOMEM);
340 * Preallocate a bio that's always going to be used for flushing device
341 * barriers and matches the device lifespan
343 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
344 if (!dev->flush_bio) {
346 return ERR_PTR(-ENOMEM);
349 INIT_LIST_HEAD(&dev->dev_list);
350 INIT_LIST_HEAD(&dev->dev_alloc_list);
351 INIT_LIST_HEAD(&dev->resized_list);
353 spin_lock_init(&dev->io_lock);
355 atomic_set(&dev->reada_in_flight, 0);
356 atomic_set(&dev->dev_stats_ccnt, 0);
357 btrfs_device_data_ordered_init(dev);
358 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
359 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
365 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
368 * If devid and uuid are both specified, the match must be exact, otherwise
369 * only devid is used.
371 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
372 u64 devid, const u8 *uuid)
374 struct btrfs_device *dev;
376 list_for_each_entry(dev, &fs_devices->devices, dev_list) {
377 if (dev->devid == devid &&
378 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
385 static noinline struct btrfs_fs_devices *find_fsid(
386 const u8 *fsid, const u8 *metadata_fsid)
388 struct btrfs_fs_devices *fs_devices;
394 * Handle scanned device having completed its fsid change but
395 * belonging to a fs_devices that was created by first scanning
396 * a device which didn't have its fsid/metadata_uuid changed
397 * at all and the CHANGING_FSID_V2 flag set.
399 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
400 if (fs_devices->fsid_change &&
401 memcmp(metadata_fsid, fs_devices->fsid,
402 BTRFS_FSID_SIZE) == 0 &&
403 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
404 BTRFS_FSID_SIZE) == 0) {
409 * Handle scanned device having completed its fsid change but
410 * belonging to a fs_devices that was created by a device that
411 * has an outdated pair of fsid/metadata_uuid and
412 * CHANGING_FSID_V2 flag set.
414 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
415 if (fs_devices->fsid_change &&
416 memcmp(fs_devices->metadata_uuid,
417 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
418 memcmp(metadata_fsid, fs_devices->metadata_uuid,
419 BTRFS_FSID_SIZE) == 0) {
425 /* Handle non-split brain cases */
426 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
428 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
429 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
430 BTRFS_FSID_SIZE) == 0)
433 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
441 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
442 int flush, struct block_device **bdev,
443 struct buffer_head **bh)
447 *bdev = blkdev_get_by_path(device_path, flags, holder);
450 ret = PTR_ERR(*bdev);
455 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
456 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
458 blkdev_put(*bdev, flags);
461 invalidate_bdev(*bdev);
462 *bh = btrfs_read_dev_super(*bdev);
465 blkdev_put(*bdev, flags);
477 static void requeue_list(struct btrfs_pending_bios *pending_bios,
478 struct bio *head, struct bio *tail)
481 struct bio *old_head;
483 old_head = pending_bios->head;
484 pending_bios->head = head;
485 if (pending_bios->tail)
486 tail->bi_next = old_head;
488 pending_bios->tail = tail;
492 * we try to collect pending bios for a device so we don't get a large
493 * number of procs sending bios down to the same device. This greatly
494 * improves the schedulers ability to collect and merge the bios.
496 * But, it also turns into a long list of bios to process and that is sure
497 * to eventually make the worker thread block. The solution here is to
498 * make some progress and then put this work struct back at the end of
499 * the list if the block device is congested. This way, multiple devices
500 * can make progress from a single worker thread.
502 static noinline void run_scheduled_bios(struct btrfs_device *device)
504 struct btrfs_fs_info *fs_info = device->fs_info;
506 struct backing_dev_info *bdi;
507 struct btrfs_pending_bios *pending_bios;
511 unsigned long num_run;
512 unsigned long batch_run = 0;
513 unsigned long last_waited = 0;
515 int sync_pending = 0;
516 struct blk_plug plug;
519 * this function runs all the bios we've collected for
520 * a particular device. We don't want to wander off to
521 * another device without first sending all of these down.
522 * So, setup a plug here and finish it off before we return
524 blk_start_plug(&plug);
526 bdi = device->bdev->bd_bdi;
529 spin_lock(&device->io_lock);
534 /* take all the bios off the list at once and process them
535 * later on (without the lock held). But, remember the
536 * tail and other pointers so the bios can be properly reinserted
537 * into the list if we hit congestion
539 if (!force_reg && device->pending_sync_bios.head) {
540 pending_bios = &device->pending_sync_bios;
543 pending_bios = &device->pending_bios;
547 pending = pending_bios->head;
548 tail = pending_bios->tail;
549 WARN_ON(pending && !tail);
552 * if pending was null this time around, no bios need processing
553 * at all and we can stop. Otherwise it'll loop back up again
554 * and do an additional check so no bios are missed.
556 * device->running_pending is used to synchronize with the
559 if (device->pending_sync_bios.head == NULL &&
560 device->pending_bios.head == NULL) {
562 device->running_pending = 0;
565 device->running_pending = 1;
568 pending_bios->head = NULL;
569 pending_bios->tail = NULL;
571 spin_unlock(&device->io_lock);
576 /* we want to work on both lists, but do more bios on the
577 * sync list than the regular list
580 pending_bios != &device->pending_sync_bios &&
581 device->pending_sync_bios.head) ||
582 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
583 device->pending_bios.head)) {
584 spin_lock(&device->io_lock);
585 requeue_list(pending_bios, pending, tail);
590 pending = pending->bi_next;
593 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
596 * if we're doing the sync list, record that our
597 * plug has some sync requests on it
599 * If we're doing the regular list and there are
600 * sync requests sitting around, unplug before
603 if (pending_bios == &device->pending_sync_bios) {
605 } else if (sync_pending) {
606 blk_finish_plug(&plug);
607 blk_start_plug(&plug);
611 btrfsic_submit_bio(cur);
618 * we made progress, there is more work to do and the bdi
619 * is now congested. Back off and let other work structs
622 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
623 fs_info->fs_devices->open_devices > 1) {
624 struct io_context *ioc;
626 ioc = current->io_context;
629 * the main goal here is that we don't want to
630 * block if we're going to be able to submit
631 * more requests without blocking.
633 * This code does two great things, it pokes into
634 * the elevator code from a filesystem _and_
635 * it makes assumptions about how batching works.
637 if (ioc && ioc->nr_batch_requests > 0 &&
638 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
640 ioc->last_waited == last_waited)) {
642 * we want to go through our batch of
643 * requests and stop. So, we copy out
644 * the ioc->last_waited time and test
645 * against it before looping
647 last_waited = ioc->last_waited;
651 spin_lock(&device->io_lock);
652 requeue_list(pending_bios, pending, tail);
653 device->running_pending = 1;
655 spin_unlock(&device->io_lock);
656 btrfs_queue_work(fs_info->submit_workers,
666 spin_lock(&device->io_lock);
667 if (device->pending_bios.head || device->pending_sync_bios.head)
669 spin_unlock(&device->io_lock);
672 blk_finish_plug(&plug);
675 static void pending_bios_fn(struct btrfs_work *work)
677 struct btrfs_device *device;
679 device = container_of(work, struct btrfs_device, work);
680 run_scheduled_bios(device);
684 * Search and remove all stale (devices which are not mounted) devices.
685 * When both inputs are NULL, it will search and release all stale devices.
686 * path: Optional. When provided will it release all unmounted devices
687 * matching this path only.
688 * skip_dev: Optional. Will skip this device when searching for the stale
691 static void btrfs_free_stale_devices(const char *path,
692 struct btrfs_device *skip_device)
694 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
695 struct btrfs_device *device, *tmp_device;
697 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
698 mutex_lock(&fs_devices->device_list_mutex);
699 if (fs_devices->opened) {
700 mutex_unlock(&fs_devices->device_list_mutex);
704 list_for_each_entry_safe(device, tmp_device,
705 &fs_devices->devices, dev_list) {
708 if (skip_device && skip_device == device)
710 if (path && !device->name)
715 not_found = strcmp(rcu_str_deref(device->name),
721 /* delete the stale device */
722 fs_devices->num_devices--;
723 list_del(&device->dev_list);
724 btrfs_free_device(device);
726 if (fs_devices->num_devices == 0)
729 mutex_unlock(&fs_devices->device_list_mutex);
730 if (fs_devices->num_devices == 0) {
731 btrfs_sysfs_remove_fsid(fs_devices);
732 list_del(&fs_devices->fs_list);
733 free_fs_devices(fs_devices);
738 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
739 struct btrfs_device *device, fmode_t flags,
742 struct request_queue *q;
743 struct block_device *bdev;
744 struct buffer_head *bh;
745 struct btrfs_super_block *disk_super;
754 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
759 disk_super = (struct btrfs_super_block *)bh->b_data;
760 devid = btrfs_stack_device_id(&disk_super->dev_item);
761 if (devid != device->devid)
764 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
767 device->generation = btrfs_super_generation(disk_super);
769 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
770 if (btrfs_super_incompat_flags(disk_super) &
771 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
773 "BTRFS: Invalid seeding and uuid-changed device detected\n");
777 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
778 fs_devices->seeding = 1;
780 if (bdev_read_only(bdev))
781 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
783 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
786 q = bdev_get_queue(bdev);
787 if (!blk_queue_nonrot(q))
788 fs_devices->rotating = 1;
791 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
792 device->mode = flags;
794 fs_devices->open_devices++;
795 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
796 device->devid != BTRFS_DEV_REPLACE_DEVID) {
797 fs_devices->rw_devices++;
798 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
806 blkdev_put(bdev, flags);
812 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
813 * being created with a disk that has already completed its fsid change.
815 static struct btrfs_fs_devices *find_fsid_inprogress(
816 struct btrfs_super_block *disk_super)
818 struct btrfs_fs_devices *fs_devices;
820 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
821 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
822 BTRFS_FSID_SIZE) != 0 &&
823 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
824 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
833 static struct btrfs_fs_devices *find_fsid_changed(
834 struct btrfs_super_block *disk_super)
836 struct btrfs_fs_devices *fs_devices;
839 * Handles the case where scanned device is part of an fs that had
840 * multiple successful changes of FSID but curently device didn't
841 * observe it. Meaning our fsid will be different than theirs.
843 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
844 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
845 BTRFS_FSID_SIZE) != 0 &&
846 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
847 BTRFS_FSID_SIZE) == 0 &&
848 memcmp(fs_devices->fsid, disk_super->fsid,
849 BTRFS_FSID_SIZE) != 0) {
857 * Add new device to list of registered devices
860 * device pointer which was just added or updated when successful
861 * error pointer when failed
863 static noinline struct btrfs_device *device_list_add(const char *path,
864 struct btrfs_super_block *disk_super,
865 bool *new_device_added)
867 struct btrfs_device *device;
868 struct btrfs_fs_devices *fs_devices = NULL;
869 struct rcu_string *name;
870 u64 found_transid = btrfs_super_generation(disk_super);
871 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
872 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
873 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
874 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
875 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
877 if (fsid_change_in_progress) {
878 if (!has_metadata_uuid) {
880 * When we have an image which has CHANGING_FSID_V2 set
881 * it might belong to either a filesystem which has
882 * disks with completed fsid change or it might belong
883 * to fs with no UUID changes in effect, handle both.
885 fs_devices = find_fsid_inprogress(disk_super);
887 fs_devices = find_fsid(disk_super->fsid, NULL);
889 fs_devices = find_fsid_changed(disk_super);
891 } else if (has_metadata_uuid) {
892 fs_devices = find_fsid(disk_super->fsid,
893 disk_super->metadata_uuid);
895 fs_devices = find_fsid(disk_super->fsid, NULL);
900 if (has_metadata_uuid)
901 fs_devices = alloc_fs_devices(disk_super->fsid,
902 disk_super->metadata_uuid);
904 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
906 fs_devices->fsid_change = fsid_change_in_progress;
908 if (IS_ERR(fs_devices))
909 return ERR_CAST(fs_devices);
911 mutex_lock(&fs_devices->device_list_mutex);
912 list_add(&fs_devices->fs_list, &fs_uuids);
916 mutex_lock(&fs_devices->device_list_mutex);
917 device = find_device(fs_devices, devid,
918 disk_super->dev_item.uuid);
921 * If this disk has been pulled into an fs devices created by
922 * a device which had the CHANGING_FSID_V2 flag then replace the
923 * metadata_uuid/fsid values of the fs_devices.
925 if (has_metadata_uuid && fs_devices->fsid_change &&
926 found_transid > fs_devices->latest_generation) {
927 memcpy(fs_devices->fsid, disk_super->fsid,
929 memcpy(fs_devices->metadata_uuid,
930 disk_super->metadata_uuid, BTRFS_FSID_SIZE);
932 fs_devices->fsid_change = false;
937 if (fs_devices->opened) {
938 mutex_unlock(&fs_devices->device_list_mutex);
939 return ERR_PTR(-EBUSY);
942 device = btrfs_alloc_device(NULL, &devid,
943 disk_super->dev_item.uuid);
944 if (IS_ERR(device)) {
945 mutex_unlock(&fs_devices->device_list_mutex);
946 /* we can safely leave the fs_devices entry around */
950 name = rcu_string_strdup(path, GFP_NOFS);
952 btrfs_free_device(device);
953 mutex_unlock(&fs_devices->device_list_mutex);
954 return ERR_PTR(-ENOMEM);
956 rcu_assign_pointer(device->name, name);
958 list_add_rcu(&device->dev_list, &fs_devices->devices);
959 fs_devices->num_devices++;
961 device->fs_devices = fs_devices;
962 *new_device_added = true;
964 if (disk_super->label[0])
965 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
966 disk_super->label, devid, found_transid, path);
968 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
969 disk_super->fsid, devid, found_transid, path);
971 } else if (!device->name || strcmp(device->name->str, path)) {
973 * When FS is already mounted.
974 * 1. If you are here and if the device->name is NULL that
975 * means this device was missing at time of FS mount.
976 * 2. If you are here and if the device->name is different
977 * from 'path' that means either
978 * a. The same device disappeared and reappeared with
980 * b. The missing-disk-which-was-replaced, has
983 * We must allow 1 and 2a above. But 2b would be a spurious
986 * Further in case of 1 and 2a above, the disk at 'path'
987 * would have missed some transaction when it was away and
988 * in case of 2a the stale bdev has to be updated as well.
989 * 2b must not be allowed at all time.
993 * For now, we do allow update to btrfs_fs_device through the
994 * btrfs dev scan cli after FS has been mounted. We're still
995 * tracking a problem where systems fail mount by subvolume id
996 * when we reject replacement on a mounted FS.
998 if (!fs_devices->opened && found_transid < device->generation) {
1000 * That is if the FS is _not_ mounted and if you
1001 * are here, that means there is more than one
1002 * disk with same uuid and devid.We keep the one
1003 * with larger generation number or the last-in if
1004 * generation are equal.
1006 mutex_unlock(&fs_devices->device_list_mutex);
1007 return ERR_PTR(-EEXIST);
1011 * We are going to replace the device path for a given devid,
1012 * make sure it's the same device if the device is mounted
1015 struct block_device *path_bdev;
1017 path_bdev = lookup_bdev(path);
1018 if (IS_ERR(path_bdev)) {
1019 mutex_unlock(&fs_devices->device_list_mutex);
1020 return ERR_CAST(path_bdev);
1023 if (device->bdev != path_bdev) {
1025 mutex_unlock(&fs_devices->device_list_mutex);
1026 btrfs_warn_in_rcu(device->fs_info,
1027 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
1028 disk_super->fsid, devid,
1029 rcu_str_deref(device->name), path);
1030 return ERR_PTR(-EEXIST);
1033 btrfs_info_in_rcu(device->fs_info,
1034 "device fsid %pU devid %llu moved old:%s new:%s",
1035 disk_super->fsid, devid,
1036 rcu_str_deref(device->name), path);
1039 name = rcu_string_strdup(path, GFP_NOFS);
1041 mutex_unlock(&fs_devices->device_list_mutex);
1042 return ERR_PTR(-ENOMEM);
1044 rcu_string_free(device->name);
1045 rcu_assign_pointer(device->name, name);
1046 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1047 fs_devices->missing_devices--;
1048 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1053 * Unmount does not free the btrfs_device struct but would zero
1054 * generation along with most of the other members. So just update
1055 * it back. We need it to pick the disk with largest generation
1058 if (!fs_devices->opened) {
1059 device->generation = found_transid;
1060 fs_devices->latest_generation = max_t(u64, found_transid,
1061 fs_devices->latest_generation);
1064 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
1066 mutex_unlock(&fs_devices->device_list_mutex);
1070 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1072 struct btrfs_fs_devices *fs_devices;
1073 struct btrfs_device *device;
1074 struct btrfs_device *orig_dev;
1076 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1077 if (IS_ERR(fs_devices))
1080 mutex_lock(&orig->device_list_mutex);
1081 fs_devices->total_devices = orig->total_devices;
1083 /* We have held the volume lock, it is safe to get the devices. */
1084 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1085 struct rcu_string *name;
1087 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1093 * This is ok to do without rcu read locked because we hold the
1094 * uuid mutex so nothing we touch in here is going to disappear.
1096 if (orig_dev->name) {
1097 name = rcu_string_strdup(orig_dev->name->str,
1100 btrfs_free_device(device);
1103 rcu_assign_pointer(device->name, name);
1106 list_add(&device->dev_list, &fs_devices->devices);
1107 device->fs_devices = fs_devices;
1108 fs_devices->num_devices++;
1110 mutex_unlock(&orig->device_list_mutex);
1113 mutex_unlock(&orig->device_list_mutex);
1114 free_fs_devices(fs_devices);
1115 return ERR_PTR(-ENOMEM);
1119 * After we have read the system tree and know devids belonging to
1120 * this filesystem, remove the device which does not belong there.
1122 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1124 struct btrfs_device *device, *next;
1125 struct btrfs_device *latest_dev = NULL;
1127 mutex_lock(&uuid_mutex);
1129 /* This is the initialized path, it is safe to release the devices. */
1130 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1131 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1132 &device->dev_state)) {
1133 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1134 &device->dev_state) &&
1136 device->generation > latest_dev->generation)) {
1137 latest_dev = device;
1142 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1144 * In the first step, keep the device which has
1145 * the correct fsid and the devid that is used
1146 * for the dev_replace procedure.
1147 * In the second step, the dev_replace state is
1148 * read from the device tree and it is known
1149 * whether the procedure is really active or
1150 * not, which means whether this device is
1151 * used or whether it should be removed.
1153 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1154 &device->dev_state)) {
1159 blkdev_put(device->bdev, device->mode);
1160 device->bdev = NULL;
1161 fs_devices->open_devices--;
1163 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1164 list_del_init(&device->dev_alloc_list);
1165 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1166 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1167 &device->dev_state))
1168 fs_devices->rw_devices--;
1170 list_del_init(&device->dev_list);
1171 fs_devices->num_devices--;
1172 btrfs_free_device(device);
1175 if (fs_devices->seed) {
1176 fs_devices = fs_devices->seed;
1180 fs_devices->latest_bdev = latest_dev->bdev;
1182 mutex_unlock(&uuid_mutex);
1185 static void free_device_rcu(struct rcu_head *head)
1187 struct btrfs_device *device;
1189 device = container_of(head, struct btrfs_device, rcu);
1190 btrfs_free_device(device);
1193 static void btrfs_close_bdev(struct btrfs_device *device)
1198 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1199 sync_blockdev(device->bdev);
1200 invalidate_bdev(device->bdev);
1203 blkdev_put(device->bdev, device->mode);
1206 static void btrfs_close_one_device(struct btrfs_device *device)
1208 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1209 struct btrfs_device *new_device;
1210 struct rcu_string *name;
1213 fs_devices->open_devices--;
1215 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1216 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1217 list_del_init(&device->dev_alloc_list);
1218 fs_devices->rw_devices--;
1221 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1222 fs_devices->missing_devices--;
1224 btrfs_close_bdev(device);
1226 new_device = btrfs_alloc_device(NULL, &device->devid,
1228 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1230 /* Safe because we are under uuid_mutex */
1232 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1233 BUG_ON(!name); /* -ENOMEM */
1234 rcu_assign_pointer(new_device->name, name);
1237 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1238 new_device->fs_devices = device->fs_devices;
1240 call_rcu(&device->rcu, free_device_rcu);
1243 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1245 struct btrfs_device *device, *tmp;
1247 if (--fs_devices->opened > 0)
1250 mutex_lock(&fs_devices->device_list_mutex);
1251 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1252 btrfs_close_one_device(device);
1254 mutex_unlock(&fs_devices->device_list_mutex);
1256 WARN_ON(fs_devices->open_devices);
1257 WARN_ON(fs_devices->rw_devices);
1258 fs_devices->opened = 0;
1259 fs_devices->seeding = 0;
1264 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1266 struct btrfs_fs_devices *seed_devices = NULL;
1269 mutex_lock(&uuid_mutex);
1270 ret = close_fs_devices(fs_devices);
1271 if (!fs_devices->opened) {
1272 seed_devices = fs_devices->seed;
1273 fs_devices->seed = NULL;
1275 mutex_unlock(&uuid_mutex);
1277 while (seed_devices) {
1278 fs_devices = seed_devices;
1279 seed_devices = fs_devices->seed;
1280 close_fs_devices(fs_devices);
1281 free_fs_devices(fs_devices);
1286 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1287 fmode_t flags, void *holder)
1289 struct btrfs_device *device;
1290 struct btrfs_device *latest_dev = NULL;
1293 flags |= FMODE_EXCL;
1295 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1296 /* Just open everything we can; ignore failures here */
1297 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1301 device->generation > latest_dev->generation)
1302 latest_dev = device;
1304 if (fs_devices->open_devices == 0) {
1308 fs_devices->opened = 1;
1309 fs_devices->latest_bdev = latest_dev->bdev;
1310 fs_devices->total_rw_bytes = 0;
1315 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1317 struct btrfs_device *dev1, *dev2;
1319 dev1 = list_entry(a, struct btrfs_device, dev_list);
1320 dev2 = list_entry(b, struct btrfs_device, dev_list);
1322 if (dev1->devid < dev2->devid)
1324 else if (dev1->devid > dev2->devid)
1329 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1330 fmode_t flags, void *holder)
1334 lockdep_assert_held(&uuid_mutex);
1336 mutex_lock(&fs_devices->device_list_mutex);
1337 if (fs_devices->opened) {
1338 fs_devices->opened++;
1341 list_sort(NULL, &fs_devices->devices, devid_cmp);
1342 ret = open_fs_devices(fs_devices, flags, holder);
1344 mutex_unlock(&fs_devices->device_list_mutex);
1349 static void btrfs_release_disk_super(struct page *page)
1355 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1357 struct btrfs_super_block **disk_super)
1362 /* make sure our super fits in the device */
1363 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1366 /* make sure our super fits in the page */
1367 if (sizeof(**disk_super) > PAGE_SIZE)
1370 /* make sure our super doesn't straddle pages on disk */
1371 index = bytenr >> PAGE_SHIFT;
1372 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1375 /* pull in the page with our super */
1376 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1379 if (IS_ERR_OR_NULL(*page))
1384 /* align our pointer to the offset of the super block */
1385 *disk_super = p + (bytenr & ~PAGE_MASK);
1387 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1388 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1389 btrfs_release_disk_super(*page);
1393 if ((*disk_super)->label[0] &&
1394 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1395 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1401 * Look for a btrfs signature on a device. This may be called out of the mount path
1402 * and we are not allowed to call set_blocksize during the scan. The superblock
1403 * is read via pagecache
1405 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1408 struct btrfs_super_block *disk_super;
1409 bool new_device_added = false;
1410 struct btrfs_device *device = NULL;
1411 struct block_device *bdev;
1415 lockdep_assert_held(&uuid_mutex);
1418 * we would like to check all the supers, but that would make
1419 * a btrfs mount succeed after a mkfs from a different FS.
1420 * So, we need to add a special mount option to scan for
1421 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1423 bytenr = btrfs_sb_offset(0);
1424 flags |= FMODE_EXCL;
1426 bdev = blkdev_get_by_path(path, flags, holder);
1428 return ERR_CAST(bdev);
1430 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1431 device = ERR_PTR(-EINVAL);
1432 goto error_bdev_put;
1435 device = device_list_add(path, disk_super, &new_device_added);
1436 if (!IS_ERR(device)) {
1437 if (new_device_added)
1438 btrfs_free_stale_devices(path, device);
1441 btrfs_release_disk_super(page);
1444 blkdev_put(bdev, flags);
1449 static int contains_pending_extent(struct btrfs_transaction *transaction,
1450 struct btrfs_device *device,
1451 u64 *start, u64 len)
1453 struct btrfs_fs_info *fs_info = device->fs_info;
1454 struct extent_map *em;
1455 struct list_head *search_list = &fs_info->pinned_chunks;
1457 u64 physical_start = *start;
1460 search_list = &transaction->pending_chunks;
1462 list_for_each_entry(em, search_list, list) {
1463 struct map_lookup *map;
1466 map = em->map_lookup;
1467 for (i = 0; i < map->num_stripes; i++) {
1470 if (map->stripes[i].dev != device)
1472 if (map->stripes[i].physical >= physical_start + len ||
1473 map->stripes[i].physical + em->orig_block_len <=
1477 * Make sure that while processing the pinned list we do
1478 * not override our *start with a lower value, because
1479 * we can have pinned chunks that fall within this
1480 * device hole and that have lower physical addresses
1481 * than the pending chunks we processed before. If we
1482 * do not take this special care we can end up getting
1483 * 2 pending chunks that start at the same physical
1484 * device offsets because the end offset of a pinned
1485 * chunk can be equal to the start offset of some
1488 end = map->stripes[i].physical + em->orig_block_len;
1495 if (search_list != &fs_info->pinned_chunks) {
1496 search_list = &fs_info->pinned_chunks;
1505 * find_free_dev_extent_start - find free space in the specified device
1506 * @device: the device which we search the free space in
1507 * @num_bytes: the size of the free space that we need
1508 * @search_start: the position from which to begin the search
1509 * @start: store the start of the free space.
1510 * @len: the size of the free space. that we find, or the size
1511 * of the max free space if we don't find suitable free space
1513 * this uses a pretty simple search, the expectation is that it is
1514 * called very infrequently and that a given device has a small number
1517 * @start is used to store the start of the free space if we find. But if we
1518 * don't find suitable free space, it will be used to store the start position
1519 * of the max free space.
1521 * @len is used to store the size of the free space that we find.
1522 * But if we don't find suitable free space, it is used to store the size of
1523 * the max free space.
1525 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1526 struct btrfs_device *device, u64 num_bytes,
1527 u64 search_start, u64 *start, u64 *len)
1529 struct btrfs_fs_info *fs_info = device->fs_info;
1530 struct btrfs_root *root = fs_info->dev_root;
1531 struct btrfs_key key;
1532 struct btrfs_dev_extent *dev_extent;
1533 struct btrfs_path *path;
1538 u64 search_end = device->total_bytes;
1541 struct extent_buffer *l;
1544 * We don't want to overwrite the superblock on the drive nor any area
1545 * used by the boot loader (grub for example), so we make sure to start
1546 * at an offset of at least 1MB.
1548 search_start = max_t(u64, search_start, SZ_1M);
1550 path = btrfs_alloc_path();
1554 max_hole_start = search_start;
1558 if (search_start >= search_end ||
1559 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1564 path->reada = READA_FORWARD;
1565 path->search_commit_root = 1;
1566 path->skip_locking = 1;
1568 key.objectid = device->devid;
1569 key.offset = search_start;
1570 key.type = BTRFS_DEV_EXTENT_KEY;
1572 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1576 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1583 slot = path->slots[0];
1584 if (slot >= btrfs_header_nritems(l)) {
1585 ret = btrfs_next_leaf(root, path);
1593 btrfs_item_key_to_cpu(l, &key, slot);
1595 if (key.objectid < device->devid)
1598 if (key.objectid > device->devid)
1601 if (key.type != BTRFS_DEV_EXTENT_KEY)
1604 if (key.offset > search_start) {
1605 hole_size = key.offset - search_start;
1608 * Have to check before we set max_hole_start, otherwise
1609 * we could end up sending back this offset anyway.
1611 if (contains_pending_extent(transaction, device,
1614 if (key.offset >= search_start) {
1615 hole_size = key.offset - search_start;
1622 if (hole_size > max_hole_size) {
1623 max_hole_start = search_start;
1624 max_hole_size = hole_size;
1628 * If this free space is greater than which we need,
1629 * it must be the max free space that we have found
1630 * until now, so max_hole_start must point to the start
1631 * of this free space and the length of this free space
1632 * is stored in max_hole_size. Thus, we return
1633 * max_hole_start and max_hole_size and go back to the
1636 if (hole_size >= num_bytes) {
1642 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1643 extent_end = key.offset + btrfs_dev_extent_length(l,
1645 if (extent_end > search_start)
1646 search_start = extent_end;
1653 * At this point, search_start should be the end of
1654 * allocated dev extents, and when shrinking the device,
1655 * search_end may be smaller than search_start.
1657 if (search_end > search_start) {
1658 hole_size = search_end - search_start;
1660 if (contains_pending_extent(transaction, device, &search_start,
1662 btrfs_release_path(path);
1666 if (hole_size > max_hole_size) {
1667 max_hole_start = search_start;
1668 max_hole_size = hole_size;
1673 if (max_hole_size < num_bytes)
1679 btrfs_free_path(path);
1680 *start = max_hole_start;
1682 *len = max_hole_size;
1686 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1687 struct btrfs_device *device, u64 num_bytes,
1688 u64 *start, u64 *len)
1690 /* FIXME use last free of some kind */
1691 return find_free_dev_extent_start(trans->transaction, device,
1692 num_bytes, 0, start, len);
1695 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1696 struct btrfs_device *device,
1697 u64 start, u64 *dev_extent_len)
1699 struct btrfs_fs_info *fs_info = device->fs_info;
1700 struct btrfs_root *root = fs_info->dev_root;
1702 struct btrfs_path *path;
1703 struct btrfs_key key;
1704 struct btrfs_key found_key;
1705 struct extent_buffer *leaf = NULL;
1706 struct btrfs_dev_extent *extent = NULL;
1708 path = btrfs_alloc_path();
1712 key.objectid = device->devid;
1714 key.type = BTRFS_DEV_EXTENT_KEY;
1716 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1718 ret = btrfs_previous_item(root, path, key.objectid,
1719 BTRFS_DEV_EXTENT_KEY);
1722 leaf = path->nodes[0];
1723 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1724 extent = btrfs_item_ptr(leaf, path->slots[0],
1725 struct btrfs_dev_extent);
1726 BUG_ON(found_key.offset > start || found_key.offset +
1727 btrfs_dev_extent_length(leaf, extent) < start);
1729 btrfs_release_path(path);
1731 } else if (ret == 0) {
1732 leaf = path->nodes[0];
1733 extent = btrfs_item_ptr(leaf, path->slots[0],
1734 struct btrfs_dev_extent);
1736 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1740 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1742 ret = btrfs_del_item(trans, root, path);
1744 btrfs_handle_fs_error(fs_info, ret,
1745 "Failed to remove dev extent item");
1747 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1750 btrfs_free_path(path);
1754 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1755 struct btrfs_device *device,
1756 u64 chunk_offset, u64 start, u64 num_bytes)
1759 struct btrfs_path *path;
1760 struct btrfs_fs_info *fs_info = device->fs_info;
1761 struct btrfs_root *root = fs_info->dev_root;
1762 struct btrfs_dev_extent *extent;
1763 struct extent_buffer *leaf;
1764 struct btrfs_key key;
1766 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1767 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1768 path = btrfs_alloc_path();
1772 key.objectid = device->devid;
1774 key.type = BTRFS_DEV_EXTENT_KEY;
1775 ret = btrfs_insert_empty_item(trans, root, path, &key,
1780 leaf = path->nodes[0];
1781 extent = btrfs_item_ptr(leaf, path->slots[0],
1782 struct btrfs_dev_extent);
1783 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1784 BTRFS_CHUNK_TREE_OBJECTID);
1785 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1786 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1787 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1789 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1790 btrfs_mark_buffer_dirty(leaf);
1792 btrfs_free_path(path);
1796 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1798 struct extent_map_tree *em_tree;
1799 struct extent_map *em;
1803 em_tree = &fs_info->mapping_tree.map_tree;
1804 read_lock(&em_tree->lock);
1805 n = rb_last(&em_tree->map.rb_root);
1807 em = rb_entry(n, struct extent_map, rb_node);
1808 ret = em->start + em->len;
1810 read_unlock(&em_tree->lock);
1815 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1819 struct btrfs_key key;
1820 struct btrfs_key found_key;
1821 struct btrfs_path *path;
1823 path = btrfs_alloc_path();
1827 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1828 key.type = BTRFS_DEV_ITEM_KEY;
1829 key.offset = (u64)-1;
1831 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1835 BUG_ON(ret == 0); /* Corruption */
1837 ret = btrfs_previous_item(fs_info->chunk_root, path,
1838 BTRFS_DEV_ITEMS_OBJECTID,
1839 BTRFS_DEV_ITEM_KEY);
1843 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1845 *devid_ret = found_key.offset + 1;
1849 btrfs_free_path(path);
1854 * the device information is stored in the chunk root
1855 * the btrfs_device struct should be fully filled in
1857 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1858 struct btrfs_device *device)
1861 struct btrfs_path *path;
1862 struct btrfs_dev_item *dev_item;
1863 struct extent_buffer *leaf;
1864 struct btrfs_key key;
1867 path = btrfs_alloc_path();
1871 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1872 key.type = BTRFS_DEV_ITEM_KEY;
1873 key.offset = device->devid;
1875 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1876 &key, sizeof(*dev_item));
1880 leaf = path->nodes[0];
1881 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1883 btrfs_set_device_id(leaf, dev_item, device->devid);
1884 btrfs_set_device_generation(leaf, dev_item, 0);
1885 btrfs_set_device_type(leaf, dev_item, device->type);
1886 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1887 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1888 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1889 btrfs_set_device_total_bytes(leaf, dev_item,
1890 btrfs_device_get_disk_total_bytes(device));
1891 btrfs_set_device_bytes_used(leaf, dev_item,
1892 btrfs_device_get_bytes_used(device));
1893 btrfs_set_device_group(leaf, dev_item, 0);
1894 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1895 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1896 btrfs_set_device_start_offset(leaf, dev_item, 0);
1898 ptr = btrfs_device_uuid(dev_item);
1899 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1900 ptr = btrfs_device_fsid(dev_item);
1901 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1902 ptr, BTRFS_FSID_SIZE);
1903 btrfs_mark_buffer_dirty(leaf);
1907 btrfs_free_path(path);
1912 * Function to update ctime/mtime for a given device path.
1913 * Mainly used for ctime/mtime based probe like libblkid.
1915 static void update_dev_time(const char *path_name)
1919 filp = filp_open(path_name, O_RDWR, 0);
1922 file_update_time(filp);
1923 filp_close(filp, NULL);
1926 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1927 struct btrfs_device *device)
1929 struct btrfs_root *root = fs_info->chunk_root;
1931 struct btrfs_path *path;
1932 struct btrfs_key key;
1933 struct btrfs_trans_handle *trans;
1935 path = btrfs_alloc_path();
1939 trans = btrfs_start_transaction(root, 0);
1940 if (IS_ERR(trans)) {
1941 btrfs_free_path(path);
1942 return PTR_ERR(trans);
1944 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1945 key.type = BTRFS_DEV_ITEM_KEY;
1946 key.offset = device->devid;
1948 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1952 btrfs_abort_transaction(trans, ret);
1953 btrfs_end_transaction(trans);
1957 ret = btrfs_del_item(trans, root, path);
1959 btrfs_abort_transaction(trans, ret);
1960 btrfs_end_transaction(trans);
1964 btrfs_free_path(path);
1966 ret = btrfs_commit_transaction(trans);
1971 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1972 * filesystem. It's up to the caller to adjust that number regarding eg. device
1975 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1983 seq = read_seqbegin(&fs_info->profiles_lock);
1985 all_avail = fs_info->avail_data_alloc_bits |
1986 fs_info->avail_system_alloc_bits |
1987 fs_info->avail_metadata_alloc_bits;
1988 } while (read_seqretry(&fs_info->profiles_lock, seq));
1990 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1991 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1994 if (num_devices < btrfs_raid_array[i].devs_min) {
1995 int ret = btrfs_raid_array[i].mindev_error;
2005 static struct btrfs_device * btrfs_find_next_active_device(
2006 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2008 struct btrfs_device *next_device;
2010 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2011 if (next_device != device &&
2012 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2013 && next_device->bdev)
2021 * Helper function to check if the given device is part of s_bdev / latest_bdev
2022 * and replace it with the provided or the next active device, in the context
2023 * where this function called, there should be always be another device (or
2024 * this_dev) which is active.
2026 void btrfs_assign_next_active_device(struct btrfs_device *device,
2027 struct btrfs_device *this_dev)
2029 struct btrfs_fs_info *fs_info = device->fs_info;
2030 struct btrfs_device *next_device;
2033 next_device = this_dev;
2035 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2037 ASSERT(next_device);
2039 if (fs_info->sb->s_bdev &&
2040 (fs_info->sb->s_bdev == device->bdev))
2041 fs_info->sb->s_bdev = next_device->bdev;
2043 if (fs_info->fs_devices->latest_bdev == device->bdev)
2044 fs_info->fs_devices->latest_bdev = next_device->bdev;
2048 * Return btrfs_fs_devices::num_devices excluding the device that's being
2049 * currently replaced.
2051 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2053 u64 num_devices = fs_info->fs_devices->num_devices;
2055 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
2056 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2057 ASSERT(num_devices > 1);
2060 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
2065 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2068 struct btrfs_device *device;
2069 struct btrfs_fs_devices *cur_devices;
2070 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2074 mutex_lock(&uuid_mutex);
2076 num_devices = btrfs_num_devices(fs_info);
2078 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2082 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2084 if (IS_ERR(device)) {
2085 if (PTR_ERR(device) == -ENOENT &&
2086 strcmp(device_path, "missing") == 0)
2087 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2089 ret = PTR_ERR(device);
2093 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2094 btrfs_warn_in_rcu(fs_info,
2095 "cannot remove device %s (devid %llu) due to active swapfile",
2096 rcu_str_deref(device->name), device->devid);
2101 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2102 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2106 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2107 fs_info->fs_devices->rw_devices == 1) {
2108 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2112 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2113 mutex_lock(&fs_info->chunk_mutex);
2114 list_del_init(&device->dev_alloc_list);
2115 device->fs_devices->rw_devices--;
2116 mutex_unlock(&fs_info->chunk_mutex);
2119 mutex_unlock(&uuid_mutex);
2120 ret = btrfs_shrink_device(device, 0);
2121 mutex_lock(&uuid_mutex);
2126 * TODO: the superblock still includes this device in its num_devices
2127 * counter although write_all_supers() is not locked out. This
2128 * could give a filesystem state which requires a degraded mount.
2130 ret = btrfs_rm_dev_item(fs_info, device);
2134 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2135 btrfs_scrub_cancel_dev(fs_info, device);
2138 * the device list mutex makes sure that we don't change
2139 * the device list while someone else is writing out all
2140 * the device supers. Whoever is writing all supers, should
2141 * lock the device list mutex before getting the number of
2142 * devices in the super block (super_copy). Conversely,
2143 * whoever updates the number of devices in the super block
2144 * (super_copy) should hold the device list mutex.
2148 * In normal cases the cur_devices == fs_devices. But in case
2149 * of deleting a seed device, the cur_devices should point to
2150 * its own fs_devices listed under the fs_devices->seed.
2152 cur_devices = device->fs_devices;
2153 mutex_lock(&fs_devices->device_list_mutex);
2154 list_del_rcu(&device->dev_list);
2156 cur_devices->num_devices--;
2157 cur_devices->total_devices--;
2158 /* Update total_devices of the parent fs_devices if it's seed */
2159 if (cur_devices != fs_devices)
2160 fs_devices->total_devices--;
2162 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2163 cur_devices->missing_devices--;
2165 btrfs_assign_next_active_device(device, NULL);
2168 cur_devices->open_devices--;
2169 /* remove sysfs entry */
2170 btrfs_sysfs_rm_device_link(fs_devices, device);
2173 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2174 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2175 mutex_unlock(&fs_devices->device_list_mutex);
2178 * at this point, the device is zero sized and detached from
2179 * the devices list. All that's left is to zero out the old
2180 * supers and free the device.
2182 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2183 btrfs_scratch_superblocks(device->bdev, device->name->str);
2185 btrfs_close_bdev(device);
2186 call_rcu(&device->rcu, free_device_rcu);
2188 if (cur_devices->open_devices == 0) {
2189 while (fs_devices) {
2190 if (fs_devices->seed == cur_devices) {
2191 fs_devices->seed = cur_devices->seed;
2194 fs_devices = fs_devices->seed;
2196 cur_devices->seed = NULL;
2197 close_fs_devices(cur_devices);
2198 free_fs_devices(cur_devices);
2202 mutex_unlock(&uuid_mutex);
2206 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2207 mutex_lock(&fs_info->chunk_mutex);
2208 list_add(&device->dev_alloc_list,
2209 &fs_devices->alloc_list);
2210 device->fs_devices->rw_devices++;
2211 mutex_unlock(&fs_info->chunk_mutex);
2216 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2218 struct btrfs_fs_devices *fs_devices;
2220 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2223 * in case of fs with no seed, srcdev->fs_devices will point
2224 * to fs_devices of fs_info. However when the dev being replaced is
2225 * a seed dev it will point to the seed's local fs_devices. In short
2226 * srcdev will have its correct fs_devices in both the cases.
2228 fs_devices = srcdev->fs_devices;
2230 list_del_rcu(&srcdev->dev_list);
2231 list_del(&srcdev->dev_alloc_list);
2232 fs_devices->num_devices--;
2233 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2234 fs_devices->missing_devices--;
2236 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2237 fs_devices->rw_devices--;
2240 fs_devices->open_devices--;
2243 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2244 struct btrfs_device *srcdev)
2246 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2248 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2249 /* zero out the old super if it is writable */
2250 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2253 btrfs_close_bdev(srcdev);
2254 call_rcu(&srcdev->rcu, free_device_rcu);
2256 /* if this is no devs we rather delete the fs_devices */
2257 if (!fs_devices->num_devices) {
2258 struct btrfs_fs_devices *tmp_fs_devices;
2261 * On a mounted FS, num_devices can't be zero unless it's a
2262 * seed. In case of a seed device being replaced, the replace
2263 * target added to the sprout FS, so there will be no more
2264 * device left under the seed FS.
2266 ASSERT(fs_devices->seeding);
2268 tmp_fs_devices = fs_info->fs_devices;
2269 while (tmp_fs_devices) {
2270 if (tmp_fs_devices->seed == fs_devices) {
2271 tmp_fs_devices->seed = fs_devices->seed;
2274 tmp_fs_devices = tmp_fs_devices->seed;
2276 fs_devices->seed = NULL;
2277 close_fs_devices(fs_devices);
2278 free_fs_devices(fs_devices);
2282 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2284 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2287 mutex_lock(&fs_devices->device_list_mutex);
2289 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2292 fs_devices->open_devices--;
2294 fs_devices->num_devices--;
2296 btrfs_assign_next_active_device(tgtdev, NULL);
2298 list_del_rcu(&tgtdev->dev_list);
2300 mutex_unlock(&fs_devices->device_list_mutex);
2303 * The update_dev_time() with in btrfs_scratch_superblocks()
2304 * may lead to a call to btrfs_show_devname() which will try
2305 * to hold device_list_mutex. And here this device
2306 * is already out of device list, so we don't have to hold
2307 * the device_list_mutex lock.
2309 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2311 btrfs_close_bdev(tgtdev);
2312 call_rcu(&tgtdev->rcu, free_device_rcu);
2315 static struct btrfs_device *btrfs_find_device_by_path(
2316 struct btrfs_fs_info *fs_info, const char *device_path)
2319 struct btrfs_super_block *disk_super;
2322 struct block_device *bdev;
2323 struct buffer_head *bh;
2324 struct btrfs_device *device;
2326 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2327 fs_info->bdev_holder, 0, &bdev, &bh);
2329 return ERR_PTR(ret);
2330 disk_super = (struct btrfs_super_block *)bh->b_data;
2331 devid = btrfs_stack_device_id(&disk_super->dev_item);
2332 dev_uuid = disk_super->dev_item.uuid;
2333 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2334 device = btrfs_find_device(fs_info, devid, dev_uuid,
2335 disk_super->metadata_uuid);
2337 device = btrfs_find_device(fs_info, devid,
2338 dev_uuid, disk_super->fsid);
2342 device = ERR_PTR(-ENOENT);
2343 blkdev_put(bdev, FMODE_READ);
2347 static struct btrfs_device *btrfs_find_device_missing_or_by_path(
2348 struct btrfs_fs_info *fs_info, const char *device_path)
2350 struct btrfs_device *device = NULL;
2351 if (strcmp(device_path, "missing") == 0) {
2352 struct list_head *devices;
2353 struct btrfs_device *tmp;
2355 devices = &fs_info->fs_devices->devices;
2356 list_for_each_entry(tmp, devices, dev_list) {
2357 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2358 &tmp->dev_state) && !tmp->bdev) {
2365 return ERR_PTR(-ENOENT);
2367 device = btrfs_find_device_by_path(fs_info, device_path);
2374 * Lookup a device given by device id, or the path if the id is 0.
2376 struct btrfs_device *btrfs_find_device_by_devspec(
2377 struct btrfs_fs_info *fs_info, u64 devid, const char *devpath)
2379 struct btrfs_device *device;
2382 device = btrfs_find_device(fs_info, devid, NULL, NULL);
2384 return ERR_PTR(-ENOENT);
2386 if (!devpath || !devpath[0])
2387 return ERR_PTR(-EINVAL);
2388 device = btrfs_find_device_missing_or_by_path(fs_info, devpath);
2394 * does all the dirty work required for changing file system's UUID.
2396 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2398 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2399 struct btrfs_fs_devices *old_devices;
2400 struct btrfs_fs_devices *seed_devices;
2401 struct btrfs_super_block *disk_super = fs_info->super_copy;
2402 struct btrfs_device *device;
2405 lockdep_assert_held(&uuid_mutex);
2406 if (!fs_devices->seeding)
2409 seed_devices = alloc_fs_devices(NULL, NULL);
2410 if (IS_ERR(seed_devices))
2411 return PTR_ERR(seed_devices);
2413 old_devices = clone_fs_devices(fs_devices);
2414 if (IS_ERR(old_devices)) {
2415 kfree(seed_devices);
2416 return PTR_ERR(old_devices);
2419 list_add(&old_devices->fs_list, &fs_uuids);
2421 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2422 seed_devices->opened = 1;
2423 INIT_LIST_HEAD(&seed_devices->devices);
2424 INIT_LIST_HEAD(&seed_devices->alloc_list);
2425 mutex_init(&seed_devices->device_list_mutex);
2427 mutex_lock(&fs_devices->device_list_mutex);
2428 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2430 list_for_each_entry(device, &seed_devices->devices, dev_list)
2431 device->fs_devices = seed_devices;
2433 mutex_lock(&fs_info->chunk_mutex);
2434 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2435 mutex_unlock(&fs_info->chunk_mutex);
2437 fs_devices->seeding = 0;
2438 fs_devices->num_devices = 0;
2439 fs_devices->open_devices = 0;
2440 fs_devices->missing_devices = 0;
2441 fs_devices->rotating = 0;
2442 fs_devices->seed = seed_devices;
2444 generate_random_uuid(fs_devices->fsid);
2445 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2446 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2447 mutex_unlock(&fs_devices->device_list_mutex);
2449 super_flags = btrfs_super_flags(disk_super) &
2450 ~BTRFS_SUPER_FLAG_SEEDING;
2451 btrfs_set_super_flags(disk_super, super_flags);
2457 * Store the expected generation for seed devices in device items.
2459 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2460 struct btrfs_fs_info *fs_info)
2462 struct btrfs_root *root = fs_info->chunk_root;
2463 struct btrfs_path *path;
2464 struct extent_buffer *leaf;
2465 struct btrfs_dev_item *dev_item;
2466 struct btrfs_device *device;
2467 struct btrfs_key key;
2468 u8 fs_uuid[BTRFS_FSID_SIZE];
2469 u8 dev_uuid[BTRFS_UUID_SIZE];
2473 path = btrfs_alloc_path();
2477 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2479 key.type = BTRFS_DEV_ITEM_KEY;
2482 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2486 leaf = path->nodes[0];
2488 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2489 ret = btrfs_next_leaf(root, path);
2494 leaf = path->nodes[0];
2495 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2496 btrfs_release_path(path);
2500 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2501 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2502 key.type != BTRFS_DEV_ITEM_KEY)
2505 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2506 struct btrfs_dev_item);
2507 devid = btrfs_device_id(leaf, dev_item);
2508 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2510 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2512 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2513 BUG_ON(!device); /* Logic error */
2515 if (device->fs_devices->seeding) {
2516 btrfs_set_device_generation(leaf, dev_item,
2517 device->generation);
2518 btrfs_mark_buffer_dirty(leaf);
2526 btrfs_free_path(path);
2530 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2532 struct btrfs_root *root = fs_info->dev_root;
2533 struct request_queue *q;
2534 struct btrfs_trans_handle *trans;
2535 struct btrfs_device *device;
2536 struct block_device *bdev;
2537 struct super_block *sb = fs_info->sb;
2538 struct rcu_string *name;
2539 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2540 u64 orig_super_total_bytes;
2541 u64 orig_super_num_devices;
2542 int seeding_dev = 0;
2544 bool unlocked = false;
2546 if (sb_rdonly(sb) && !fs_devices->seeding)
2549 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2550 fs_info->bdev_holder);
2552 return PTR_ERR(bdev);
2554 if (fs_devices->seeding) {
2556 down_write(&sb->s_umount);
2557 mutex_lock(&uuid_mutex);
2560 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2562 mutex_lock(&fs_devices->device_list_mutex);
2563 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2564 if (device->bdev == bdev) {
2567 &fs_devices->device_list_mutex);
2571 mutex_unlock(&fs_devices->device_list_mutex);
2573 device = btrfs_alloc_device(fs_info, NULL, NULL);
2574 if (IS_ERR(device)) {
2575 /* we can safely leave the fs_devices entry around */
2576 ret = PTR_ERR(device);
2580 name = rcu_string_strdup(device_path, GFP_KERNEL);
2583 goto error_free_device;
2585 rcu_assign_pointer(device->name, name);
2587 trans = btrfs_start_transaction(root, 0);
2588 if (IS_ERR(trans)) {
2589 ret = PTR_ERR(trans);
2590 goto error_free_device;
2593 q = bdev_get_queue(bdev);
2594 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2595 device->generation = trans->transid;
2596 device->io_width = fs_info->sectorsize;
2597 device->io_align = fs_info->sectorsize;
2598 device->sector_size = fs_info->sectorsize;
2599 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2600 fs_info->sectorsize);
2601 device->disk_total_bytes = device->total_bytes;
2602 device->commit_total_bytes = device->total_bytes;
2603 device->fs_info = fs_info;
2604 device->bdev = bdev;
2605 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2606 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2607 device->mode = FMODE_EXCL;
2608 device->dev_stats_valid = 1;
2609 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2612 sb->s_flags &= ~SB_RDONLY;
2613 ret = btrfs_prepare_sprout(fs_info);
2615 btrfs_abort_transaction(trans, ret);
2620 device->fs_devices = fs_devices;
2622 mutex_lock(&fs_devices->device_list_mutex);
2623 mutex_lock(&fs_info->chunk_mutex);
2624 list_add_rcu(&device->dev_list, &fs_devices->devices);
2625 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2626 fs_devices->num_devices++;
2627 fs_devices->open_devices++;
2628 fs_devices->rw_devices++;
2629 fs_devices->total_devices++;
2630 fs_devices->total_rw_bytes += device->total_bytes;
2632 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2634 if (!blk_queue_nonrot(q))
2635 fs_devices->rotating = 1;
2637 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2638 btrfs_set_super_total_bytes(fs_info->super_copy,
2639 round_down(orig_super_total_bytes + device->total_bytes,
2640 fs_info->sectorsize));
2642 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2643 btrfs_set_super_num_devices(fs_info->super_copy,
2644 orig_super_num_devices + 1);
2646 /* add sysfs device entry */
2647 btrfs_sysfs_add_device_link(fs_devices, device);
2650 * we've got more storage, clear any full flags on the space
2653 btrfs_clear_space_info_full(fs_info);
2655 mutex_unlock(&fs_info->chunk_mutex);
2656 mutex_unlock(&fs_devices->device_list_mutex);
2659 mutex_lock(&fs_info->chunk_mutex);
2660 ret = init_first_rw_device(trans, fs_info);
2661 mutex_unlock(&fs_info->chunk_mutex);
2663 btrfs_abort_transaction(trans, ret);
2668 ret = btrfs_add_dev_item(trans, device);
2670 btrfs_abort_transaction(trans, ret);
2675 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2677 ret = btrfs_finish_sprout(trans, fs_info);
2679 btrfs_abort_transaction(trans, ret);
2683 /* Sprouting would change fsid of the mounted root,
2684 * so rename the fsid on the sysfs
2686 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2687 fs_info->fs_devices->fsid);
2688 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2690 "sysfs: failed to create fsid for sprout");
2693 ret = btrfs_commit_transaction(trans);
2696 mutex_unlock(&uuid_mutex);
2697 up_write(&sb->s_umount);
2700 if (ret) /* transaction commit */
2703 ret = btrfs_relocate_sys_chunks(fs_info);
2705 btrfs_handle_fs_error(fs_info, ret,
2706 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2707 trans = btrfs_attach_transaction(root);
2708 if (IS_ERR(trans)) {
2709 if (PTR_ERR(trans) == -ENOENT)
2711 ret = PTR_ERR(trans);
2715 ret = btrfs_commit_transaction(trans);
2718 /* Update ctime/mtime for libblkid */
2719 update_dev_time(device_path);
2723 btrfs_sysfs_rm_device_link(fs_devices, device);
2724 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2725 mutex_lock(&fs_info->chunk_mutex);
2726 list_del_rcu(&device->dev_list);
2727 list_del(&device->dev_alloc_list);
2728 fs_info->fs_devices->num_devices--;
2729 fs_info->fs_devices->open_devices--;
2730 fs_info->fs_devices->rw_devices--;
2731 fs_info->fs_devices->total_devices--;
2732 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2733 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2734 btrfs_set_super_total_bytes(fs_info->super_copy,
2735 orig_super_total_bytes);
2736 btrfs_set_super_num_devices(fs_info->super_copy,
2737 orig_super_num_devices);
2738 mutex_unlock(&fs_info->chunk_mutex);
2739 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2742 sb->s_flags |= SB_RDONLY;
2744 btrfs_end_transaction(trans);
2746 btrfs_free_device(device);
2748 blkdev_put(bdev, FMODE_EXCL);
2749 if (seeding_dev && !unlocked) {
2750 mutex_unlock(&uuid_mutex);
2751 up_write(&sb->s_umount);
2756 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2757 struct btrfs_device *device)
2760 struct btrfs_path *path;
2761 struct btrfs_root *root = device->fs_info->chunk_root;
2762 struct btrfs_dev_item *dev_item;
2763 struct extent_buffer *leaf;
2764 struct btrfs_key key;
2766 path = btrfs_alloc_path();
2770 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2771 key.type = BTRFS_DEV_ITEM_KEY;
2772 key.offset = device->devid;
2774 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2783 leaf = path->nodes[0];
2784 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2786 btrfs_set_device_id(leaf, dev_item, device->devid);
2787 btrfs_set_device_type(leaf, dev_item, device->type);
2788 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2789 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2790 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2791 btrfs_set_device_total_bytes(leaf, dev_item,
2792 btrfs_device_get_disk_total_bytes(device));
2793 btrfs_set_device_bytes_used(leaf, dev_item,
2794 btrfs_device_get_bytes_used(device));
2795 btrfs_mark_buffer_dirty(leaf);
2798 btrfs_free_path(path);
2802 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2803 struct btrfs_device *device, u64 new_size)
2805 struct btrfs_fs_info *fs_info = device->fs_info;
2806 struct btrfs_super_block *super_copy = fs_info->super_copy;
2807 struct btrfs_fs_devices *fs_devices;
2811 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2814 new_size = round_down(new_size, fs_info->sectorsize);
2816 mutex_lock(&fs_info->chunk_mutex);
2817 old_total = btrfs_super_total_bytes(super_copy);
2818 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2820 if (new_size <= device->total_bytes ||
2821 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2822 mutex_unlock(&fs_info->chunk_mutex);
2826 fs_devices = fs_info->fs_devices;
2828 btrfs_set_super_total_bytes(super_copy,
2829 round_down(old_total + diff, fs_info->sectorsize));
2830 device->fs_devices->total_rw_bytes += diff;
2832 btrfs_device_set_total_bytes(device, new_size);
2833 btrfs_device_set_disk_total_bytes(device, new_size);
2834 btrfs_clear_space_info_full(device->fs_info);
2835 if (list_empty(&device->resized_list))
2836 list_add_tail(&device->resized_list,
2837 &fs_devices->resized_devices);
2838 mutex_unlock(&fs_info->chunk_mutex);
2840 return btrfs_update_device(trans, device);
2843 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2845 struct btrfs_fs_info *fs_info = trans->fs_info;
2846 struct btrfs_root *root = fs_info->chunk_root;
2848 struct btrfs_path *path;
2849 struct btrfs_key key;
2851 path = btrfs_alloc_path();
2855 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2856 key.offset = chunk_offset;
2857 key.type = BTRFS_CHUNK_ITEM_KEY;
2859 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2862 else if (ret > 0) { /* Logic error or corruption */
2863 btrfs_handle_fs_error(fs_info, -ENOENT,
2864 "Failed lookup while freeing chunk.");
2869 ret = btrfs_del_item(trans, root, path);
2871 btrfs_handle_fs_error(fs_info, ret,
2872 "Failed to delete chunk item.");
2874 btrfs_free_path(path);
2878 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2880 struct btrfs_super_block *super_copy = fs_info->super_copy;
2881 struct btrfs_disk_key *disk_key;
2882 struct btrfs_chunk *chunk;
2889 struct btrfs_key key;
2891 mutex_lock(&fs_info->chunk_mutex);
2892 array_size = btrfs_super_sys_array_size(super_copy);
2894 ptr = super_copy->sys_chunk_array;
2897 while (cur < array_size) {
2898 disk_key = (struct btrfs_disk_key *)ptr;
2899 btrfs_disk_key_to_cpu(&key, disk_key);
2901 len = sizeof(*disk_key);
2903 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2904 chunk = (struct btrfs_chunk *)(ptr + len);
2905 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2906 len += btrfs_chunk_item_size(num_stripes);
2911 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2912 key.offset == chunk_offset) {
2913 memmove(ptr, ptr + len, array_size - (cur + len));
2915 btrfs_set_super_sys_array_size(super_copy, array_size);
2921 mutex_unlock(&fs_info->chunk_mutex);
2926 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2927 * @logical: Logical block offset in bytes.
2928 * @length: Length of extent in bytes.
2930 * Return: Chunk mapping or ERR_PTR.
2932 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2933 u64 logical, u64 length)
2935 struct extent_map_tree *em_tree;
2936 struct extent_map *em;
2938 em_tree = &fs_info->mapping_tree.map_tree;
2939 read_lock(&em_tree->lock);
2940 em = lookup_extent_mapping(em_tree, logical, length);
2941 read_unlock(&em_tree->lock);
2944 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2946 return ERR_PTR(-EINVAL);
2949 if (em->start > logical || em->start + em->len < logical) {
2951 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2952 logical, length, em->start, em->start + em->len);
2953 free_extent_map(em);
2954 return ERR_PTR(-EINVAL);
2957 /* callers are responsible for dropping em's ref. */
2961 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2963 struct btrfs_fs_info *fs_info = trans->fs_info;
2964 struct extent_map *em;
2965 struct map_lookup *map;
2966 u64 dev_extent_len = 0;
2968 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2970 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2973 * This is a logic error, but we don't want to just rely on the
2974 * user having built with ASSERT enabled, so if ASSERT doesn't
2975 * do anything we still error out.
2980 map = em->map_lookup;
2981 mutex_lock(&fs_info->chunk_mutex);
2982 check_system_chunk(trans, map->type);
2983 mutex_unlock(&fs_info->chunk_mutex);
2986 * Take the device list mutex to prevent races with the final phase of
2987 * a device replace operation that replaces the device object associated
2988 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2990 mutex_lock(&fs_devices->device_list_mutex);
2991 for (i = 0; i < map->num_stripes; i++) {
2992 struct btrfs_device *device = map->stripes[i].dev;
2993 ret = btrfs_free_dev_extent(trans, device,
2994 map->stripes[i].physical,
2997 mutex_unlock(&fs_devices->device_list_mutex);
2998 btrfs_abort_transaction(trans, ret);
3002 if (device->bytes_used > 0) {
3003 mutex_lock(&fs_info->chunk_mutex);
3004 btrfs_device_set_bytes_used(device,
3005 device->bytes_used - dev_extent_len);
3006 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3007 btrfs_clear_space_info_full(fs_info);
3008 mutex_unlock(&fs_info->chunk_mutex);
3011 ret = btrfs_update_device(trans, device);
3013 mutex_unlock(&fs_devices->device_list_mutex);
3014 btrfs_abort_transaction(trans, ret);
3018 mutex_unlock(&fs_devices->device_list_mutex);
3020 ret = btrfs_free_chunk(trans, chunk_offset);
3022 btrfs_abort_transaction(trans, ret);
3026 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3028 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3029 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3031 btrfs_abort_transaction(trans, ret);
3036 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3038 btrfs_abort_transaction(trans, ret);
3044 free_extent_map(em);
3048 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3050 struct btrfs_root *root = fs_info->chunk_root;
3051 struct btrfs_trans_handle *trans;
3055 * Prevent races with automatic removal of unused block groups.
3056 * After we relocate and before we remove the chunk with offset
3057 * chunk_offset, automatic removal of the block group can kick in,
3058 * resulting in a failure when calling btrfs_remove_chunk() below.
3060 * Make sure to acquire this mutex before doing a tree search (dev
3061 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3062 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3063 * we release the path used to search the chunk/dev tree and before
3064 * the current task acquires this mutex and calls us.
3066 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3068 ret = btrfs_can_relocate(fs_info, chunk_offset);
3072 /* step one, relocate all the extents inside this chunk */
3073 btrfs_scrub_pause(fs_info);
3074 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3075 btrfs_scrub_continue(fs_info);
3080 * We add the kobjects here (and after forcing data chunk creation)
3081 * since relocation is the only place we'll create chunks of a new
3082 * type at runtime. The only place where we'll remove the last
3083 * chunk of a type is the call immediately below this one. Even
3084 * so, we're protected against races with the cleaner thread since
3085 * we're covered by the delete_unused_bgs_mutex.
3087 btrfs_add_raid_kobjects(fs_info);
3089 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3091 if (IS_ERR(trans)) {
3092 ret = PTR_ERR(trans);
3093 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3098 * step two, delete the device extents and the
3099 * chunk tree entries
3101 ret = btrfs_remove_chunk(trans, chunk_offset);
3102 btrfs_end_transaction(trans);
3106 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3108 struct btrfs_root *chunk_root = fs_info->chunk_root;
3109 struct btrfs_path *path;
3110 struct extent_buffer *leaf;
3111 struct btrfs_chunk *chunk;
3112 struct btrfs_key key;
3113 struct btrfs_key found_key;
3115 bool retried = false;
3119 path = btrfs_alloc_path();
3124 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3125 key.offset = (u64)-1;
3126 key.type = BTRFS_CHUNK_ITEM_KEY;
3129 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3130 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3132 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3135 BUG_ON(ret == 0); /* Corruption */
3137 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3140 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3146 leaf = path->nodes[0];
3147 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3149 chunk = btrfs_item_ptr(leaf, path->slots[0],
3150 struct btrfs_chunk);
3151 chunk_type = btrfs_chunk_type(leaf, chunk);
3152 btrfs_release_path(path);
3154 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3155 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3161 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3163 if (found_key.offset == 0)
3165 key.offset = found_key.offset - 1;
3168 if (failed && !retried) {
3172 } else if (WARN_ON(failed && retried)) {
3176 btrfs_free_path(path);
3181 * return 1 : allocate a data chunk successfully,
3182 * return <0: errors during allocating a data chunk,
3183 * return 0 : no need to allocate a data chunk.
3185 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3188 struct btrfs_block_group_cache *cache;
3192 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3194 chunk_type = cache->flags;
3195 btrfs_put_block_group(cache);
3197 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3198 spin_lock(&fs_info->data_sinfo->lock);
3199 bytes_used = fs_info->data_sinfo->bytes_used;
3200 spin_unlock(&fs_info->data_sinfo->lock);
3203 struct btrfs_trans_handle *trans;
3206 trans = btrfs_join_transaction(fs_info->tree_root);
3208 return PTR_ERR(trans);
3210 ret = btrfs_force_chunk_alloc(trans,
3211 BTRFS_BLOCK_GROUP_DATA);
3212 btrfs_end_transaction(trans);
3216 btrfs_add_raid_kobjects(fs_info);
3224 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3225 struct btrfs_balance_control *bctl)
3227 struct btrfs_root *root = fs_info->tree_root;
3228 struct btrfs_trans_handle *trans;
3229 struct btrfs_balance_item *item;
3230 struct btrfs_disk_balance_args disk_bargs;
3231 struct btrfs_path *path;
3232 struct extent_buffer *leaf;
3233 struct btrfs_key key;
3236 path = btrfs_alloc_path();
3240 trans = btrfs_start_transaction(root, 0);
3241 if (IS_ERR(trans)) {
3242 btrfs_free_path(path);
3243 return PTR_ERR(trans);
3246 key.objectid = BTRFS_BALANCE_OBJECTID;
3247 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3250 ret = btrfs_insert_empty_item(trans, root, path, &key,
3255 leaf = path->nodes[0];
3256 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3258 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3260 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3261 btrfs_set_balance_data(leaf, item, &disk_bargs);
3262 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3263 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3264 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3265 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3267 btrfs_set_balance_flags(leaf, item, bctl->flags);
3269 btrfs_mark_buffer_dirty(leaf);
3271 btrfs_free_path(path);
3272 err = btrfs_commit_transaction(trans);
3278 static int del_balance_item(struct btrfs_fs_info *fs_info)
3280 struct btrfs_root *root = fs_info->tree_root;
3281 struct btrfs_trans_handle *trans;
3282 struct btrfs_path *path;
3283 struct btrfs_key key;
3286 path = btrfs_alloc_path();
3290 trans = btrfs_start_transaction(root, 0);
3291 if (IS_ERR(trans)) {
3292 btrfs_free_path(path);
3293 return PTR_ERR(trans);
3296 key.objectid = BTRFS_BALANCE_OBJECTID;
3297 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3300 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3308 ret = btrfs_del_item(trans, root, path);
3310 btrfs_free_path(path);
3311 err = btrfs_commit_transaction(trans);
3318 * This is a heuristic used to reduce the number of chunks balanced on
3319 * resume after balance was interrupted.
3321 static void update_balance_args(struct btrfs_balance_control *bctl)
3324 * Turn on soft mode for chunk types that were being converted.
3326 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3327 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3328 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3329 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3330 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3331 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3334 * Turn on usage filter if is not already used. The idea is
3335 * that chunks that we have already balanced should be
3336 * reasonably full. Don't do it for chunks that are being
3337 * converted - that will keep us from relocating unconverted
3338 * (albeit full) chunks.
3340 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3341 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3342 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3343 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3344 bctl->data.usage = 90;
3346 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3347 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3348 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3349 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3350 bctl->sys.usage = 90;
3352 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3353 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3354 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3355 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3356 bctl->meta.usage = 90;
3361 * Clear the balance status in fs_info and delete the balance item from disk.
3363 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3365 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3368 BUG_ON(!fs_info->balance_ctl);
3370 spin_lock(&fs_info->balance_lock);
3371 fs_info->balance_ctl = NULL;
3372 spin_unlock(&fs_info->balance_lock);
3375 ret = del_balance_item(fs_info);
3377 btrfs_handle_fs_error(fs_info, ret, NULL);
3381 * Balance filters. Return 1 if chunk should be filtered out
3382 * (should not be balanced).
3384 static int chunk_profiles_filter(u64 chunk_type,
3385 struct btrfs_balance_args *bargs)
3387 chunk_type = chunk_to_extended(chunk_type) &
3388 BTRFS_EXTENDED_PROFILE_MASK;
3390 if (bargs->profiles & chunk_type)
3396 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3397 struct btrfs_balance_args *bargs)
3399 struct btrfs_block_group_cache *cache;
3401 u64 user_thresh_min;
3402 u64 user_thresh_max;
3405 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3406 chunk_used = btrfs_block_group_used(&cache->item);
3408 if (bargs->usage_min == 0)
3409 user_thresh_min = 0;
3411 user_thresh_min = div_factor_fine(cache->key.offset,
3414 if (bargs->usage_max == 0)
3415 user_thresh_max = 1;
3416 else if (bargs->usage_max > 100)
3417 user_thresh_max = cache->key.offset;
3419 user_thresh_max = div_factor_fine(cache->key.offset,
3422 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3425 btrfs_put_block_group(cache);
3429 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3430 u64 chunk_offset, struct btrfs_balance_args *bargs)
3432 struct btrfs_block_group_cache *cache;
3433 u64 chunk_used, user_thresh;
3436 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3437 chunk_used = btrfs_block_group_used(&cache->item);
3439 if (bargs->usage_min == 0)
3441 else if (bargs->usage > 100)
3442 user_thresh = cache->key.offset;
3444 user_thresh = div_factor_fine(cache->key.offset,
3447 if (chunk_used < user_thresh)
3450 btrfs_put_block_group(cache);
3454 static int chunk_devid_filter(struct extent_buffer *leaf,
3455 struct btrfs_chunk *chunk,
3456 struct btrfs_balance_args *bargs)
3458 struct btrfs_stripe *stripe;
3459 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3462 for (i = 0; i < num_stripes; i++) {
3463 stripe = btrfs_stripe_nr(chunk, i);
3464 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3471 /* [pstart, pend) */
3472 static int chunk_drange_filter(struct extent_buffer *leaf,
3473 struct btrfs_chunk *chunk,
3474 struct btrfs_balance_args *bargs)
3476 struct btrfs_stripe *stripe;
3477 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3483 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3486 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3487 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3488 factor = num_stripes / 2;
3489 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3490 factor = num_stripes - 1;
3491 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3492 factor = num_stripes - 2;
3494 factor = num_stripes;
3497 for (i = 0; i < num_stripes; i++) {
3498 stripe = btrfs_stripe_nr(chunk, i);
3499 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3502 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3503 stripe_length = btrfs_chunk_length(leaf, chunk);
3504 stripe_length = div_u64(stripe_length, factor);
3506 if (stripe_offset < bargs->pend &&
3507 stripe_offset + stripe_length > bargs->pstart)
3514 /* [vstart, vend) */
3515 static int chunk_vrange_filter(struct extent_buffer *leaf,
3516 struct btrfs_chunk *chunk,
3518 struct btrfs_balance_args *bargs)
3520 if (chunk_offset < bargs->vend &&
3521 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3522 /* at least part of the chunk is inside this vrange */
3528 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3529 struct btrfs_chunk *chunk,
3530 struct btrfs_balance_args *bargs)
3532 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3534 if (bargs->stripes_min <= num_stripes
3535 && num_stripes <= bargs->stripes_max)
3541 static int chunk_soft_convert_filter(u64 chunk_type,
3542 struct btrfs_balance_args *bargs)
3544 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3547 chunk_type = chunk_to_extended(chunk_type) &
3548 BTRFS_EXTENDED_PROFILE_MASK;
3550 if (bargs->target == chunk_type)
3556 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3557 struct extent_buffer *leaf,
3558 struct btrfs_chunk *chunk, u64 chunk_offset)
3560 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3561 struct btrfs_balance_args *bargs = NULL;
3562 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3565 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3566 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3570 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3571 bargs = &bctl->data;
3572 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3574 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3575 bargs = &bctl->meta;
3577 /* profiles filter */
3578 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3579 chunk_profiles_filter(chunk_type, bargs)) {
3584 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3585 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3587 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3588 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3593 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3594 chunk_devid_filter(leaf, chunk, bargs)) {
3598 /* drange filter, makes sense only with devid filter */
3599 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3600 chunk_drange_filter(leaf, chunk, bargs)) {
3605 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3606 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3610 /* stripes filter */
3611 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3612 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3616 /* soft profile changing mode */
3617 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3618 chunk_soft_convert_filter(chunk_type, bargs)) {
3623 * limited by count, must be the last filter
3625 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3626 if (bargs->limit == 0)
3630 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3632 * Same logic as the 'limit' filter; the minimum cannot be
3633 * determined here because we do not have the global information
3634 * about the count of all chunks that satisfy the filters.
3636 if (bargs->limit_max == 0)
3645 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3647 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3648 struct btrfs_root *chunk_root = fs_info->chunk_root;
3649 struct btrfs_root *dev_root = fs_info->dev_root;
3650 struct list_head *devices;
3651 struct btrfs_device *device;
3655 struct btrfs_chunk *chunk;
3656 struct btrfs_path *path = NULL;
3657 struct btrfs_key key;
3658 struct btrfs_key found_key;
3659 struct btrfs_trans_handle *trans;
3660 struct extent_buffer *leaf;
3663 int enospc_errors = 0;
3664 bool counting = true;
3665 /* The single value limit and min/max limits use the same bytes in the */
3666 u64 limit_data = bctl->data.limit;
3667 u64 limit_meta = bctl->meta.limit;
3668 u64 limit_sys = bctl->sys.limit;
3672 int chunk_reserved = 0;
3674 /* step one make some room on all the devices */
3675 devices = &fs_info->fs_devices->devices;
3676 list_for_each_entry(device, devices, dev_list) {
3677 old_size = btrfs_device_get_total_bytes(device);
3678 size_to_free = div_factor(old_size, 1);
3679 size_to_free = min_t(u64, size_to_free, SZ_1M);
3680 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3681 btrfs_device_get_total_bytes(device) -
3682 btrfs_device_get_bytes_used(device) > size_to_free ||
3683 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3686 ret = btrfs_shrink_device(device, old_size - size_to_free);
3690 /* btrfs_shrink_device never returns ret > 0 */
3695 trans = btrfs_start_transaction(dev_root, 0);
3696 if (IS_ERR(trans)) {
3697 ret = PTR_ERR(trans);
3698 btrfs_info_in_rcu(fs_info,
3699 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3700 rcu_str_deref(device->name), ret,
3701 old_size, old_size - size_to_free);
3705 ret = btrfs_grow_device(trans, device, old_size);
3707 btrfs_end_transaction(trans);
3708 /* btrfs_grow_device never returns ret > 0 */
3710 btrfs_info_in_rcu(fs_info,
3711 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3712 rcu_str_deref(device->name), ret,
3713 old_size, old_size - size_to_free);
3717 btrfs_end_transaction(trans);
3720 /* step two, relocate all the chunks */
3721 path = btrfs_alloc_path();
3727 /* zero out stat counters */
3728 spin_lock(&fs_info->balance_lock);
3729 memset(&bctl->stat, 0, sizeof(bctl->stat));
3730 spin_unlock(&fs_info->balance_lock);