1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/mm.h>
9 #include <linux/slab.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>
19 #include "extent_map.h"
21 #include "transaction.h"
22 #include "print-tree.h"
25 #include "async-thread.h"
26 #include "check-integrity.h"
27 #include "rcu-string.h"
28 #include "dev-replace.h"
30 #include "tree-checker.h"
31 #include "space-info.h"
32 #include "block-group.h"
35 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
36 [BTRFS_RAID_RAID10] = {
39 .devs_max = 0, /* 0 == as many as possible */
41 .tolerated_failures = 1,
45 .raid_name = "raid10",
46 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
47 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
49 [BTRFS_RAID_RAID1] = {
54 .tolerated_failures = 1,
59 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
60 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
62 [BTRFS_RAID_RAID1C3] = {
67 .tolerated_failures = 2,
71 .raid_name = "raid1c3",
72 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
73 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
75 [BTRFS_RAID_RAID1C4] = {
80 .tolerated_failures = 3,
84 .raid_name = "raid1c4",
85 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
86 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
93 .tolerated_failures = 0,
98 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
101 [BTRFS_RAID_RAID0] = {
106 .tolerated_failures = 0,
110 .raid_name = "raid0",
111 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
114 [BTRFS_RAID_SINGLE] = {
119 .tolerated_failures = 0,
123 .raid_name = "single",
127 [BTRFS_RAID_RAID5] = {
132 .tolerated_failures = 1,
136 .raid_name = "raid5",
137 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
138 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
140 [BTRFS_RAID_RAID6] = {
145 .tolerated_failures = 2,
149 .raid_name = "raid6",
150 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
151 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
155 const char *btrfs_bg_type_to_raid_name(u64 flags)
157 const int index = btrfs_bg_flags_to_raid_index(flags);
159 if (index >= BTRFS_NR_RAID_TYPES)
162 return btrfs_raid_array[index].raid_name;
166 * Fill @buf with textual description of @bg_flags, no more than @size_buf
167 * bytes including terminating null byte.
169 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
174 u64 flags = bg_flags;
175 u32 size_bp = size_buf;
182 #define DESCRIBE_FLAG(flag, desc) \
184 if (flags & (flag)) { \
185 ret = snprintf(bp, size_bp, "%s|", (desc)); \
186 if (ret < 0 || ret >= size_bp) \
194 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
195 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
196 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
198 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
199 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
200 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
201 btrfs_raid_array[i].raid_name);
205 ret = snprintf(bp, size_bp, "0x%llx|", flags);
209 if (size_bp < size_buf)
210 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
213 * The text is trimmed, it's up to the caller to provide sufficiently
219 static int init_first_rw_device(struct btrfs_trans_handle *trans);
220 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
221 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
222 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
223 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
224 enum btrfs_map_op op,
225 u64 logical, u64 *length,
226 struct btrfs_bio **bbio_ret,
227 int mirror_num, int need_raid_map);
233 * There are several mutexes that protect manipulation of devices and low-level
234 * structures like chunks but not block groups, extents or files
236 * uuid_mutex (global lock)
237 * ------------------------
238 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
239 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
240 * device) or requested by the device= mount option
242 * the mutex can be very coarse and can cover long-running operations
244 * protects: updates to fs_devices counters like missing devices, rw devices,
245 * seeding, structure cloning, opening/closing devices at mount/umount time
247 * global::fs_devs - add, remove, updates to the global list
249 * does not protect: manipulation of the fs_devices::devices list in general
250 * but in mount context it could be used to exclude list modifications by eg.
253 * btrfs_device::name - renames (write side), read is RCU
255 * fs_devices::device_list_mutex (per-fs, with RCU)
256 * ------------------------------------------------
257 * protects updates to fs_devices::devices, ie. adding and deleting
259 * simple list traversal with read-only actions can be done with RCU protection
261 * may be used to exclude some operations from running concurrently without any
262 * modifications to the list (see write_all_supers)
264 * Is not required at mount and close times, because our device list is
265 * protected by the uuid_mutex at that point.
269 * protects balance structures (status, state) and context accessed from
270 * several places (internally, ioctl)
274 * protects chunks, adding or removing during allocation, trim or when a new
275 * device is added/removed. Additionally it also protects post_commit_list of
276 * individual devices, since they can be added to the transaction's
277 * post_commit_list only with chunk_mutex held.
281 * a big lock that is held by the cleaner thread and prevents running subvolume
282 * cleaning together with relocation or delayed iputs
294 * Exclusive operations
295 * ====================
297 * Maintains the exclusivity of the following operations that apply to the
298 * whole filesystem and cannot run in parallel.
303 * - Device replace (*)
306 * The device operations (as above) can be in one of the following states:
312 * Only device operations marked with (*) can go into the Paused state for the
315 * - ioctl (only Balance can be Paused through ioctl)
316 * - filesystem remounted as read-only
317 * - filesystem unmounted and mounted as read-only
318 * - system power-cycle and filesystem mounted as read-only
319 * - filesystem or device errors leading to forced read-only
321 * The status of exclusive operation is set and cleared atomically.
322 * During the course of Paused state, fs_info::exclusive_operation remains set.
323 * A device operation in Paused or Running state can be canceled or resumed
324 * either by ioctl (Balance only) or when remounted as read-write.
325 * The exclusive status is cleared when the device operation is canceled or
329 DEFINE_MUTEX(uuid_mutex);
330 static LIST_HEAD(fs_uuids);
331 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
337 * alloc_fs_devices - allocate struct btrfs_fs_devices
338 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
339 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
341 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
342 * The returned struct is not linked onto any lists and can be destroyed with
343 * kfree() right away.
345 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
346 const u8 *metadata_fsid)
348 struct btrfs_fs_devices *fs_devs;
350 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
352 return ERR_PTR(-ENOMEM);
354 mutex_init(&fs_devs->device_list_mutex);
356 INIT_LIST_HEAD(&fs_devs->devices);
357 INIT_LIST_HEAD(&fs_devs->alloc_list);
358 INIT_LIST_HEAD(&fs_devs->fs_list);
359 INIT_LIST_HEAD(&fs_devs->seed_list);
361 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
364 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
366 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
371 void btrfs_free_device(struct btrfs_device *device)
373 WARN_ON(!list_empty(&device->post_commit_list));
374 rcu_string_free(device->name);
375 extent_io_tree_release(&device->alloc_state);
376 bio_put(device->flush_bio);
380 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
382 struct btrfs_device *device;
383 WARN_ON(fs_devices->opened);
384 while (!list_empty(&fs_devices->devices)) {
385 device = list_entry(fs_devices->devices.next,
386 struct btrfs_device, dev_list);
387 list_del(&device->dev_list);
388 btrfs_free_device(device);
393 void __exit btrfs_cleanup_fs_uuids(void)
395 struct btrfs_fs_devices *fs_devices;
397 while (!list_empty(&fs_uuids)) {
398 fs_devices = list_entry(fs_uuids.next,
399 struct btrfs_fs_devices, fs_list);
400 list_del(&fs_devices->fs_list);
401 free_fs_devices(fs_devices);
406 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
407 * Returned struct is not linked onto any lists and must be destroyed using
410 static struct btrfs_device *__alloc_device(struct btrfs_fs_info *fs_info)
412 struct btrfs_device *dev;
414 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
416 return ERR_PTR(-ENOMEM);
419 * Preallocate a bio that's always going to be used for flushing device
420 * barriers and matches the device lifespan
422 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
423 if (!dev->flush_bio) {
425 return ERR_PTR(-ENOMEM);
428 INIT_LIST_HEAD(&dev->dev_list);
429 INIT_LIST_HEAD(&dev->dev_alloc_list);
430 INIT_LIST_HEAD(&dev->post_commit_list);
432 atomic_set(&dev->reada_in_flight, 0);
433 atomic_set(&dev->dev_stats_ccnt, 0);
434 btrfs_device_data_ordered_init(dev, fs_info);
435 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
436 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
437 extent_io_tree_init(fs_info, &dev->alloc_state,
438 IO_TREE_DEVICE_ALLOC_STATE, NULL);
443 static noinline struct btrfs_fs_devices *find_fsid(
444 const u8 *fsid, const u8 *metadata_fsid)
446 struct btrfs_fs_devices *fs_devices;
450 /* Handle non-split brain cases */
451 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
453 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
454 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
455 BTRFS_FSID_SIZE) == 0)
458 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
465 static struct btrfs_fs_devices *find_fsid_with_metadata_uuid(
466 struct btrfs_super_block *disk_super)
469 struct btrfs_fs_devices *fs_devices;
472 * Handle scanned device having completed its fsid change but
473 * belonging to a fs_devices that was created by first scanning
474 * a device which didn't have its fsid/metadata_uuid changed
475 * at all and the CHANGING_FSID_V2 flag set.
477 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
478 if (fs_devices->fsid_change &&
479 memcmp(disk_super->metadata_uuid, fs_devices->fsid,
480 BTRFS_FSID_SIZE) == 0 &&
481 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
482 BTRFS_FSID_SIZE) == 0) {
487 * Handle scanned device having completed its fsid change but
488 * belonging to a fs_devices that was created by a device that
489 * has an outdated pair of fsid/metadata_uuid and
490 * CHANGING_FSID_V2 flag set.
492 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
493 if (fs_devices->fsid_change &&
494 memcmp(fs_devices->metadata_uuid,
495 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
496 memcmp(disk_super->metadata_uuid, fs_devices->metadata_uuid,
497 BTRFS_FSID_SIZE) == 0) {
502 return find_fsid(disk_super->fsid, disk_super->metadata_uuid);
507 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
508 int flush, struct block_device **bdev,
509 struct btrfs_super_block **disk_super)
513 *bdev = blkdev_get_by_path(device_path, flags, holder);
516 ret = PTR_ERR(*bdev);
521 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
522 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
524 blkdev_put(*bdev, flags);
527 invalidate_bdev(*bdev);
528 *disk_super = btrfs_read_dev_super(*bdev);
529 if (IS_ERR(*disk_super)) {
530 ret = PTR_ERR(*disk_super);
531 blkdev_put(*bdev, flags);
542 static bool device_path_matched(const char *path, struct btrfs_device *device)
547 found = strcmp(rcu_str_deref(device->name), path);
554 * Search and remove all stale (devices which are not mounted) devices.
555 * When both inputs are NULL, it will search and release all stale devices.
556 * path: Optional. When provided will it release all unmounted devices
557 * matching this path only.
558 * skip_dev: Optional. Will skip this device when searching for the stale
560 * Return: 0 for success or if @path is NULL.
561 * -EBUSY if @path is a mounted device.
562 * -ENOENT if @path does not match any device in the list.
564 static int btrfs_free_stale_devices(const char *path,
565 struct btrfs_device *skip_device)
567 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
568 struct btrfs_device *device, *tmp_device;
574 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
576 mutex_lock(&fs_devices->device_list_mutex);
577 list_for_each_entry_safe(device, tmp_device,
578 &fs_devices->devices, dev_list) {
579 if (skip_device && skip_device == device)
581 if (path && !device->name)
583 if (path && !device_path_matched(path, device))
585 if (fs_devices->opened) {
586 /* for an already deleted device return 0 */
587 if (path && ret != 0)
592 /* delete the stale device */
593 fs_devices->num_devices--;
594 list_del(&device->dev_list);
595 btrfs_free_device(device);
599 mutex_unlock(&fs_devices->device_list_mutex);
601 if (fs_devices->num_devices == 0) {
602 btrfs_sysfs_remove_fsid(fs_devices);
603 list_del(&fs_devices->fs_list);
604 free_fs_devices(fs_devices);
612 * This is only used on mount, and we are protected from competing things
613 * messing with our fs_devices by the uuid_mutex, thus we do not need the
614 * fs_devices->device_list_mutex here.
616 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
617 struct btrfs_device *device, fmode_t flags,
620 struct request_queue *q;
621 struct block_device *bdev;
622 struct btrfs_super_block *disk_super;
631 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
636 devid = btrfs_stack_device_id(&disk_super->dev_item);
637 if (devid != device->devid)
638 goto error_free_page;
640 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
641 goto error_free_page;
643 device->generation = btrfs_super_generation(disk_super);
645 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
646 if (btrfs_super_incompat_flags(disk_super) &
647 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
649 "BTRFS: Invalid seeding and uuid-changed device detected\n");
650 goto error_free_page;
653 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
654 fs_devices->seeding = true;
656 if (bdev_read_only(bdev))
657 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
659 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
662 q = bdev_get_queue(bdev);
663 if (!blk_queue_nonrot(q))
664 fs_devices->rotating = true;
667 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
668 device->mode = flags;
670 fs_devices->open_devices++;
671 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
672 device->devid != BTRFS_DEV_REPLACE_DEVID) {
673 fs_devices->rw_devices++;
674 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
676 btrfs_release_disk_super(disk_super);
681 btrfs_release_disk_super(disk_super);
682 blkdev_put(bdev, flags);
688 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
689 * being created with a disk that has already completed its fsid change. Such
690 * disk can belong to an fs which has its FSID changed or to one which doesn't.
691 * Handle both cases here.
693 static struct btrfs_fs_devices *find_fsid_inprogress(
694 struct btrfs_super_block *disk_super)
696 struct btrfs_fs_devices *fs_devices;
698 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
699 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
700 BTRFS_FSID_SIZE) != 0 &&
701 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
702 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
707 return find_fsid(disk_super->fsid, NULL);
711 static struct btrfs_fs_devices *find_fsid_changed(
712 struct btrfs_super_block *disk_super)
714 struct btrfs_fs_devices *fs_devices;
717 * Handles the case where scanned device is part of an fs that had
718 * multiple successful changes of FSID but curently device didn't
719 * observe it. Meaning our fsid will be different than theirs. We need
720 * to handle two subcases :
721 * 1 - The fs still continues to have different METADATA/FSID uuids.
722 * 2 - The fs is switched back to its original FSID (METADATA/FSID
725 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
727 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
728 BTRFS_FSID_SIZE) != 0 &&
729 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
730 BTRFS_FSID_SIZE) == 0 &&
731 memcmp(fs_devices->fsid, disk_super->fsid,
732 BTRFS_FSID_SIZE) != 0)
735 /* Unchanged UUIDs */
736 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
737 BTRFS_FSID_SIZE) == 0 &&
738 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
739 BTRFS_FSID_SIZE) == 0)
746 static struct btrfs_fs_devices *find_fsid_reverted_metadata(
747 struct btrfs_super_block *disk_super)
749 struct btrfs_fs_devices *fs_devices;
752 * Handle the case where the scanned device is part of an fs whose last
753 * metadata UUID change reverted it to the original FSID. At the same
754 * time * fs_devices was first created by another constitutent device
755 * which didn't fully observe the operation. This results in an
756 * btrfs_fs_devices created with metadata/fsid different AND
757 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
758 * fs_devices equal to the FSID of the disk.
760 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
761 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
762 BTRFS_FSID_SIZE) != 0 &&
763 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
764 BTRFS_FSID_SIZE) == 0 &&
765 fs_devices->fsid_change)
772 * Add new device to list of registered devices
775 * device pointer which was just added or updated when successful
776 * error pointer when failed
778 static noinline struct btrfs_device *device_list_add(const char *path,
779 struct btrfs_super_block *disk_super,
780 bool *new_device_added)
782 struct btrfs_device *device;
783 struct btrfs_fs_devices *fs_devices = NULL;
784 struct rcu_string *name;
785 u64 found_transid = btrfs_super_generation(disk_super);
786 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
787 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
788 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
789 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
790 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
792 if (fsid_change_in_progress) {
793 if (!has_metadata_uuid)
794 fs_devices = find_fsid_inprogress(disk_super);
796 fs_devices = find_fsid_changed(disk_super);
797 } else if (has_metadata_uuid) {
798 fs_devices = find_fsid_with_metadata_uuid(disk_super);
800 fs_devices = find_fsid_reverted_metadata(disk_super);
802 fs_devices = find_fsid(disk_super->fsid, NULL);
807 if (has_metadata_uuid)
808 fs_devices = alloc_fs_devices(disk_super->fsid,
809 disk_super->metadata_uuid);
811 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
813 if (IS_ERR(fs_devices))
814 return ERR_CAST(fs_devices);
816 fs_devices->fsid_change = fsid_change_in_progress;
818 mutex_lock(&fs_devices->device_list_mutex);
819 list_add(&fs_devices->fs_list, &fs_uuids);
823 mutex_lock(&fs_devices->device_list_mutex);
824 device = btrfs_find_device(fs_devices, devid,
825 disk_super->dev_item.uuid, NULL, false);
828 * If this disk has been pulled into an fs devices created by
829 * a device which had the CHANGING_FSID_V2 flag then replace the
830 * metadata_uuid/fsid values of the fs_devices.
832 if (fs_devices->fsid_change &&
833 found_transid > fs_devices->latest_generation) {
834 memcpy(fs_devices->fsid, disk_super->fsid,
837 if (has_metadata_uuid)
838 memcpy(fs_devices->metadata_uuid,
839 disk_super->metadata_uuid,
842 memcpy(fs_devices->metadata_uuid,
843 disk_super->fsid, BTRFS_FSID_SIZE);
845 fs_devices->fsid_change = false;
850 if (fs_devices->opened) {
851 mutex_unlock(&fs_devices->device_list_mutex);
852 return ERR_PTR(-EBUSY);
855 device = btrfs_alloc_device(NULL, &devid,
856 disk_super->dev_item.uuid);
857 if (IS_ERR(device)) {
858 mutex_unlock(&fs_devices->device_list_mutex);
859 /* we can safely leave the fs_devices entry around */
863 name = rcu_string_strdup(path, GFP_NOFS);
865 btrfs_free_device(device);
866 mutex_unlock(&fs_devices->device_list_mutex);
867 return ERR_PTR(-ENOMEM);
869 rcu_assign_pointer(device->name, name);
871 list_add_rcu(&device->dev_list, &fs_devices->devices);
872 fs_devices->num_devices++;
874 device->fs_devices = fs_devices;
875 *new_device_added = true;
877 if (disk_super->label[0])
879 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
880 disk_super->label, devid, found_transid, path,
881 current->comm, task_pid_nr(current));
884 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
885 disk_super->fsid, devid, found_transid, path,
886 current->comm, task_pid_nr(current));
888 } else if (!device->name || strcmp(device->name->str, path)) {
890 * When FS is already mounted.
891 * 1. If you are here and if the device->name is NULL that
892 * means this device was missing at time of FS mount.
893 * 2. If you are here and if the device->name is different
894 * from 'path' that means either
895 * a. The same device disappeared and reappeared with
897 * b. The missing-disk-which-was-replaced, has
900 * We must allow 1 and 2a above. But 2b would be a spurious
903 * Further in case of 1 and 2a above, the disk at 'path'
904 * would have missed some transaction when it was away and
905 * in case of 2a the stale bdev has to be updated as well.
906 * 2b must not be allowed at all time.
910 * For now, we do allow update to btrfs_fs_device through the
911 * btrfs dev scan cli after FS has been mounted. We're still
912 * tracking a problem where systems fail mount by subvolume id
913 * when we reject replacement on a mounted FS.
915 if (!fs_devices->opened && found_transid < device->generation) {
917 * That is if the FS is _not_ mounted and if you
918 * are here, that means there is more than one
919 * disk with same uuid and devid.We keep the one
920 * with larger generation number or the last-in if
921 * generation are equal.
923 mutex_unlock(&fs_devices->device_list_mutex);
924 return ERR_PTR(-EEXIST);
928 * We are going to replace the device path for a given devid,
929 * make sure it's the same device if the device is mounted
935 error = lookup_bdev(path, &path_dev);
937 mutex_unlock(&fs_devices->device_list_mutex);
938 return ERR_PTR(error);
941 if (device->bdev->bd_dev != path_dev) {
942 mutex_unlock(&fs_devices->device_list_mutex);
943 btrfs_warn_in_rcu(device->fs_info,
944 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
945 path, devid, found_transid,
947 task_pid_nr(current));
948 return ERR_PTR(-EEXIST);
950 btrfs_info_in_rcu(device->fs_info,
951 "devid %llu device path %s changed to %s scanned by %s (%d)",
952 devid, rcu_str_deref(device->name),
954 task_pid_nr(current));
957 name = rcu_string_strdup(path, GFP_NOFS);
959 mutex_unlock(&fs_devices->device_list_mutex);
960 return ERR_PTR(-ENOMEM);
962 rcu_string_free(device->name);
963 rcu_assign_pointer(device->name, name);
964 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
965 fs_devices->missing_devices--;
966 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
971 * Unmount does not free the btrfs_device struct but would zero
972 * generation along with most of the other members. So just update
973 * it back. We need it to pick the disk with largest generation
976 if (!fs_devices->opened) {
977 device->generation = found_transid;
978 fs_devices->latest_generation = max_t(u64, found_transid,
979 fs_devices->latest_generation);
982 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
984 mutex_unlock(&fs_devices->device_list_mutex);
988 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
990 struct btrfs_fs_devices *fs_devices;
991 struct btrfs_device *device;
992 struct btrfs_device *orig_dev;
995 fs_devices = alloc_fs_devices(orig->fsid, NULL);
996 if (IS_ERR(fs_devices))
999 mutex_lock(&orig->device_list_mutex);
1000 fs_devices->total_devices = orig->total_devices;
1002 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1003 struct rcu_string *name;
1005 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1007 if (IS_ERR(device)) {
1008 ret = PTR_ERR(device);
1013 * This is ok to do without rcu read locked because we hold the
1014 * uuid mutex so nothing we touch in here is going to disappear.
1016 if (orig_dev->name) {
1017 name = rcu_string_strdup(orig_dev->name->str,
1020 btrfs_free_device(device);
1024 rcu_assign_pointer(device->name, name);
1027 list_add(&device->dev_list, &fs_devices->devices);
1028 device->fs_devices = fs_devices;
1029 fs_devices->num_devices++;
1031 mutex_unlock(&orig->device_list_mutex);
1034 mutex_unlock(&orig->device_list_mutex);
1035 free_fs_devices(fs_devices);
1036 return ERR_PTR(ret);
1039 static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
1040 int step, struct btrfs_device **latest_dev)
1042 struct btrfs_device *device, *next;
1044 /* This is the initialized path, it is safe to release the devices. */
1045 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1046 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
1047 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1048 &device->dev_state) &&
1049 !test_bit(BTRFS_DEV_STATE_MISSING,
1050 &device->dev_state) &&
1052 device->generation > (*latest_dev)->generation)) {
1053 *latest_dev = device;
1059 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1060 * in btrfs_init_dev_replace() so just continue.
1062 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1066 blkdev_put(device->bdev, device->mode);
1067 device->bdev = NULL;
1068 fs_devices->open_devices--;
1070 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1071 list_del_init(&device->dev_alloc_list);
1072 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1074 list_del_init(&device->dev_list);
1075 fs_devices->num_devices--;
1076 btrfs_free_device(device);
1082 * After we have read the system tree and know devids belonging to this
1083 * filesystem, remove the device which does not belong there.
1085 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1087 struct btrfs_device *latest_dev = NULL;
1088 struct btrfs_fs_devices *seed_dev;
1090 mutex_lock(&uuid_mutex);
1091 __btrfs_free_extra_devids(fs_devices, step, &latest_dev);
1093 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1094 __btrfs_free_extra_devids(seed_dev, step, &latest_dev);
1096 fs_devices->latest_bdev = latest_dev->bdev;
1098 mutex_unlock(&uuid_mutex);
1101 static void btrfs_close_bdev(struct btrfs_device *device)
1106 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1107 sync_blockdev(device->bdev);
1108 invalidate_bdev(device->bdev);
1111 blkdev_put(device->bdev, device->mode);
1114 static void btrfs_close_one_device(struct btrfs_device *device)
1116 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1118 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1119 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1120 list_del_init(&device->dev_alloc_list);
1121 fs_devices->rw_devices--;
1124 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1125 fs_devices->missing_devices--;
1127 btrfs_close_bdev(device);
1129 fs_devices->open_devices--;
1130 device->bdev = NULL;
1132 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1134 device->fs_info = NULL;
1135 atomic_set(&device->dev_stats_ccnt, 0);
1136 extent_io_tree_release(&device->alloc_state);
1138 /* Verify the device is back in a pristine state */
1139 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1140 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1141 ASSERT(list_empty(&device->dev_alloc_list));
1142 ASSERT(list_empty(&device->post_commit_list));
1143 ASSERT(atomic_read(&device->reada_in_flight) == 0);
1146 static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
1148 struct btrfs_device *device, *tmp;
1150 lockdep_assert_held(&uuid_mutex);
1152 if (--fs_devices->opened > 0)
1155 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
1156 btrfs_close_one_device(device);
1158 WARN_ON(fs_devices->open_devices);
1159 WARN_ON(fs_devices->rw_devices);
1160 fs_devices->opened = 0;
1161 fs_devices->seeding = false;
1162 fs_devices->fs_info = NULL;
1165 void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1168 struct btrfs_fs_devices *tmp;
1170 mutex_lock(&uuid_mutex);
1171 close_fs_devices(fs_devices);
1172 if (!fs_devices->opened)
1173 list_splice_init(&fs_devices->seed_list, &list);
1175 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
1176 close_fs_devices(fs_devices);
1177 list_del(&fs_devices->seed_list);
1178 free_fs_devices(fs_devices);
1180 mutex_unlock(&uuid_mutex);
1183 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1184 fmode_t flags, void *holder)
1186 struct btrfs_device *device;
1187 struct btrfs_device *latest_dev = NULL;
1188 struct btrfs_device *tmp_device;
1190 flags |= FMODE_EXCL;
1192 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1196 ret = btrfs_open_one_device(fs_devices, device, flags, holder);
1198 (!latest_dev || device->generation > latest_dev->generation)) {
1199 latest_dev = device;
1200 } else if (ret == -ENODATA) {
1201 fs_devices->num_devices--;
1202 list_del(&device->dev_list);
1203 btrfs_free_device(device);
1206 if (fs_devices->open_devices == 0)
1209 fs_devices->opened = 1;
1210 fs_devices->latest_bdev = latest_dev->bdev;
1211 fs_devices->total_rw_bytes = 0;
1212 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1217 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1219 struct btrfs_device *dev1, *dev2;
1221 dev1 = list_entry(a, struct btrfs_device, dev_list);
1222 dev2 = list_entry(b, struct btrfs_device, dev_list);
1224 if (dev1->devid < dev2->devid)
1226 else if (dev1->devid > dev2->devid)
1231 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1232 fmode_t flags, void *holder)
1236 lockdep_assert_held(&uuid_mutex);
1238 * The device_list_mutex cannot be taken here in case opening the
1239 * underlying device takes further locks like bd_mutex.
1241 * We also don't need the lock here as this is called during mount and
1242 * exclusion is provided by uuid_mutex
1245 if (fs_devices->opened) {
1246 fs_devices->opened++;
1249 list_sort(NULL, &fs_devices->devices, devid_cmp);
1250 ret = open_fs_devices(fs_devices, flags, holder);
1256 void btrfs_release_disk_super(struct btrfs_super_block *super)
1258 struct page *page = virt_to_page(super);
1263 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1266 struct btrfs_super_block *disk_super;
1271 /* make sure our super fits in the device */
1272 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1273 return ERR_PTR(-EINVAL);
1275 /* make sure our super fits in the page */
1276 if (sizeof(*disk_super) > PAGE_SIZE)
1277 return ERR_PTR(-EINVAL);
1279 /* make sure our super doesn't straddle pages on disk */
1280 index = bytenr >> PAGE_SHIFT;
1281 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1282 return ERR_PTR(-EINVAL);
1284 /* pull in the page with our super */
1285 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1288 return ERR_CAST(page);
1290 p = page_address(page);
1292 /* align our pointer to the offset of the super block */
1293 disk_super = p + offset_in_page(bytenr);
1295 if (btrfs_super_bytenr(disk_super) != bytenr ||
1296 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1297 btrfs_release_disk_super(p);
1298 return ERR_PTR(-EINVAL);
1301 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1302 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1307 int btrfs_forget_devices(const char *path)
1311 mutex_lock(&uuid_mutex);
1312 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1313 mutex_unlock(&uuid_mutex);
1319 * Look for a btrfs signature on a device. This may be called out of the mount path
1320 * and we are not allowed to call set_blocksize during the scan. The superblock
1321 * is read via pagecache
1323 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1326 struct btrfs_super_block *disk_super;
1327 bool new_device_added = false;
1328 struct btrfs_device *device = NULL;
1329 struct block_device *bdev;
1332 lockdep_assert_held(&uuid_mutex);
1335 * we would like to check all the supers, but that would make
1336 * a btrfs mount succeed after a mkfs from a different FS.
1337 * So, we need to add a special mount option to scan for
1338 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1340 bytenr = btrfs_sb_offset(0);
1341 flags |= FMODE_EXCL;
1343 bdev = blkdev_get_by_path(path, flags, holder);
1345 return ERR_CAST(bdev);
1347 disk_super = btrfs_read_disk_super(bdev, bytenr);
1348 if (IS_ERR(disk_super)) {
1349 device = ERR_CAST(disk_super);
1350 goto error_bdev_put;
1353 device = device_list_add(path, disk_super, &new_device_added);
1354 if (!IS_ERR(device)) {
1355 if (new_device_added)
1356 btrfs_free_stale_devices(path, device);
1359 btrfs_release_disk_super(disk_super);
1362 blkdev_put(bdev, flags);
1368 * Try to find a chunk that intersects [start, start + len] range and when one
1369 * such is found, record the end of it in *start
1371 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1374 u64 physical_start, physical_end;
1376 lockdep_assert_held(&device->fs_info->chunk_mutex);
1378 if (!find_first_extent_bit(&device->alloc_state, *start,
1379 &physical_start, &physical_end,
1380 CHUNK_ALLOCATED, NULL)) {
1382 if (in_range(physical_start, *start, len) ||
1383 in_range(*start, physical_start,
1384 physical_end - physical_start)) {
1385 *start = physical_end + 1;
1392 static u64 dev_extent_search_start(struct btrfs_device *device, u64 start)
1394 switch (device->fs_devices->chunk_alloc_policy) {
1395 case BTRFS_CHUNK_ALLOC_REGULAR:
1397 * We don't want to overwrite the superblock on the drive nor
1398 * any area used by the boot loader (grub for example), so we
1399 * make sure to start at an offset of at least 1MB.
1401 return max_t(u64, start, SZ_1M);
1408 * dev_extent_hole_check - check if specified hole is suitable for allocation
1409 * @device: the device which we have the hole
1410 * @hole_start: starting position of the hole
1411 * @hole_size: the size of the hole
1412 * @num_bytes: the size of the free space that we need
1414 * This function may modify @hole_start and @hole_end to reflect the suitable
1415 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1417 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1418 u64 *hole_size, u64 num_bytes)
1420 bool changed = false;
1421 u64 hole_end = *hole_start + *hole_size;
1424 * Check before we set max_hole_start, otherwise we could end up
1425 * sending back this offset anyway.
1427 if (contains_pending_extent(device, hole_start, *hole_size)) {
1428 if (hole_end >= *hole_start)
1429 *hole_size = hole_end - *hole_start;
1435 switch (device->fs_devices->chunk_alloc_policy) {
1436 case BTRFS_CHUNK_ALLOC_REGULAR:
1437 /* No extra check */
1447 * find_free_dev_extent_start - find free space in the specified device
1448 * @device: the device which we search the free space in
1449 * @num_bytes: the size of the free space that we need
1450 * @search_start: the position from which to begin the search
1451 * @start: store the start of the free space.
1452 * @len: the size of the free space. that we find, or the size
1453 * of the max free space if we don't find suitable free space
1455 * this uses a pretty simple search, the expectation is that it is
1456 * called very infrequently and that a given device has a small number
1459 * @start is used to store the start of the free space if we find. But if we
1460 * don't find suitable free space, it will be used to store the start position
1461 * of the max free space.
1463 * @len is used to store the size of the free space that we find.
1464 * But if we don't find suitable free space, it is used to store the size of
1465 * the max free space.
1467 * NOTE: This function will search *commit* root of device tree, and does extra
1468 * check to ensure dev extents are not double allocated.
1469 * This makes the function safe to allocate dev extents but may not report
1470 * correct usable device space, as device extent freed in current transaction
1471 * is not reported as avaiable.
1473 static int find_free_dev_extent_start(struct btrfs_device *device,
1474 u64 num_bytes, u64 search_start, u64 *start,
1477 struct btrfs_fs_info *fs_info = device->fs_info;
1478 struct btrfs_root *root = fs_info->dev_root;
1479 struct btrfs_key key;
1480 struct btrfs_dev_extent *dev_extent;
1481 struct btrfs_path *path;
1486 u64 search_end = device->total_bytes;
1489 struct extent_buffer *l;
1491 search_start = dev_extent_search_start(device, search_start);
1493 path = btrfs_alloc_path();
1497 max_hole_start = search_start;
1501 if (search_start >= search_end ||
1502 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1507 path->reada = READA_FORWARD;
1508 path->search_commit_root = 1;
1509 path->skip_locking = 1;
1511 key.objectid = device->devid;
1512 key.offset = search_start;
1513 key.type = BTRFS_DEV_EXTENT_KEY;
1515 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1519 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1526 slot = path->slots[0];
1527 if (slot >= btrfs_header_nritems(l)) {
1528 ret = btrfs_next_leaf(root, path);
1536 btrfs_item_key_to_cpu(l, &key, slot);
1538 if (key.objectid < device->devid)
1541 if (key.objectid > device->devid)
1544 if (key.type != BTRFS_DEV_EXTENT_KEY)
1547 if (key.offset > search_start) {
1548 hole_size = key.offset - search_start;
1549 dev_extent_hole_check(device, &search_start, &hole_size,
1552 if (hole_size > max_hole_size) {
1553 max_hole_start = search_start;
1554 max_hole_size = hole_size;
1558 * If this free space is greater than which we need,
1559 * it must be the max free space that we have found
1560 * until now, so max_hole_start must point to the start
1561 * of this free space and the length of this free space
1562 * is stored in max_hole_size. Thus, we return
1563 * max_hole_start and max_hole_size and go back to the
1566 if (hole_size >= num_bytes) {
1572 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1573 extent_end = key.offset + btrfs_dev_extent_length(l,
1575 if (extent_end > search_start)
1576 search_start = extent_end;
1583 * At this point, search_start should be the end of
1584 * allocated dev extents, and when shrinking the device,
1585 * search_end may be smaller than search_start.
1587 if (search_end > search_start) {
1588 hole_size = search_end - search_start;
1589 if (dev_extent_hole_check(device, &search_start, &hole_size,
1591 btrfs_release_path(path);
1595 if (hole_size > max_hole_size) {
1596 max_hole_start = search_start;
1597 max_hole_size = hole_size;
1602 if (max_hole_size < num_bytes)
1608 btrfs_free_path(path);
1609 *start = max_hole_start;
1611 *len = max_hole_size;
1615 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1616 u64 *start, u64 *len)
1618 /* FIXME use last free of some kind */
1619 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1622 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1623 struct btrfs_device *device,
1624 u64 start, u64 *dev_extent_len)
1626 struct btrfs_fs_info *fs_info = device->fs_info;
1627 struct btrfs_root *root = fs_info->dev_root;
1629 struct btrfs_path *path;
1630 struct btrfs_key key;
1631 struct btrfs_key found_key;
1632 struct extent_buffer *leaf = NULL;
1633 struct btrfs_dev_extent *extent = NULL;
1635 path = btrfs_alloc_path();
1639 key.objectid = device->devid;
1641 key.type = BTRFS_DEV_EXTENT_KEY;
1643 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1645 ret = btrfs_previous_item(root, path, key.objectid,
1646 BTRFS_DEV_EXTENT_KEY);
1649 leaf = path->nodes[0];
1650 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1651 extent = btrfs_item_ptr(leaf, path->slots[0],
1652 struct btrfs_dev_extent);
1653 BUG_ON(found_key.offset > start || found_key.offset +
1654 btrfs_dev_extent_length(leaf, extent) < start);
1656 btrfs_release_path(path);
1658 } else if (ret == 0) {
1659 leaf = path->nodes[0];
1660 extent = btrfs_item_ptr(leaf, path->slots[0],
1661 struct btrfs_dev_extent);
1663 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1667 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1669 ret = btrfs_del_item(trans, root, path);
1671 btrfs_handle_fs_error(fs_info, ret,
1672 "Failed to remove dev extent item");
1674 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1677 btrfs_free_path(path);
1681 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1682 struct btrfs_device *device,
1683 u64 chunk_offset, u64 start, u64 num_bytes)
1686 struct btrfs_path *path;
1687 struct btrfs_fs_info *fs_info = device->fs_info;
1688 struct btrfs_root *root = fs_info->dev_root;
1689 struct btrfs_dev_extent *extent;
1690 struct extent_buffer *leaf;
1691 struct btrfs_key key;
1693 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1694 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1695 path = btrfs_alloc_path();
1699 key.objectid = device->devid;
1701 key.type = BTRFS_DEV_EXTENT_KEY;
1702 ret = btrfs_insert_empty_item(trans, root, path, &key,
1707 leaf = path->nodes[0];
1708 extent = btrfs_item_ptr(leaf, path->slots[0],
1709 struct btrfs_dev_extent);
1710 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1711 BTRFS_CHUNK_TREE_OBJECTID);
1712 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1713 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1714 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1716 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1717 btrfs_mark_buffer_dirty(leaf);
1719 btrfs_free_path(path);
1723 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1725 struct extent_map_tree *em_tree;
1726 struct extent_map *em;
1730 em_tree = &fs_info->mapping_tree;
1731 read_lock(&em_tree->lock);
1732 n = rb_last(&em_tree->map.rb_root);
1734 em = rb_entry(n, struct extent_map, rb_node);
1735 ret = em->start + em->len;
1737 read_unlock(&em_tree->lock);
1742 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1746 struct btrfs_key key;
1747 struct btrfs_key found_key;
1748 struct btrfs_path *path;
1750 path = btrfs_alloc_path();
1754 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1755 key.type = BTRFS_DEV_ITEM_KEY;
1756 key.offset = (u64)-1;
1758 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1764 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1769 ret = btrfs_previous_item(fs_info->chunk_root, path,
1770 BTRFS_DEV_ITEMS_OBJECTID,
1771 BTRFS_DEV_ITEM_KEY);
1775 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1777 *devid_ret = found_key.offset + 1;
1781 btrfs_free_path(path);
1786 * the device information is stored in the chunk root
1787 * the btrfs_device struct should be fully filled in
1789 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1790 struct btrfs_device *device)
1793 struct btrfs_path *path;
1794 struct btrfs_dev_item *dev_item;
1795 struct extent_buffer *leaf;
1796 struct btrfs_key key;
1799 path = btrfs_alloc_path();
1803 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1804 key.type = BTRFS_DEV_ITEM_KEY;
1805 key.offset = device->devid;
1807 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1808 &key, sizeof(*dev_item));
1812 leaf = path->nodes[0];
1813 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1815 btrfs_set_device_id(leaf, dev_item, device->devid);
1816 btrfs_set_device_generation(leaf, dev_item, 0);
1817 btrfs_set_device_type(leaf, dev_item, device->type);
1818 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1819 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1820 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1821 btrfs_set_device_total_bytes(leaf, dev_item,
1822 btrfs_device_get_disk_total_bytes(device));
1823 btrfs_set_device_bytes_used(leaf, dev_item,
1824 btrfs_device_get_bytes_used(device));
1825 btrfs_set_device_group(leaf, dev_item, 0);
1826 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1827 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1828 btrfs_set_device_start_offset(leaf, dev_item, 0);
1830 ptr = btrfs_device_uuid(dev_item);
1831 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1832 ptr = btrfs_device_fsid(dev_item);
1833 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1834 ptr, BTRFS_FSID_SIZE);
1835 btrfs_mark_buffer_dirty(leaf);
1839 btrfs_free_path(path);
1844 * Function to update ctime/mtime for a given device path.
1845 * Mainly used for ctime/mtime based probe like libblkid.
1847 static void update_dev_time(const char *path_name)
1851 filp = filp_open(path_name, O_RDWR, 0);
1854 file_update_time(filp);
1855 filp_close(filp, NULL);
1858 static int btrfs_rm_dev_item(struct btrfs_device *device)
1860 struct btrfs_root *root = device->fs_info->chunk_root;
1862 struct btrfs_path *path;
1863 struct btrfs_key key;
1864 struct btrfs_trans_handle *trans;
1866 path = btrfs_alloc_path();
1870 trans = btrfs_start_transaction(root, 0);
1871 if (IS_ERR(trans)) {
1872 btrfs_free_path(path);
1873 return PTR_ERR(trans);
1875 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1876 key.type = BTRFS_DEV_ITEM_KEY;
1877 key.offset = device->devid;
1879 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1883 btrfs_abort_transaction(trans, ret);
1884 btrfs_end_transaction(trans);
1888 ret = btrfs_del_item(trans, root, path);
1890 btrfs_abort_transaction(trans, ret);
1891 btrfs_end_transaction(trans);
1895 btrfs_free_path(path);
1897 ret = btrfs_commit_transaction(trans);
1902 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1903 * filesystem. It's up to the caller to adjust that number regarding eg. device
1906 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1914 seq = read_seqbegin(&fs_info->profiles_lock);
1916 all_avail = fs_info->avail_data_alloc_bits |
1917 fs_info->avail_system_alloc_bits |
1918 fs_info->avail_metadata_alloc_bits;
1919 } while (read_seqretry(&fs_info->profiles_lock, seq));
1921 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1922 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1925 if (num_devices < btrfs_raid_array[i].devs_min) {
1926 int ret = btrfs_raid_array[i].mindev_error;
1936 static struct btrfs_device * btrfs_find_next_active_device(
1937 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1939 struct btrfs_device *next_device;
1941 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1942 if (next_device != device &&
1943 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1944 && next_device->bdev)
1952 * Helper function to check if the given device is part of s_bdev / latest_bdev
1953 * and replace it with the provided or the next active device, in the context
1954 * where this function called, there should be always be another device (or
1955 * this_dev) which is active.
1957 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
1958 struct btrfs_device *next_device)
1960 struct btrfs_fs_info *fs_info = device->fs_info;
1963 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1965 ASSERT(next_device);
1967 if (fs_info->sb->s_bdev &&
1968 (fs_info->sb->s_bdev == device->bdev))
1969 fs_info->sb->s_bdev = next_device->bdev;
1971 if (fs_info->fs_devices->latest_bdev == device->bdev)
1972 fs_info->fs_devices->latest_bdev = next_device->bdev;
1976 * Return btrfs_fs_devices::num_devices excluding the device that's being
1977 * currently replaced.
1979 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1981 u64 num_devices = fs_info->fs_devices->num_devices;
1983 down_read(&fs_info->dev_replace.rwsem);
1984 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1985 ASSERT(num_devices > 1);
1988 up_read(&fs_info->dev_replace.rwsem);
1993 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
1994 struct block_device *bdev,
1995 const char *device_path)
1997 struct btrfs_super_block *disk_super;
2003 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2007 disk_super = btrfs_read_dev_one_super(bdev, copy_num);
2008 if (IS_ERR(disk_super))
2011 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
2013 page = virt_to_page(disk_super);
2014 set_page_dirty(page);
2016 /* write_on_page() unlocks the page */
2017 ret = write_one_page(page);
2020 "error clearing superblock number %d (%d)",
2022 btrfs_release_disk_super(disk_super);
2026 /* Notify udev that device has changed */
2027 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2029 /* Update ctime/mtime for device path for libblkid */
2030 update_dev_time(device_path);
2033 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2036 struct btrfs_device *device;
2037 struct btrfs_fs_devices *cur_devices;
2038 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2042 mutex_lock(&uuid_mutex);
2044 num_devices = btrfs_num_devices(fs_info);
2046 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2050 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2052 if (IS_ERR(device)) {
2053 if (PTR_ERR(device) == -ENOENT &&
2054 strcmp(device_path, "missing") == 0)
2055 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2057 ret = PTR_ERR(device);
2061 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2062 btrfs_warn_in_rcu(fs_info,
2063 "cannot remove device %s (devid %llu) due to active swapfile",
2064 rcu_str_deref(device->name), device->devid);
2069 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2070 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2074 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2075 fs_info->fs_devices->rw_devices == 1) {
2076 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2080 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2081 mutex_lock(&fs_info->chunk_mutex);
2082 list_del_init(&device->dev_alloc_list);
2083 device->fs_devices->rw_devices--;
2084 mutex_unlock(&fs_info->chunk_mutex);
2087 mutex_unlock(&uuid_mutex);
2088 ret = btrfs_shrink_device(device, 0);
2090 btrfs_reada_remove_dev(device);
2091 mutex_lock(&uuid_mutex);
2096 * TODO: the superblock still includes this device in its num_devices
2097 * counter although write_all_supers() is not locked out. This
2098 * could give a filesystem state which requires a degraded mount.
2100 ret = btrfs_rm_dev_item(device);
2104 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2105 btrfs_scrub_cancel_dev(device);
2108 * the device list mutex makes sure that we don't change
2109 * the device list while someone else is writing out all
2110 * the device supers. Whoever is writing all supers, should
2111 * lock the device list mutex before getting the number of
2112 * devices in the super block (super_copy). Conversely,
2113 * whoever updates the number of devices in the super block
2114 * (super_copy) should hold the device list mutex.
2118 * In normal cases the cur_devices == fs_devices. But in case
2119 * of deleting a seed device, the cur_devices should point to
2120 * its own fs_devices listed under the fs_devices->seed.
2122 cur_devices = device->fs_devices;
2123 mutex_lock(&fs_devices->device_list_mutex);
2124 list_del_rcu(&device->dev_list);
2126 cur_devices->num_devices--;
2127 cur_devices->total_devices--;
2128 /* Update total_devices of the parent fs_devices if it's seed */
2129 if (cur_devices != fs_devices)
2130 fs_devices->total_devices--;
2132 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2133 cur_devices->missing_devices--;
2135 btrfs_assign_next_active_device(device, NULL);
2138 cur_devices->open_devices--;
2139 /* remove sysfs entry */
2140 btrfs_sysfs_remove_device(device);
2143 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2144 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2145 mutex_unlock(&fs_devices->device_list_mutex);
2148 * at this point, the device is zero sized and detached from
2149 * the devices list. All that's left is to zero out the old
2150 * supers and free the device.
2152 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2153 btrfs_scratch_superblocks(fs_info, device->bdev,
2156 btrfs_close_bdev(device);
2158 btrfs_free_device(device);
2160 if (cur_devices->open_devices == 0) {
2161 list_del_init(&cur_devices->seed_list);
2162 close_fs_devices(cur_devices);
2163 free_fs_devices(cur_devices);
2167 mutex_unlock(&uuid_mutex);
2171 btrfs_reada_undo_remove_dev(device);
2172 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2173 mutex_lock(&fs_info->chunk_mutex);
2174 list_add(&device->dev_alloc_list,
2175 &fs_devices->alloc_list);
2176 device->fs_devices->rw_devices++;
2177 mutex_unlock(&fs_info->chunk_mutex);
2182 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2184 struct btrfs_fs_devices *fs_devices;
2186 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2189 * in case of fs with no seed, srcdev->fs_devices will point
2190 * to fs_devices of fs_info. However when the dev being replaced is
2191 * a seed dev it will point to the seed's local fs_devices. In short
2192 * srcdev will have its correct fs_devices in both the cases.
2194 fs_devices = srcdev->fs_devices;
2196 list_del_rcu(&srcdev->dev_list);
2197 list_del(&srcdev->dev_alloc_list);
2198 fs_devices->num_devices--;
2199 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2200 fs_devices->missing_devices--;
2202 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2203 fs_devices->rw_devices--;
2206 fs_devices->open_devices--;
2209 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2211 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2213 mutex_lock(&uuid_mutex);
2215 btrfs_close_bdev(srcdev);
2217 btrfs_free_device(srcdev);
2219 /* if this is no devs we rather delete the fs_devices */
2220 if (!fs_devices->num_devices) {
2222 * On a mounted FS, num_devices can't be zero unless it's a
2223 * seed. In case of a seed device being replaced, the replace
2224 * target added to the sprout FS, so there will be no more
2225 * device left under the seed FS.
2227 ASSERT(fs_devices->seeding);
2229 list_del_init(&fs_devices->seed_list);
2230 close_fs_devices(fs_devices);
2231 free_fs_devices(fs_devices);
2233 mutex_unlock(&uuid_mutex);
2236 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2238 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2240 mutex_lock(&fs_devices->device_list_mutex);
2242 btrfs_sysfs_remove_device(tgtdev);
2245 fs_devices->open_devices--;
2247 fs_devices->num_devices--;
2249 btrfs_assign_next_active_device(tgtdev, NULL);
2251 list_del_rcu(&tgtdev->dev_list);
2253 mutex_unlock(&fs_devices->device_list_mutex);
2256 * The update_dev_time() with in btrfs_scratch_superblocks()
2257 * may lead to a call to btrfs_show_devname() which will try
2258 * to hold device_list_mutex. And here this device
2259 * is already out of device list, so we don't have to hold
2260 * the device_list_mutex lock.
2262 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2265 btrfs_close_bdev(tgtdev);
2267 btrfs_free_device(tgtdev);
2270 static struct btrfs_device *btrfs_find_device_by_path(
2271 struct btrfs_fs_info *fs_info, const char *device_path)
2274 struct btrfs_super_block *disk_super;
2277 struct block_device *bdev;
2278 struct btrfs_device *device;
2280 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2281 fs_info->bdev_holder, 0, &bdev, &disk_super);
2283 return ERR_PTR(ret);
2285 devid = btrfs_stack_device_id(&disk_super->dev_item);
2286 dev_uuid = disk_super->dev_item.uuid;
2287 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2288 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2289 disk_super->metadata_uuid, true);
2291 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2292 disk_super->fsid, true);
2294 btrfs_release_disk_super(disk_super);
2296 device = ERR_PTR(-ENOENT);
2297 blkdev_put(bdev, FMODE_READ);
2302 * Lookup a device given by device id, or the path if the id is 0.
2304 struct btrfs_device *btrfs_find_device_by_devspec(
2305 struct btrfs_fs_info *fs_info, u64 devid,
2306 const char *device_path)
2308 struct btrfs_device *device;
2311 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2314 return ERR_PTR(-ENOENT);
2318 if (!device_path || !device_path[0])
2319 return ERR_PTR(-EINVAL);
2321 if (strcmp(device_path, "missing") == 0) {
2322 /* Find first missing device */
2323 list_for_each_entry(device, &fs_info->fs_devices->devices,
2325 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2326 &device->dev_state) && !device->bdev)
2329 return ERR_PTR(-ENOENT);
2332 return btrfs_find_device_by_path(fs_info, device_path);
2336 * does all the dirty work required for changing file system's UUID.
2338 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2340 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2341 struct btrfs_fs_devices *old_devices;
2342 struct btrfs_fs_devices *seed_devices;
2343 struct btrfs_super_block *disk_super = fs_info->super_copy;
2344 struct btrfs_device *device;
2347 lockdep_assert_held(&uuid_mutex);
2348 if (!fs_devices->seeding)
2352 * Private copy of the seed devices, anchored at
2353 * fs_info->fs_devices->seed_list
2355 seed_devices = alloc_fs_devices(NULL, NULL);
2356 if (IS_ERR(seed_devices))
2357 return PTR_ERR(seed_devices);
2360 * It's necessary to retain a copy of the original seed fs_devices in
2361 * fs_uuids so that filesystems which have been seeded can successfully
2362 * reference the seed device from open_seed_devices. This also supports
2365 old_devices = clone_fs_devices(fs_devices);
2366 if (IS_ERR(old_devices)) {
2367 kfree(seed_devices);
2368 return PTR_ERR(old_devices);
2371 list_add(&old_devices->fs_list, &fs_uuids);
2373 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2374 seed_devices->opened = 1;
2375 INIT_LIST_HEAD(&seed_devices->devices);
2376 INIT_LIST_HEAD(&seed_devices->alloc_list);
2377 mutex_init(&seed_devices->device_list_mutex);
2379 mutex_lock(&fs_devices->device_list_mutex);
2380 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2382 list_for_each_entry(device, &seed_devices->devices, dev_list)
2383 device->fs_devices = seed_devices;
2385 fs_devices->seeding = false;
2386 fs_devices->num_devices = 0;
2387 fs_devices->open_devices = 0;
2388 fs_devices->missing_devices = 0;
2389 fs_devices->rotating = false;
2390 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2392 generate_random_uuid(fs_devices->fsid);
2393 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2394 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2395 mutex_unlock(&fs_devices->device_list_mutex);
2397 super_flags = btrfs_super_flags(disk_super) &
2398 ~BTRFS_SUPER_FLAG_SEEDING;
2399 btrfs_set_super_flags(disk_super, super_flags);
2405 * Store the expected generation for seed devices in device items.
2407 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2409 struct btrfs_fs_info *fs_info = trans->fs_info;
2410 struct btrfs_root *root = fs_info->chunk_root;
2411 struct btrfs_path *path;
2412 struct extent_buffer *leaf;
2413 struct btrfs_dev_item *dev_item;
2414 struct btrfs_device *device;
2415 struct btrfs_key key;
2416 u8 fs_uuid[BTRFS_FSID_SIZE];
2417 u8 dev_uuid[BTRFS_UUID_SIZE];
2421 path = btrfs_alloc_path();
2425 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2427 key.type = BTRFS_DEV_ITEM_KEY;
2430 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2434 leaf = path->nodes[0];
2436 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2437 ret = btrfs_next_leaf(root, path);
2442 leaf = path->nodes[0];
2443 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2444 btrfs_release_path(path);
2448 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2449 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2450 key.type != BTRFS_DEV_ITEM_KEY)
2453 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2454 struct btrfs_dev_item);
2455 devid = btrfs_device_id(leaf, dev_item);
2456 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2458 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2460 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2462 BUG_ON(!device); /* Logic error */
2464 if (device->fs_devices->seeding) {
2465 btrfs_set_device_generation(leaf, dev_item,
2466 device->generation);
2467 btrfs_mark_buffer_dirty(leaf);
2475 btrfs_free_path(path);
2479 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2481 struct btrfs_root *root = fs_info->dev_root;
2482 struct request_queue *q;
2483 struct btrfs_trans_handle *trans;
2484 struct btrfs_device *device;
2485 struct block_device *bdev;
2486 struct super_block *sb = fs_info->sb;
2487 struct rcu_string *name;
2488 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2489 u64 orig_super_total_bytes;
2490 u64 orig_super_num_devices;
2491 int seeding_dev = 0;
2493 bool locked = false;
2495 if (sb_rdonly(sb) && !fs_devices->seeding)
2498 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2499 fs_info->bdev_holder);
2501 return PTR_ERR(bdev);
2503 if (fs_devices->seeding) {
2505 down_write(&sb->s_umount);
2506 mutex_lock(&uuid_mutex);
2510 sync_blockdev(bdev);
2513 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2514 if (device->bdev == bdev) {
2522 device = btrfs_alloc_device(fs_info, NULL, NULL);
2523 if (IS_ERR(device)) {
2524 /* we can safely leave the fs_devices entry around */
2525 ret = PTR_ERR(device);
2529 name = rcu_string_strdup(device_path, GFP_KERNEL);
2532 goto error_free_device;
2534 rcu_assign_pointer(device->name, name);
2536 trans = btrfs_start_transaction(root, 0);
2537 if (IS_ERR(trans)) {
2538 ret = PTR_ERR(trans);
2539 goto error_free_device;
2542 q = bdev_get_queue(bdev);
2543 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2544 device->generation = trans->transid;
2545 device->io_width = fs_info->sectorsize;
2546 device->io_align = fs_info->sectorsize;
2547 device->sector_size = fs_info->sectorsize;
2548 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2549 fs_info->sectorsize);
2550 device->disk_total_bytes = device->total_bytes;
2551 device->commit_total_bytes = device->total_bytes;
2552 device->fs_info = fs_info;
2553 device->bdev = bdev;
2554 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2555 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2556 device->mode = FMODE_EXCL;
2557 device->dev_stats_valid = 1;
2558 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2561 sb->s_flags &= ~SB_RDONLY;
2562 ret = btrfs_prepare_sprout(fs_info);
2564 btrfs_abort_transaction(trans, ret);
2569 device->fs_devices = fs_devices;
2571 mutex_lock(&fs_devices->device_list_mutex);
2572 mutex_lock(&fs_info->chunk_mutex);
2573 list_add_rcu(&device->dev_list, &fs_devices->devices);
2574 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2575 fs_devices->num_devices++;
2576 fs_devices->open_devices++;
2577 fs_devices->rw_devices++;
2578 fs_devices->total_devices++;
2579 fs_devices->total_rw_bytes += device->total_bytes;
2581 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2583 if (!blk_queue_nonrot(q))
2584 fs_devices->rotating = true;
2586 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2587 btrfs_set_super_total_bytes(fs_info->super_copy,
2588 round_down(orig_super_total_bytes + device->total_bytes,
2589 fs_info->sectorsize));
2591 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2592 btrfs_set_super_num_devices(fs_info->super_copy,
2593 orig_super_num_devices + 1);
2596 * we've got more storage, clear any full flags on the space
2599 btrfs_clear_space_info_full(fs_info);
2601 mutex_unlock(&fs_info->chunk_mutex);
2603 /* Add sysfs device entry */
2604 btrfs_sysfs_add_device(device);
2606 mutex_unlock(&fs_devices->device_list_mutex);
2609 mutex_lock(&fs_info->chunk_mutex);
2610 ret = init_first_rw_device(trans);
2611 mutex_unlock(&fs_info->chunk_mutex);
2613 btrfs_abort_transaction(trans, ret);
2618 ret = btrfs_add_dev_item(trans, device);
2620 btrfs_abort_transaction(trans, ret);
2625 ret = btrfs_finish_sprout(trans);
2627 btrfs_abort_transaction(trans, ret);
2632 * fs_devices now represents the newly sprouted filesystem and
2633 * its fsid has been changed by btrfs_prepare_sprout
2635 btrfs_sysfs_update_sprout_fsid(fs_devices);
2638 ret = btrfs_commit_transaction(trans);
2641 mutex_unlock(&uuid_mutex);
2642 up_write(&sb->s_umount);
2645 if (ret) /* transaction commit */
2648 ret = btrfs_relocate_sys_chunks(fs_info);
2650 btrfs_handle_fs_error(fs_info, ret,
2651 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2652 trans = btrfs_attach_transaction(root);
2653 if (IS_ERR(trans)) {
2654 if (PTR_ERR(trans) == -ENOENT)
2656 ret = PTR_ERR(trans);
2660 ret = btrfs_commit_transaction(trans);
2664 * Now that we have written a new super block to this device, check all
2665 * other fs_devices list if device_path alienates any other scanned
2667 * We can ignore the return value as it typically returns -EINVAL and
2668 * only succeeds if the device was an alien.
2670 btrfs_forget_devices(device_path);
2672 /* Update ctime/mtime for blkid or udev */
2673 update_dev_time(device_path);
2678 btrfs_sysfs_remove_device(device);
2679 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2680 mutex_lock(&fs_info->chunk_mutex);
2681 list_del_rcu(&device->dev_list);
2682 list_del(&device->dev_alloc_list);
2683 fs_info->fs_devices->num_devices--;
2684 fs_info->fs_devices->open_devices--;
2685 fs_info->fs_devices->rw_devices--;
2686 fs_info->fs_devices->total_devices--;
2687 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2688 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2689 btrfs_set_super_total_bytes(fs_info->super_copy,
2690 orig_super_total_bytes);
2691 btrfs_set_super_num_devices(fs_info->super_copy,
2692 orig_super_num_devices);
2693 mutex_unlock(&fs_info->chunk_mutex);
2694 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2697 sb->s_flags |= SB_RDONLY;
2699 btrfs_end_transaction(trans);
2701 btrfs_free_device(device);
2703 blkdev_put(bdev, FMODE_EXCL);
2705 mutex_unlock(&uuid_mutex);
2706 up_write(&sb->s_umount);
2711 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2712 struct btrfs_device *device)
2715 struct btrfs_path *path;
2716 struct btrfs_root *root = device->fs_info->chunk_root;
2717 struct btrfs_dev_item *dev_item;
2718 struct extent_buffer *leaf;
2719 struct btrfs_key key;
2721 path = btrfs_alloc_path();
2725 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2726 key.type = BTRFS_DEV_ITEM_KEY;
2727 key.offset = device->devid;
2729 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2738 leaf = path->nodes[0];
2739 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2741 btrfs_set_device_id(leaf, dev_item, device->devid);
2742 btrfs_set_device_type(leaf, dev_item, device->type);
2743 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2744 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2745 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2746 btrfs_set_device_total_bytes(leaf, dev_item,
2747 btrfs_device_get_disk_total_bytes(device));
2748 btrfs_set_device_bytes_used(leaf, dev_item,
2749 btrfs_device_get_bytes_used(device));
2750 btrfs_mark_buffer_dirty(leaf);
2753 btrfs_free_path(path);
2757 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2758 struct btrfs_device *device, u64 new_size)
2760 struct btrfs_fs_info *fs_info = device->fs_info;
2761 struct btrfs_super_block *super_copy = fs_info->super_copy;
2765 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2768 new_size = round_down(new_size, fs_info->sectorsize);
2770 mutex_lock(&fs_info->chunk_mutex);
2771 old_total = btrfs_super_total_bytes(super_copy);
2772 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2774 if (new_size <= device->total_bytes ||
2775 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2776 mutex_unlock(&fs_info->chunk_mutex);
2780 btrfs_set_super_total_bytes(super_copy,
2781 round_down(old_total + diff, fs_info->sectorsize));
2782 device->fs_devices->total_rw_bytes += diff;
2784 btrfs_device_set_total_bytes(device, new_size);
2785 btrfs_device_set_disk_total_bytes(device, new_size);
2786 btrfs_clear_space_info_full(device->fs_info);
2787 if (list_empty(&device->post_commit_list))
2788 list_add_tail(&device->post_commit_list,
2789 &trans->transaction->dev_update_list);
2790 mutex_unlock(&fs_info->chunk_mutex);
2792 return btrfs_update_device(trans, device);
2795 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2797 struct btrfs_fs_info *fs_info = trans->fs_info;
2798 struct btrfs_root *root = fs_info->chunk_root;
2800 struct btrfs_path *path;
2801 struct btrfs_key key;
2803 path = btrfs_alloc_path();
2807 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2808 key.offset = chunk_offset;
2809 key.type = BTRFS_CHUNK_ITEM_KEY;
2811 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2814 else if (ret > 0) { /* Logic error or corruption */
2815 btrfs_handle_fs_error(fs_info, -ENOENT,
2816 "Failed lookup while freeing chunk.");
2821 ret = btrfs_del_item(trans, root, path);
2823 btrfs_handle_fs_error(fs_info, ret,
2824 "Failed to delete chunk item.");
2826 btrfs_free_path(path);
2830 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2832 struct btrfs_super_block *super_copy = fs_info->super_copy;
2833 struct btrfs_disk_key *disk_key;
2834 struct btrfs_chunk *chunk;
2841 struct btrfs_key key;
2843 mutex_lock(&fs_info->chunk_mutex);
2844 array_size = btrfs_super_sys_array_size(super_copy);
2846 ptr = super_copy->sys_chunk_array;
2849 while (cur < array_size) {
2850 disk_key = (struct btrfs_disk_key *)ptr;
2851 btrfs_disk_key_to_cpu(&key, disk_key);
2853 len = sizeof(*disk_key);
2855 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2856 chunk = (struct btrfs_chunk *)(ptr + len);
2857 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2858 len += btrfs_chunk_item_size(num_stripes);
2863 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2864 key.offset == chunk_offset) {
2865 memmove(ptr, ptr + len, array_size - (cur + len));
2867 btrfs_set_super_sys_array_size(super_copy, array_size);
2873 mutex_unlock(&fs_info->chunk_mutex);
2878 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2879 * @logical: Logical block offset in bytes.
2880 * @length: Length of extent in bytes.
2882 * Return: Chunk mapping or ERR_PTR.
2884 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2885 u64 logical, u64 length)
2887 struct extent_map_tree *em_tree;
2888 struct extent_map *em;
2890 em_tree = &fs_info->mapping_tree;
2891 read_lock(&em_tree->lock);
2892 em = lookup_extent_mapping(em_tree, logical, length);
2893 read_unlock(&em_tree->lock);
2896 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2898 return ERR_PTR(-EINVAL);
2901 if (em->start > logical || em->start + em->len < logical) {
2903 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2904 logical, length, em->start, em->start + em->len);
2905 free_extent_map(em);
2906 return ERR_PTR(-EINVAL);
2909 /* callers are responsible for dropping em's ref. */
2913 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2915 struct btrfs_fs_info *fs_info = trans->fs_info;
2916 struct extent_map *em;
2917 struct map_lookup *map;
2918 u64 dev_extent_len = 0;
2920 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2922 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2925 * This is a logic error, but we don't want to just rely on the
2926 * user having built with ASSERT enabled, so if ASSERT doesn't
2927 * do anything we still error out.
2932 map = em->map_lookup;
2933 mutex_lock(&fs_info->chunk_mutex);
2934 check_system_chunk(trans, map->type);
2935 mutex_unlock(&fs_info->chunk_mutex);
2938 * Take the device list mutex to prevent races with the final phase of
2939 * a device replace operation that replaces the device object associated
2940 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2942 mutex_lock(&fs_devices->device_list_mutex);
2943 for (i = 0; i < map->num_stripes; i++) {
2944 struct btrfs_device *device = map->stripes[i].dev;
2945 ret = btrfs_free_dev_extent(trans, device,
2946 map->stripes[i].physical,
2949 mutex_unlock(&fs_devices->device_list_mutex);
2950 btrfs_abort_transaction(trans, ret);
2954 if (device->bytes_used > 0) {
2955 mutex_lock(&fs_info->chunk_mutex);
2956 btrfs_device_set_bytes_used(device,
2957 device->bytes_used - dev_extent_len);
2958 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2959 btrfs_clear_space_info_full(fs_info);
2960 mutex_unlock(&fs_info->chunk_mutex);
2963 ret = btrfs_update_device(trans, device);
2965 mutex_unlock(&fs_devices->device_list_mutex);
2966 btrfs_abort_transaction(trans, ret);
2970 mutex_unlock(&fs_devices->device_list_mutex);
2972 ret = btrfs_free_chunk(trans, chunk_offset);
2974 btrfs_abort_transaction(trans, ret);
2978 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2980 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2981 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2983 btrfs_abort_transaction(trans, ret);
2988 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2990 btrfs_abort_transaction(trans, ret);
2996 free_extent_map(em);
3000 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3002 struct btrfs_root *root = fs_info->chunk_root;
3003 struct btrfs_trans_handle *trans;
3004 struct btrfs_block_group *block_group;
3008 * Prevent races with automatic removal of unused block groups.
3009 * After we relocate and before we remove the chunk with offset
3010 * chunk_offset, automatic removal of the block group can kick in,
3011 * resulting in a failure when calling btrfs_remove_chunk() below.
3013 * Make sure to acquire this mutex before doing a tree search (dev
3014 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3015 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3016 * we release the path used to search the chunk/dev tree and before
3017 * the current task acquires this mutex and calls us.
3019 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3021 /* step one, relocate all the extents inside this chunk */
3022 btrfs_scrub_pause(fs_info);
3023 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3024 btrfs_scrub_continue(fs_info);
3028 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3031 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3032 btrfs_put_block_group(block_group);
3034 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3036 if (IS_ERR(trans)) {
3037 ret = PTR_ERR(trans);
3038 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3043 * step two, delete the device extents and the
3044 * chunk tree entries
3046 ret = btrfs_remove_chunk(trans, chunk_offset);
3047 btrfs_end_transaction(trans);
3051 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3053 struct btrfs_root *chunk_root = fs_info->chunk_root;
3054 struct btrfs_path *path;
3055 struct extent_buffer *leaf;
3056 struct btrfs_chunk *chunk;
3057 struct btrfs_key key;
3058 struct btrfs_key found_key;
3060 bool retried = false;
3064 path = btrfs_alloc_path();
3069 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3070 key.offset = (u64)-1;
3071 key.type = BTRFS_CHUNK_ITEM_KEY;
3074 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3075 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3077 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3080 BUG_ON(ret == 0); /* Corruption */
3082 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3085 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3091 leaf = path->nodes[0];
3092 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3094 chunk = btrfs_item_ptr(leaf, path->slots[0],
3095 struct btrfs_chunk);
3096 chunk_type = btrfs_chunk_type(leaf, chunk);
3097 btrfs_release_path(path);
3099 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3100 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3106 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3108 if (found_key.offset == 0)
3110 key.offset = found_key.offset - 1;
3113 if (failed && !retried) {
3117 } else if (WARN_ON(failed && retried)) {
3121 btrfs_free_path(path);
3126 * return 1 : allocate a data chunk successfully,
3127 * return <0: errors during allocating a data chunk,
3128 * return 0 : no need to allocate a data chunk.
3130 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3133 struct btrfs_block_group *cache;
3137 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3139 chunk_type = cache->flags;
3140 btrfs_put_block_group(cache);
3142 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3145 spin_lock(&fs_info->data_sinfo->lock);
3146 bytes_used = fs_info->data_sinfo->bytes_used;
3147 spin_unlock(&fs_info->data_sinfo->lock);
3150 struct btrfs_trans_handle *trans;
3153 trans = btrfs_join_transaction(fs_info->tree_root);
3155 return PTR_ERR(trans);
3157 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3158 btrfs_end_transaction(trans);
3167 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3168 struct btrfs_balance_control *bctl)
3170 struct btrfs_root *root = fs_info->tree_root;
3171 struct btrfs_trans_handle *trans;
3172 struct btrfs_balance_item *item;
3173 struct btrfs_disk_balance_args disk_bargs;
3174 struct btrfs_path *path;
3175 struct extent_buffer *leaf;
3176 struct btrfs_key key;
3179 path = btrfs_alloc_path();
3183 trans = btrfs_start_transaction(root, 0);
3184 if (IS_ERR(trans)) {
3185 btrfs_free_path(path);
3186 return PTR_ERR(trans);
3189 key.objectid = BTRFS_BALANCE_OBJECTID;
3190 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3193 ret = btrfs_insert_empty_item(trans, root, path, &key,
3198 leaf = path->nodes[0];
3199 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3201 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3203 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3204 btrfs_set_balance_data(leaf, item, &disk_bargs);
3205 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3206 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3207 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3208 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3210 btrfs_set_balance_flags(leaf, item, bctl->flags);
3212 btrfs_mark_buffer_dirty(leaf);
3214 btrfs_free_path(path);
3215 err = btrfs_commit_transaction(trans);
3221 static int del_balance_item(struct btrfs_fs_info *fs_info)
3223 struct btrfs_root *root = fs_info->tree_root;
3224 struct btrfs_trans_handle *trans;
3225 struct btrfs_path *path;
3226 struct btrfs_key key;
3229 path = btrfs_alloc_path();
3233 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3234 if (IS_ERR(trans)) {
3235 btrfs_free_path(path);
3236 return PTR_ERR(trans);
3239 key.objectid = BTRFS_BALANCE_OBJECTID;
3240 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3243 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3251 ret = btrfs_del_item(trans, root, path);
3253 btrfs_free_path(path);
3254 err = btrfs_commit_transaction(trans);
3261 * This is a heuristic used to reduce the number of chunks balanced on
3262 * resume after balance was interrupted.
3264 static void update_balance_args(struct btrfs_balance_control *bctl)
3267 * Turn on soft mode for chunk types that were being converted.
3269 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3270 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3271 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3272 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3273 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3274 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3277 * Turn on usage filter if is not already used. The idea is
3278 * that chunks that we have already balanced should be
3279 * reasonably full. Don't do it for chunks that are being
3280 * converted - that will keep us from relocating unconverted
3281 * (albeit full) chunks.
3283 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3284 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3285 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3286 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3287 bctl->data.usage = 90;
3289 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3290 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3291 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3292 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3293 bctl->sys.usage = 90;
3295 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3296 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3297 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3298 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3299 bctl->meta.usage = 90;
3304 * Clear the balance status in fs_info and delete the balance item from disk.
3306 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3308 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3311 BUG_ON(!fs_info->balance_ctl);
3313 spin_lock(&fs_info->balance_lock);
3314 fs_info->balance_ctl = NULL;
3315 spin_unlock(&fs_info->balance_lock);
3318 ret = del_balance_item(fs_info);
3320 btrfs_handle_fs_error(fs_info, ret, NULL);
3324 * Balance filters. Return 1 if chunk should be filtered out
3325 * (should not be balanced).
3327 static int chunk_profiles_filter(u64 chunk_type,
3328 struct btrfs_balance_args *bargs)
3330 chunk_type = chunk_to_extended(chunk_type) &
3331 BTRFS_EXTENDED_PROFILE_MASK;
3333 if (bargs->profiles & chunk_type)
3339 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3340 struct btrfs_balance_args *bargs)
3342 struct btrfs_block_group *cache;
3344 u64 user_thresh_min;
3345 u64 user_thresh_max;
3348 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3349 chunk_used = cache->used;
3351 if (bargs->usage_min == 0)
3352 user_thresh_min = 0;
3354 user_thresh_min = div_factor_fine(cache->length,
3357 if (bargs->usage_max == 0)
3358 user_thresh_max = 1;
3359 else if (bargs->usage_max > 100)
3360 user_thresh_max = cache->length;
3362 user_thresh_max = div_factor_fine(cache->length,
3365 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3368 btrfs_put_block_group(cache);
3372 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3373 u64 chunk_offset, struct btrfs_balance_args *bargs)
3375 struct btrfs_block_group *cache;
3376 u64 chunk_used, user_thresh;
3379 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3380 chunk_used = cache->used;
3382 if (bargs->usage_min == 0)
3384 else if (bargs->usage > 100)
3385 user_thresh = cache->length;
3387 user_thresh = div_factor_fine(cache->length, bargs->usage);
3389 if (chunk_used < user_thresh)
3392 btrfs_put_block_group(cache);
3396 static int chunk_devid_filter(struct extent_buffer *leaf,
3397 struct btrfs_chunk *chunk,
3398 struct btrfs_balance_args *bargs)
3400 struct btrfs_stripe *stripe;
3401 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3404 for (i = 0; i < num_stripes; i++) {
3405 stripe = btrfs_stripe_nr(chunk, i);
3406 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3413 static u64 calc_data_stripes(u64 type, int num_stripes)
3415 const int index = btrfs_bg_flags_to_raid_index(type);
3416 const int ncopies = btrfs_raid_array[index].ncopies;
3417 const int nparity = btrfs_raid_array[index].nparity;
3420 return num_stripes - nparity;
3422 return num_stripes / ncopies;
3425 /* [pstart, pend) */
3426 static int chunk_drange_filter(struct extent_buffer *leaf,
3427 struct btrfs_chunk *chunk,
3428 struct btrfs_balance_args *bargs)
3430 struct btrfs_stripe *stripe;
3431 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3438 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3441 type = btrfs_chunk_type(leaf, chunk);
3442 factor = calc_data_stripes(type, num_stripes);
3444 for (i = 0; i < num_stripes; i++) {
3445 stripe = btrfs_stripe_nr(chunk, i);
3446 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3449 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3450 stripe_length = btrfs_chunk_length(leaf, chunk);
3451 stripe_length = div_u64(stripe_length, factor);
3453 if (stripe_offset < bargs->pend &&
3454 stripe_offset + stripe_length > bargs->pstart)
3461 /* [vstart, vend) */
3462 static int chunk_vrange_filter(struct extent_buffer *leaf,
3463 struct btrfs_chunk *chunk,
3465 struct btrfs_balance_args *bargs)
3467 if (chunk_offset < bargs->vend &&
3468 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3469 /* at least part of the chunk is inside this vrange */
3475 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3476 struct btrfs_chunk *chunk,
3477 struct btrfs_balance_args *bargs)
3479 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3481 if (bargs->stripes_min <= num_stripes
3482 && num_stripes <= bargs->stripes_max)
3488 static int chunk_soft_convert_filter(u64 chunk_type,
3489 struct btrfs_balance_args *bargs)
3491 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3494 chunk_type = chunk_to_extended(chunk_type) &
3495 BTRFS_EXTENDED_PROFILE_MASK;
3497 if (bargs->target == chunk_type)
3503 static int should_balance_chunk(struct extent_buffer *leaf,
3504 struct btrfs_chunk *chunk, u64 chunk_offset)
3506 struct btrfs_fs_info *fs_info = leaf->fs_info;
3507 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3508 struct btrfs_balance_args *bargs = NULL;
3509 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3512 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3513 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3517 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3518 bargs = &bctl->data;
3519 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3521 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3522 bargs = &bctl->meta;
3524 /* profiles filter */
3525 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3526 chunk_profiles_filter(chunk_type, bargs)) {
3531 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3532 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3534 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3535 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3540 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3541 chunk_devid_filter(leaf, chunk, bargs)) {
3545 /* drange filter, makes sense only with devid filter */
3546 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3547 chunk_drange_filter(leaf, chunk, bargs)) {
3552 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3553 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3557 /* stripes filter */
3558 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3559 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3563 /* soft profile changing mode */
3564 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3565 chunk_soft_convert_filter(chunk_type, bargs)) {
3570 * limited by count, must be the last filter
3572 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3573 if (bargs->limit == 0)
3577 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3579 * Same logic as the 'limit' filter; the minimum cannot be
3580 * determined here because we do not have the global information
3581 * about the count of all chunks that satisfy the filters.
3583 if (bargs->limit_max == 0)
3592 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3594 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3595 struct btrfs_root *chunk_root = fs_info->chunk_root;
3597 struct btrfs_chunk *chunk;
3598 struct btrfs_path *path = NULL;
3599 struct btrfs_key key;
3600 struct btrfs_key found_key;
3601 struct extent_buffer *leaf;
3604 int enospc_errors = 0;
3605 bool counting = true;
3606 /* The single value limit and min/max limits use the same bytes in the */
3607 u64 limit_data = bctl->data.limit;
3608 u64 limit_meta = bctl->meta.limit;
3609 u64 limit_sys = bctl->sys.limit;
3613 int chunk_reserved = 0;
3615 path = btrfs_alloc_path();
3621 /* zero out stat counters */
3622 spin_lock(&fs_info->balance_lock);
3623 memset(&bctl->stat, 0, sizeof(bctl->stat));
3624 spin_unlock(&fs_info->balance_lock);
3628 * The single value limit and min/max limits use the same bytes
3631 bctl->data.limit = limit_data;
3632 bctl->meta.limit = limit_meta;
3633 bctl->sys.limit = limit_sys;
3635 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3636 key.offset = (u64)-1;
3637 key.type = BTRFS_CHUNK_ITEM_KEY;
3640 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3641 atomic_read(&fs_info->balance_cancel_req)) {