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>
8 #include <linux/slab.h>
9 #include <linux/ratelimit.h>
10 #include <linux/kthread.h>
11 #include <linux/semaphore.h>
12 #include <linux/uuid.h>
13 #include <linux/list_sort.h>
14 #include <linux/namei.h>
17 #include "extent_map.h"
19 #include "transaction.h"
20 #include "print-tree.h"
23 #include "rcu-string.h"
24 #include "dev-replace.h"
26 #include "tree-checker.h"
27 #include "space-info.h"
28 #include "block-group.h"
32 #include "accessors.h"
33 #include "uuid-tree.h"
35 #include "relocation.h"
38 #include "raid-stripe-tree.h"
40 #define BTRFS_BLOCK_GROUP_STRIPE_MASK (BTRFS_BLOCK_GROUP_RAID0 | \
41 BTRFS_BLOCK_GROUP_RAID10 | \
42 BTRFS_BLOCK_GROUP_RAID56_MASK)
44 struct btrfs_io_geometry {
50 u64 raid56_full_stripe_start;
55 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
56 [BTRFS_RAID_RAID10] = {
59 .devs_max = 0, /* 0 == as many as possible */
61 .tolerated_failures = 1,
65 .raid_name = "raid10",
66 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
67 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
69 [BTRFS_RAID_RAID1] = {
74 .tolerated_failures = 1,
79 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
80 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
82 [BTRFS_RAID_RAID1C3] = {
87 .tolerated_failures = 2,
91 .raid_name = "raid1c3",
92 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
93 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
95 [BTRFS_RAID_RAID1C4] = {
100 .tolerated_failures = 3,
104 .raid_name = "raid1c4",
105 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
106 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
113 .tolerated_failures = 0,
118 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
121 [BTRFS_RAID_RAID0] = {
126 .tolerated_failures = 0,
130 .raid_name = "raid0",
131 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
134 [BTRFS_RAID_SINGLE] = {
139 .tolerated_failures = 0,
143 .raid_name = "single",
147 [BTRFS_RAID_RAID5] = {
152 .tolerated_failures = 1,
156 .raid_name = "raid5",
157 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
158 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
160 [BTRFS_RAID_RAID6] = {
165 .tolerated_failures = 2,
169 .raid_name = "raid6",
170 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
171 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
176 * Convert block group flags (BTRFS_BLOCK_GROUP_*) to btrfs_raid_types, which
177 * can be used as index to access btrfs_raid_array[].
179 enum btrfs_raid_types __attribute_const__ btrfs_bg_flags_to_raid_index(u64 flags)
181 const u64 profile = (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK);
184 return BTRFS_RAID_SINGLE;
186 return BTRFS_BG_FLAG_TO_INDEX(profile);
189 const char *btrfs_bg_type_to_raid_name(u64 flags)
191 const int index = btrfs_bg_flags_to_raid_index(flags);
193 if (index >= BTRFS_NR_RAID_TYPES)
196 return btrfs_raid_array[index].raid_name;
199 int btrfs_nr_parity_stripes(u64 type)
201 enum btrfs_raid_types index = btrfs_bg_flags_to_raid_index(type);
203 return btrfs_raid_array[index].nparity;
207 * Fill @buf with textual description of @bg_flags, no more than @size_buf
208 * bytes including terminating null byte.
210 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
215 u64 flags = bg_flags;
216 u32 size_bp = size_buf;
223 #define DESCRIBE_FLAG(flag, desc) \
225 if (flags & (flag)) { \
226 ret = snprintf(bp, size_bp, "%s|", (desc)); \
227 if (ret < 0 || ret >= size_bp) \
235 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
236 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
237 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
239 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
240 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
241 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
242 btrfs_raid_array[i].raid_name);
246 ret = snprintf(bp, size_bp, "0x%llx|", flags);
250 if (size_bp < size_buf)
251 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
254 * The text is trimmed, it's up to the caller to provide sufficiently
260 static int init_first_rw_device(struct btrfs_trans_handle *trans);
261 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
262 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
268 * There are several mutexes that protect manipulation of devices and low-level
269 * structures like chunks but not block groups, extents or files
271 * uuid_mutex (global lock)
272 * ------------------------
273 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
274 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
275 * device) or requested by the device= mount option
277 * the mutex can be very coarse and can cover long-running operations
279 * protects: updates to fs_devices counters like missing devices, rw devices,
280 * seeding, structure cloning, opening/closing devices at mount/umount time
282 * global::fs_devs - add, remove, updates to the global list
284 * does not protect: manipulation of the fs_devices::devices list in general
285 * but in mount context it could be used to exclude list modifications by eg.
288 * btrfs_device::name - renames (write side), read is RCU
290 * fs_devices::device_list_mutex (per-fs, with RCU)
291 * ------------------------------------------------
292 * protects updates to fs_devices::devices, ie. adding and deleting
294 * simple list traversal with read-only actions can be done with RCU protection
296 * may be used to exclude some operations from running concurrently without any
297 * modifications to the list (see write_all_supers)
299 * Is not required at mount and close times, because our device list is
300 * protected by the uuid_mutex at that point.
304 * protects balance structures (status, state) and context accessed from
305 * several places (internally, ioctl)
309 * protects chunks, adding or removing during allocation, trim or when a new
310 * device is added/removed. Additionally it also protects post_commit_list of
311 * individual devices, since they can be added to the transaction's
312 * post_commit_list only with chunk_mutex held.
316 * a big lock that is held by the cleaner thread and prevents running subvolume
317 * cleaning together with relocation or delayed iputs
329 * Exclusive operations
330 * ====================
332 * Maintains the exclusivity of the following operations that apply to the
333 * whole filesystem and cannot run in parallel.
338 * - Device replace (*)
341 * The device operations (as above) can be in one of the following states:
347 * Only device operations marked with (*) can go into the Paused state for the
350 * - ioctl (only Balance can be Paused through ioctl)
351 * - filesystem remounted as read-only
352 * - filesystem unmounted and mounted as read-only
353 * - system power-cycle and filesystem mounted as read-only
354 * - filesystem or device errors leading to forced read-only
356 * The status of exclusive operation is set and cleared atomically.
357 * During the course of Paused state, fs_info::exclusive_operation remains set.
358 * A device operation in Paused or Running state can be canceled or resumed
359 * either by ioctl (Balance only) or when remounted as read-write.
360 * The exclusive status is cleared when the device operation is canceled or
364 DEFINE_MUTEX(uuid_mutex);
365 static LIST_HEAD(fs_uuids);
366 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
372 * Allocate new btrfs_fs_devices structure identified by a fsid.
374 * @fsid: if not NULL, copy the UUID to fs_devices::fsid and to
375 * fs_devices::metadata_fsid
377 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
378 * The returned struct is not linked onto any lists and can be destroyed with
379 * kfree() right away.
381 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
383 struct btrfs_fs_devices *fs_devs;
385 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
387 return ERR_PTR(-ENOMEM);
389 mutex_init(&fs_devs->device_list_mutex);
391 INIT_LIST_HEAD(&fs_devs->devices);
392 INIT_LIST_HEAD(&fs_devs->alloc_list);
393 INIT_LIST_HEAD(&fs_devs->fs_list);
394 INIT_LIST_HEAD(&fs_devs->seed_list);
397 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
398 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
404 static void btrfs_free_device(struct btrfs_device *device)
406 WARN_ON(!list_empty(&device->post_commit_list));
407 rcu_string_free(device->name);
408 extent_io_tree_release(&device->alloc_state);
409 btrfs_destroy_dev_zone_info(device);
413 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
415 struct btrfs_device *device;
417 WARN_ON(fs_devices->opened);
418 while (!list_empty(&fs_devices->devices)) {
419 device = list_entry(fs_devices->devices.next,
420 struct btrfs_device, dev_list);
421 list_del(&device->dev_list);
422 btrfs_free_device(device);
427 void __exit btrfs_cleanup_fs_uuids(void)
429 struct btrfs_fs_devices *fs_devices;
431 while (!list_empty(&fs_uuids)) {
432 fs_devices = list_entry(fs_uuids.next,
433 struct btrfs_fs_devices, fs_list);
434 list_del(&fs_devices->fs_list);
435 free_fs_devices(fs_devices);
439 static bool match_fsid_fs_devices(const struct btrfs_fs_devices *fs_devices,
440 const u8 *fsid, const u8 *metadata_fsid)
442 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) != 0)
448 if (memcmp(metadata_fsid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE) != 0)
454 static noinline struct btrfs_fs_devices *find_fsid(
455 const u8 *fsid, const u8 *metadata_fsid)
457 struct btrfs_fs_devices *fs_devices;
461 /* Handle non-split brain cases */
462 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
463 if (match_fsid_fs_devices(fs_devices, fsid, metadata_fsid))
470 btrfs_get_bdev_and_sb(const char *device_path, blk_mode_t flags, void *holder,
471 int flush, struct bdev_handle **bdev_handle,
472 struct btrfs_super_block **disk_super)
474 struct block_device *bdev;
477 *bdev_handle = bdev_open_by_path(device_path, flags, holder, NULL);
479 if (IS_ERR(*bdev_handle)) {
480 ret = PTR_ERR(*bdev_handle);
483 bdev = (*bdev_handle)->bdev;
487 ret = set_blocksize(bdev, BTRFS_BDEV_BLOCKSIZE);
489 bdev_release(*bdev_handle);
492 invalidate_bdev(bdev);
493 *disk_super = btrfs_read_dev_super(bdev);
494 if (IS_ERR(*disk_super)) {
495 ret = PTR_ERR(*disk_super);
496 bdev_release(*bdev_handle);
508 * Search and remove all stale devices (which are not mounted). When both
509 * inputs are NULL, it will search and release all stale devices.
511 * @devt: Optional. When provided will it release all unmounted devices
512 * matching this devt only.
513 * @skip_device: Optional. Will skip this device when searching for the stale
516 * Return: 0 for success or if @devt is 0.
517 * -EBUSY if @devt is a mounted device.
518 * -ENOENT if @devt does not match any device in the list.
520 static int btrfs_free_stale_devices(dev_t devt, struct btrfs_device *skip_device)
522 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
523 struct btrfs_device *device, *tmp_device;
527 lockdep_assert_held(&uuid_mutex);
529 /* Return good status if there is no instance of devt. */
531 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
533 mutex_lock(&fs_devices->device_list_mutex);
534 list_for_each_entry_safe(device, tmp_device,
535 &fs_devices->devices, dev_list) {
536 if (skip_device && skip_device == device)
538 if (devt && devt != device->devt)
540 if (fs_devices->opened) {
546 /* delete the stale device */
547 fs_devices->num_devices--;
548 list_del(&device->dev_list);
549 btrfs_free_device(device);
553 mutex_unlock(&fs_devices->device_list_mutex);
555 if (fs_devices->num_devices == 0) {
556 btrfs_sysfs_remove_fsid(fs_devices);
557 list_del(&fs_devices->fs_list);
558 free_fs_devices(fs_devices);
562 /* If there is at least one freed device return 0. */
569 static struct btrfs_fs_devices *find_fsid_by_device(
570 struct btrfs_super_block *disk_super,
571 dev_t devt, bool *same_fsid_diff_dev)
573 struct btrfs_fs_devices *fsid_fs_devices;
574 struct btrfs_fs_devices *devt_fs_devices;
575 const bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
576 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
577 bool found_by_devt = false;
579 /* Find the fs_device by the usual method, if found use it. */
580 fsid_fs_devices = find_fsid(disk_super->fsid,
581 has_metadata_uuid ? disk_super->metadata_uuid : NULL);
583 /* The temp_fsid feature is supported only with single device filesystem. */
584 if (btrfs_super_num_devices(disk_super) != 1)
585 return fsid_fs_devices;
588 * A seed device is an integral component of the sprout device, which
589 * functions as a multi-device filesystem. So, temp-fsid feature is
592 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING)
593 return fsid_fs_devices;
595 /* Try to find a fs_devices by matching devt. */
596 list_for_each_entry(devt_fs_devices, &fs_uuids, fs_list) {
597 struct btrfs_device *device;
599 list_for_each_entry(device, &devt_fs_devices->devices, dev_list) {
600 if (device->devt == devt) {
601 found_by_devt = true;
610 /* Existing device. */
611 if (fsid_fs_devices == NULL) {
612 if (devt_fs_devices->opened == 0) {
616 /* temp_fsid is mounting a subvol. */
617 return devt_fs_devices;
620 /* Regular or temp_fsid device mounting a subvol. */
621 return devt_fs_devices;
625 if (fsid_fs_devices == NULL) {
628 /* sb::fsid is already used create a new temp_fsid. */
629 *same_fsid_diff_dev = true;
638 * This is only used on mount, and we are protected from competing things
639 * messing with our fs_devices by the uuid_mutex, thus we do not need the
640 * fs_devices->device_list_mutex here.
642 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
643 struct btrfs_device *device, blk_mode_t flags,
646 struct bdev_handle *bdev_handle;
647 struct btrfs_super_block *disk_super;
656 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
657 &bdev_handle, &disk_super);
661 devid = btrfs_stack_device_id(&disk_super->dev_item);
662 if (devid != device->devid)
663 goto error_free_page;
665 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
666 goto error_free_page;
668 device->generation = btrfs_super_generation(disk_super);
670 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
671 if (btrfs_super_incompat_flags(disk_super) &
672 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
674 "BTRFS: Invalid seeding and uuid-changed device detected\n");
675 goto error_free_page;
678 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
679 fs_devices->seeding = true;
681 if (bdev_read_only(bdev_handle->bdev))
682 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
684 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
687 if (!bdev_nonrot(bdev_handle->bdev))
688 fs_devices->rotating = true;
690 if (bdev_max_discard_sectors(bdev_handle->bdev))
691 fs_devices->discardable = true;
693 device->bdev_handle = bdev_handle;
694 device->bdev = bdev_handle->bdev;
695 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
697 if (device->devt != device->bdev->bd_dev) {
699 "device %s maj:min changed from %d:%d to %d:%d",
700 device->name->str, MAJOR(device->devt),
701 MINOR(device->devt), MAJOR(device->bdev->bd_dev),
702 MINOR(device->bdev->bd_dev));
704 device->devt = device->bdev->bd_dev;
707 fs_devices->open_devices++;
708 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
709 device->devid != BTRFS_DEV_REPLACE_DEVID) {
710 fs_devices->rw_devices++;
711 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
713 btrfs_release_disk_super(disk_super);
718 btrfs_release_disk_super(disk_super);
719 bdev_release(bdev_handle);
724 u8 *btrfs_sb_fsid_ptr(struct btrfs_super_block *sb)
726 bool has_metadata_uuid = (btrfs_super_incompat_flags(sb) &
727 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
729 return has_metadata_uuid ? sb->metadata_uuid : sb->fsid;
733 * Add new device to list of registered devices
736 * device pointer which was just added or updated when successful
737 * error pointer when failed
739 static noinline struct btrfs_device *device_list_add(const char *path,
740 struct btrfs_super_block *disk_super,
741 bool *new_device_added)
743 struct btrfs_device *device;
744 struct btrfs_fs_devices *fs_devices = NULL;
745 struct rcu_string *name;
746 u64 found_transid = btrfs_super_generation(disk_super);
747 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
750 bool same_fsid_diff_dev = false;
751 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
752 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
754 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
756 "device %s has incomplete metadata_uuid change, please use btrfstune to complete",
758 return ERR_PTR(-EAGAIN);
761 error = lookup_bdev(path, &path_devt);
763 btrfs_err(NULL, "failed to lookup block device for path %s: %d",
765 return ERR_PTR(error);
768 fs_devices = find_fsid_by_device(disk_super, path_devt, &same_fsid_diff_dev);
771 fs_devices = alloc_fs_devices(disk_super->fsid);
772 if (IS_ERR(fs_devices))
773 return ERR_CAST(fs_devices);
775 if (has_metadata_uuid)
776 memcpy(fs_devices->metadata_uuid,
777 disk_super->metadata_uuid, BTRFS_FSID_SIZE);
779 if (same_fsid_diff_dev) {
780 generate_random_uuid(fs_devices->fsid);
781 fs_devices->temp_fsid = true;
782 pr_info("BTRFS: device %s using temp-fsid %pU\n",
783 path, fs_devices->fsid);
786 mutex_lock(&fs_devices->device_list_mutex);
787 list_add(&fs_devices->fs_list, &fs_uuids);
791 struct btrfs_dev_lookup_args args = {
793 .uuid = disk_super->dev_item.uuid,
796 mutex_lock(&fs_devices->device_list_mutex);
797 device = btrfs_find_device(fs_devices, &args);
799 if (found_transid > fs_devices->latest_generation) {
800 memcpy(fs_devices->fsid, disk_super->fsid,
802 memcpy(fs_devices->metadata_uuid,
803 btrfs_sb_fsid_ptr(disk_super), BTRFS_FSID_SIZE);
808 unsigned int nofs_flag;
810 if (fs_devices->opened) {
812 "device %s belongs to fsid %pU, and the fs is already mounted, scanned by %s (%d)",
813 path, fs_devices->fsid, current->comm,
814 task_pid_nr(current));
815 mutex_unlock(&fs_devices->device_list_mutex);
816 return ERR_PTR(-EBUSY);
819 nofs_flag = memalloc_nofs_save();
820 device = btrfs_alloc_device(NULL, &devid,
821 disk_super->dev_item.uuid, path);
822 memalloc_nofs_restore(nofs_flag);
823 if (IS_ERR(device)) {
824 mutex_unlock(&fs_devices->device_list_mutex);
825 /* we can safely leave the fs_devices entry around */
829 device->devt = path_devt;
831 list_add_rcu(&device->dev_list, &fs_devices->devices);
832 fs_devices->num_devices++;
834 device->fs_devices = fs_devices;
835 *new_device_added = true;
837 if (disk_super->label[0])
839 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
840 disk_super->label, devid, found_transid, path,
841 current->comm, task_pid_nr(current));
844 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
845 disk_super->fsid, devid, found_transid, path,
846 current->comm, task_pid_nr(current));
848 } else if (!device->name || strcmp(device->name->str, path)) {
850 * When FS is already mounted.
851 * 1. If you are here and if the device->name is NULL that
852 * means this device was missing at time of FS mount.
853 * 2. If you are here and if the device->name is different
854 * from 'path' that means either
855 * a. The same device disappeared and reappeared with
857 * b. The missing-disk-which-was-replaced, has
860 * We must allow 1 and 2a above. But 2b would be a spurious
863 * Further in case of 1 and 2a above, the disk at 'path'
864 * would have missed some transaction when it was away and
865 * in case of 2a the stale bdev has to be updated as well.
866 * 2b must not be allowed at all time.
870 * For now, we do allow update to btrfs_fs_device through the
871 * btrfs dev scan cli after FS has been mounted. We're still
872 * tracking a problem where systems fail mount by subvolume id
873 * when we reject replacement on a mounted FS.
875 if (!fs_devices->opened && found_transid < device->generation) {
877 * That is if the FS is _not_ mounted and if you
878 * are here, that means there is more than one
879 * disk with same uuid and devid.We keep the one
880 * with larger generation number or the last-in if
881 * generation are equal.
883 mutex_unlock(&fs_devices->device_list_mutex);
885 "device %s already registered with a higher generation, found %llu expect %llu",
886 path, found_transid, device->generation);
887 return ERR_PTR(-EEXIST);
891 * We are going to replace the device path for a given devid,
892 * make sure it's the same device if the device is mounted
894 * NOTE: the device->fs_info may not be reliable here so pass
895 * in a NULL to message helpers instead. This avoids a possible
896 * use-after-free when the fs_info and fs_info->sb are already
900 if (device->devt != path_devt) {
901 mutex_unlock(&fs_devices->device_list_mutex);
902 btrfs_warn_in_rcu(NULL,
903 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
904 path, devid, found_transid,
906 task_pid_nr(current));
907 return ERR_PTR(-EEXIST);
909 btrfs_info_in_rcu(NULL,
910 "devid %llu device path %s changed to %s scanned by %s (%d)",
911 devid, btrfs_dev_name(device),
913 task_pid_nr(current));
916 name = rcu_string_strdup(path, GFP_NOFS);
918 mutex_unlock(&fs_devices->device_list_mutex);
919 return ERR_PTR(-ENOMEM);
921 rcu_string_free(device->name);
922 rcu_assign_pointer(device->name, name);
923 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
924 fs_devices->missing_devices--;
925 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
927 device->devt = path_devt;
931 * Unmount does not free the btrfs_device struct but would zero
932 * generation along with most of the other members. So just update
933 * it back. We need it to pick the disk with largest generation
936 if (!fs_devices->opened) {
937 device->generation = found_transid;
938 fs_devices->latest_generation = max_t(u64, found_transid,
939 fs_devices->latest_generation);
942 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
944 mutex_unlock(&fs_devices->device_list_mutex);
948 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
950 struct btrfs_fs_devices *fs_devices;
951 struct btrfs_device *device;
952 struct btrfs_device *orig_dev;
955 lockdep_assert_held(&uuid_mutex);
957 fs_devices = alloc_fs_devices(orig->fsid);
958 if (IS_ERR(fs_devices))
961 fs_devices->total_devices = orig->total_devices;
963 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
964 const char *dev_path = NULL;
967 * This is ok to do without RCU read locked because we hold the
968 * uuid mutex so nothing we touch in here is going to disappear.
971 dev_path = orig_dev->name->str;
973 device = btrfs_alloc_device(NULL, &orig_dev->devid,
974 orig_dev->uuid, dev_path);
975 if (IS_ERR(device)) {
976 ret = PTR_ERR(device);
980 if (orig_dev->zone_info) {
981 struct btrfs_zoned_device_info *zone_info;
983 zone_info = btrfs_clone_dev_zone_info(orig_dev);
985 btrfs_free_device(device);
989 device->zone_info = zone_info;
992 list_add(&device->dev_list, &fs_devices->devices);
993 device->fs_devices = fs_devices;
994 fs_devices->num_devices++;
998 free_fs_devices(fs_devices);
1002 static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
1003 struct btrfs_device **latest_dev)
1005 struct btrfs_device *device, *next;
1007 /* This is the initialized path, it is safe to release the devices. */
1008 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1009 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
1010 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1011 &device->dev_state) &&
1012 !test_bit(BTRFS_DEV_STATE_MISSING,
1013 &device->dev_state) &&
1015 device->generation > (*latest_dev)->generation)) {
1016 *latest_dev = device;
1022 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1023 * in btrfs_init_dev_replace() so just continue.
1025 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1028 if (device->bdev_handle) {
1029 bdev_release(device->bdev_handle);
1030 device->bdev = NULL;
1031 device->bdev_handle = NULL;
1032 fs_devices->open_devices--;
1034 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1035 list_del_init(&device->dev_alloc_list);
1036 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1037 fs_devices->rw_devices--;
1039 list_del_init(&device->dev_list);
1040 fs_devices->num_devices--;
1041 btrfs_free_device(device);
1047 * After we have read the system tree and know devids belonging to this
1048 * filesystem, remove the device which does not belong there.
1050 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices)
1052 struct btrfs_device *latest_dev = NULL;
1053 struct btrfs_fs_devices *seed_dev;
1055 mutex_lock(&uuid_mutex);
1056 __btrfs_free_extra_devids(fs_devices, &latest_dev);
1058 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1059 __btrfs_free_extra_devids(seed_dev, &latest_dev);
1061 fs_devices->latest_dev = latest_dev;
1063 mutex_unlock(&uuid_mutex);
1066 static void btrfs_close_bdev(struct btrfs_device *device)
1071 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1072 sync_blockdev(device->bdev);
1073 invalidate_bdev(device->bdev);
1076 bdev_release(device->bdev_handle);
1079 static void btrfs_close_one_device(struct btrfs_device *device)
1081 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1083 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1084 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1085 list_del_init(&device->dev_alloc_list);
1086 fs_devices->rw_devices--;
1089 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1090 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
1092 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1093 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1094 fs_devices->missing_devices--;
1097 btrfs_close_bdev(device);
1099 fs_devices->open_devices--;
1100 device->bdev = NULL;
1102 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1103 btrfs_destroy_dev_zone_info(device);
1105 device->fs_info = NULL;
1106 atomic_set(&device->dev_stats_ccnt, 0);
1107 extent_io_tree_release(&device->alloc_state);
1110 * Reset the flush error record. We might have a transient flush error
1111 * in this mount, and if so we aborted the current transaction and set
1112 * the fs to an error state, guaranteeing no super blocks can be further
1113 * committed. However that error might be transient and if we unmount the
1114 * filesystem and mount it again, we should allow the mount to succeed
1115 * (btrfs_check_rw_degradable() should not fail) - if after mounting the
1116 * filesystem again we still get flush errors, then we will again abort
1117 * any transaction and set the error state, guaranteeing no commits of
1118 * unsafe super blocks.
1120 device->last_flush_error = 0;
1122 /* Verify the device is back in a pristine state */
1123 WARN_ON(test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1124 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1125 WARN_ON(!list_empty(&device->dev_alloc_list));
1126 WARN_ON(!list_empty(&device->post_commit_list));
1129 static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
1131 struct btrfs_device *device, *tmp;
1133 lockdep_assert_held(&uuid_mutex);
1135 if (--fs_devices->opened > 0)
1138 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
1139 btrfs_close_one_device(device);
1141 WARN_ON(fs_devices->open_devices);
1142 WARN_ON(fs_devices->rw_devices);
1143 fs_devices->opened = 0;
1144 fs_devices->seeding = false;
1145 fs_devices->fs_info = NULL;
1148 void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1151 struct btrfs_fs_devices *tmp;
1153 mutex_lock(&uuid_mutex);
1154 close_fs_devices(fs_devices);
1155 if (!fs_devices->opened) {
1156 list_splice_init(&fs_devices->seed_list, &list);
1159 * If the struct btrfs_fs_devices is not assembled with any
1160 * other device, it can be re-initialized during the next mount
1161 * without the needing device-scan step. Therefore, it can be
1164 if (fs_devices->num_devices == 1) {
1165 list_del(&fs_devices->fs_list);
1166 free_fs_devices(fs_devices);
1171 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
1172 close_fs_devices(fs_devices);
1173 list_del(&fs_devices->seed_list);
1174 free_fs_devices(fs_devices);
1176 mutex_unlock(&uuid_mutex);
1179 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1180 blk_mode_t flags, void *holder)
1182 struct btrfs_device *device;
1183 struct btrfs_device *latest_dev = NULL;
1184 struct btrfs_device *tmp_device;
1186 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1190 ret = btrfs_open_one_device(fs_devices, device, flags, holder);
1192 (!latest_dev || device->generation > latest_dev->generation)) {
1193 latest_dev = device;
1194 } else if (ret == -ENODATA) {
1195 fs_devices->num_devices--;
1196 list_del(&device->dev_list);
1197 btrfs_free_device(device);
1200 if (fs_devices->open_devices == 0)
1203 fs_devices->opened = 1;
1204 fs_devices->latest_dev = latest_dev;
1205 fs_devices->total_rw_bytes = 0;
1206 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1207 fs_devices->read_policy = BTRFS_READ_POLICY_PID;
1212 static int devid_cmp(void *priv, const struct list_head *a,
1213 const struct list_head *b)
1215 const struct btrfs_device *dev1, *dev2;
1217 dev1 = list_entry(a, struct btrfs_device, dev_list);
1218 dev2 = list_entry(b, struct btrfs_device, dev_list);
1220 if (dev1->devid < dev2->devid)
1222 else if (dev1->devid > dev2->devid)
1227 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1228 blk_mode_t flags, void *holder)
1232 lockdep_assert_held(&uuid_mutex);
1234 * The device_list_mutex cannot be taken here in case opening the
1235 * underlying device takes further locks like open_mutex.
1237 * We also don't need the lock here as this is called during mount and
1238 * exclusion is provided by uuid_mutex
1241 if (fs_devices->opened) {
1242 fs_devices->opened++;
1245 list_sort(NULL, &fs_devices->devices, devid_cmp);
1246 ret = open_fs_devices(fs_devices, flags, holder);
1252 void btrfs_release_disk_super(struct btrfs_super_block *super)
1254 struct page *page = virt_to_page(super);
1259 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1260 u64 bytenr, u64 bytenr_orig)
1262 struct btrfs_super_block *disk_super;
1267 /* make sure our super fits in the device */
1268 if (bytenr + PAGE_SIZE >= bdev_nr_bytes(bdev))
1269 return ERR_PTR(-EINVAL);
1271 /* make sure our super fits in the page */
1272 if (sizeof(*disk_super) > PAGE_SIZE)
1273 return ERR_PTR(-EINVAL);
1275 /* make sure our super doesn't straddle pages on disk */
1276 index = bytenr >> PAGE_SHIFT;
1277 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1278 return ERR_PTR(-EINVAL);
1280 /* pull in the page with our super */
1281 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1284 return ERR_CAST(page);
1286 p = page_address(page);
1288 /* align our pointer to the offset of the super block */
1289 disk_super = p + offset_in_page(bytenr);
1291 if (btrfs_super_bytenr(disk_super) != bytenr_orig ||
1292 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1293 btrfs_release_disk_super(p);
1294 return ERR_PTR(-EINVAL);
1297 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1298 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1303 int btrfs_forget_devices(dev_t devt)
1307 mutex_lock(&uuid_mutex);
1308 ret = btrfs_free_stale_devices(devt, NULL);
1309 mutex_unlock(&uuid_mutex);
1314 static bool btrfs_skip_registration(struct btrfs_super_block *disk_super,
1315 const char *path, dev_t devt,
1318 struct btrfs_fs_devices *fs_devices;
1321 * Do not skip device registration for mounted devices with matching
1322 * maj:min but different paths. Booting without initrd relies on
1323 * /dev/root initially, later replaced with the actual root device.
1324 * A successful scan ensures grub2-probe selects the correct device.
1326 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
1327 struct btrfs_device *device;
1329 mutex_lock(&fs_devices->device_list_mutex);
1331 if (!fs_devices->opened) {
1332 mutex_unlock(&fs_devices->device_list_mutex);
1336 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1337 if (device->bdev && (device->bdev->bd_dev == devt) &&
1338 strcmp(device->name->str, path) != 0) {
1339 mutex_unlock(&fs_devices->device_list_mutex);
1341 /* Do not skip registration. */
1345 mutex_unlock(&fs_devices->device_list_mutex);
1348 if (!mount_arg_dev && btrfs_super_num_devices(disk_super) == 1 &&
1349 !(btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING))
1356 * Look for a btrfs signature on a device. This may be called out of the mount path
1357 * and we are not allowed to call set_blocksize during the scan. The superblock
1358 * is read via pagecache.
1360 * With @mount_arg_dev it's a scan during mount time that will always register
1361 * the device or return an error. Multi-device and seeding devices are registered
1364 struct btrfs_device *btrfs_scan_one_device(const char *path, blk_mode_t flags,
1367 struct btrfs_super_block *disk_super;
1368 bool new_device_added = false;
1369 struct btrfs_device *device = NULL;
1370 struct bdev_handle *bdev_handle;
1371 u64 bytenr, bytenr_orig;
1374 lockdep_assert_held(&uuid_mutex);
1377 * we would like to check all the supers, but that would make
1378 * a btrfs mount succeed after a mkfs from a different FS.
1379 * So, we need to add a special mount option to scan for
1380 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1384 * Avoid an exclusive open here, as the systemd-udev may initiate the
1385 * device scan which may race with the user's mount or mkfs command,
1386 * resulting in failure.
1387 * Since the device scan is solely for reading purposes, there is no
1388 * need for an exclusive open. Additionally, the devices are read again
1389 * during the mount process. It is ok to get some inconsistent
1390 * values temporarily, as the device paths of the fsid are the only
1391 * required information for assembling the volume.
1393 bdev_handle = bdev_open_by_path(path, flags, NULL, NULL);
1394 if (IS_ERR(bdev_handle))
1395 return ERR_CAST(bdev_handle);
1397 bytenr_orig = btrfs_sb_offset(0);
1398 ret = btrfs_sb_log_location_bdev(bdev_handle->bdev, 0, READ, &bytenr);
1400 device = ERR_PTR(ret);
1401 goto error_bdev_put;
1404 disk_super = btrfs_read_disk_super(bdev_handle->bdev, bytenr,
1406 if (IS_ERR(disk_super)) {
1407 device = ERR_CAST(disk_super);
1408 goto error_bdev_put;
1411 if (btrfs_skip_registration(disk_super, path, bdev_handle->bdev->bd_dev,
1413 pr_debug("BTRFS: skip registering single non-seed device %s (%d:%d)\n",
1414 path, MAJOR(bdev_handle->bdev->bd_dev),
1415 MINOR(bdev_handle->bdev->bd_dev));
1417 btrfs_free_stale_devices(bdev_handle->bdev->bd_dev, NULL);
1420 goto free_disk_super;
1423 device = device_list_add(path, disk_super, &new_device_added);
1424 if (!IS_ERR(device) && new_device_added)
1425 btrfs_free_stale_devices(device->devt, device);
1428 btrfs_release_disk_super(disk_super);
1431 bdev_release(bdev_handle);
1437 * Try to find a chunk that intersects [start, start + len] range and when one
1438 * such is found, record the end of it in *start
1440 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1443 u64 physical_start, physical_end;
1445 lockdep_assert_held(&device->fs_info->chunk_mutex);
1447 if (find_first_extent_bit(&device->alloc_state, *start,
1448 &physical_start, &physical_end,
1449 CHUNK_ALLOCATED, NULL)) {
1451 if (in_range(physical_start, *start, len) ||
1452 in_range(*start, physical_start,
1453 physical_end + 1 - physical_start)) {
1454 *start = physical_end + 1;
1461 static u64 dev_extent_search_start(struct btrfs_device *device)
1463 switch (device->fs_devices->chunk_alloc_policy) {
1464 case BTRFS_CHUNK_ALLOC_REGULAR:
1465 return BTRFS_DEVICE_RANGE_RESERVED;
1466 case BTRFS_CHUNK_ALLOC_ZONED:
1468 * We don't care about the starting region like regular
1469 * allocator, because we anyway use/reserve the first two zones
1470 * for superblock logging.
1478 static bool dev_extent_hole_check_zoned(struct btrfs_device *device,
1479 u64 *hole_start, u64 *hole_size,
1482 u64 zone_size = device->zone_info->zone_size;
1485 bool changed = false;
1487 ASSERT(IS_ALIGNED(*hole_start, zone_size));
1489 while (*hole_size > 0) {
1490 pos = btrfs_find_allocatable_zones(device, *hole_start,
1491 *hole_start + *hole_size,
1493 if (pos != *hole_start) {
1494 *hole_size = *hole_start + *hole_size - pos;
1497 if (*hole_size < num_bytes)
1501 ret = btrfs_ensure_empty_zones(device, pos, num_bytes);
1503 /* Range is ensured to be empty */
1507 /* Given hole range was invalid (outside of device) */
1508 if (ret == -ERANGE) {
1509 *hole_start += *hole_size;
1514 *hole_start += zone_size;
1515 *hole_size -= zone_size;
1523 * Check if specified hole is suitable for allocation.
1525 * @device: the device which we have the hole
1526 * @hole_start: starting position of the hole
1527 * @hole_size: the size of the hole
1528 * @num_bytes: the size of the free space that we need
1530 * This function may modify @hole_start and @hole_size to reflect the suitable
1531 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1533 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1534 u64 *hole_size, u64 num_bytes)
1536 bool changed = false;
1537 u64 hole_end = *hole_start + *hole_size;
1541 * Check before we set max_hole_start, otherwise we could end up
1542 * sending back this offset anyway.
1544 if (contains_pending_extent(device, hole_start, *hole_size)) {
1545 if (hole_end >= *hole_start)
1546 *hole_size = hole_end - *hole_start;
1552 switch (device->fs_devices->chunk_alloc_policy) {
1553 case BTRFS_CHUNK_ALLOC_REGULAR:
1554 /* No extra check */
1556 case BTRFS_CHUNK_ALLOC_ZONED:
1557 if (dev_extent_hole_check_zoned(device, hole_start,
1558 hole_size, num_bytes)) {
1561 * The changed hole can contain pending extent.
1562 * Loop again to check that.
1578 * Find free space in the specified device.
1580 * @device: the device which we search the free space in
1581 * @num_bytes: the size of the free space that we need
1582 * @search_start: the position from which to begin the search
1583 * @start: store the start of the free space.
1584 * @len: the size of the free space. that we find, or the size
1585 * of the max free space if we don't find suitable free space
1587 * This does a pretty simple search, the expectation is that it is called very
1588 * infrequently and that a given device has a small number of extents.
1590 * @start is used to store the start of the free space if we find. But if we
1591 * don't find suitable free space, it will be used to store the start position
1592 * of the max free space.
1594 * @len is used to store the size of the free space that we find.
1595 * But if we don't find suitable free space, it is used to store the size of
1596 * the max free space.
1598 * NOTE: This function will search *commit* root of device tree, and does extra
1599 * check to ensure dev extents are not double allocated.
1600 * This makes the function safe to allocate dev extents but may not report
1601 * correct usable device space, as device extent freed in current transaction
1602 * is not reported as available.
1604 static int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1605 u64 *start, u64 *len)
1607 struct btrfs_fs_info *fs_info = device->fs_info;
1608 struct btrfs_root *root = fs_info->dev_root;
1609 struct btrfs_key key;
1610 struct btrfs_dev_extent *dev_extent;
1611 struct btrfs_path *path;
1615 u64 max_hole_size = 0;
1617 u64 search_end = device->total_bytes;
1620 struct extent_buffer *l;
1622 search_start = dev_extent_search_start(device);
1623 max_hole_start = search_start;
1625 WARN_ON(device->zone_info &&
1626 !IS_ALIGNED(num_bytes, device->zone_info->zone_size));
1628 path = btrfs_alloc_path();
1634 if (search_start >= search_end ||
1635 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1640 path->reada = READA_FORWARD;
1641 path->search_commit_root = 1;
1642 path->skip_locking = 1;
1644 key.objectid = device->devid;
1645 key.offset = search_start;
1646 key.type = BTRFS_DEV_EXTENT_KEY;
1648 ret = btrfs_search_backwards(root, &key, path);
1652 while (search_start < search_end) {
1654 slot = path->slots[0];
1655 if (slot >= btrfs_header_nritems(l)) {
1656 ret = btrfs_next_leaf(root, path);
1664 btrfs_item_key_to_cpu(l, &key, slot);
1666 if (key.objectid < device->devid)
1669 if (key.objectid > device->devid)
1672 if (key.type != BTRFS_DEV_EXTENT_KEY)
1675 if (key.offset > search_end)
1678 if (key.offset > search_start) {
1679 hole_size = key.offset - search_start;
1680 dev_extent_hole_check(device, &search_start, &hole_size,
1683 if (hole_size > max_hole_size) {
1684 max_hole_start = search_start;
1685 max_hole_size = hole_size;
1689 * If this free space is greater than which we need,
1690 * it must be the max free space that we have found
1691 * until now, so max_hole_start must point to the start
1692 * of this free space and the length of this free space
1693 * is stored in max_hole_size. Thus, we return
1694 * max_hole_start and max_hole_size and go back to the
1697 if (hole_size >= num_bytes) {
1703 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1704 extent_end = key.offset + btrfs_dev_extent_length(l,
1706 if (extent_end > search_start)
1707 search_start = extent_end;
1714 * At this point, search_start should be the end of
1715 * allocated dev extents, and when shrinking the device,
1716 * search_end may be smaller than search_start.
1718 if (search_end > search_start) {
1719 hole_size = search_end - search_start;
1720 if (dev_extent_hole_check(device, &search_start, &hole_size,
1722 btrfs_release_path(path);
1726 if (hole_size > max_hole_size) {
1727 max_hole_start = search_start;
1728 max_hole_size = hole_size;
1733 if (max_hole_size < num_bytes)
1738 ASSERT(max_hole_start + max_hole_size <= search_end);
1740 btrfs_free_path(path);
1741 *start = max_hole_start;
1743 *len = max_hole_size;
1747 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1748 struct btrfs_device *device,
1749 u64 start, u64 *dev_extent_len)
1751 struct btrfs_fs_info *fs_info = device->fs_info;
1752 struct btrfs_root *root = fs_info->dev_root;
1754 struct btrfs_path *path;
1755 struct btrfs_key key;
1756 struct btrfs_key found_key;
1757 struct extent_buffer *leaf = NULL;
1758 struct btrfs_dev_extent *extent = NULL;
1760 path = btrfs_alloc_path();
1764 key.objectid = device->devid;
1766 key.type = BTRFS_DEV_EXTENT_KEY;
1768 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1770 ret = btrfs_previous_item(root, path, key.objectid,
1771 BTRFS_DEV_EXTENT_KEY);
1774 leaf = path->nodes[0];
1775 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1776 extent = btrfs_item_ptr(leaf, path->slots[0],
1777 struct btrfs_dev_extent);
1778 BUG_ON(found_key.offset > start || found_key.offset +
1779 btrfs_dev_extent_length(leaf, extent) < start);
1781 btrfs_release_path(path);
1783 } else if (ret == 0) {
1784 leaf = path->nodes[0];
1785 extent = btrfs_item_ptr(leaf, path->slots[0],
1786 struct btrfs_dev_extent);
1791 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1793 ret = btrfs_del_item(trans, root, path);
1795 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1797 btrfs_free_path(path);
1801 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1806 read_lock(&fs_info->mapping_tree_lock);
1807 n = rb_last(&fs_info->mapping_tree.rb_root);
1809 struct btrfs_chunk_map *map;
1811 map = rb_entry(n, struct btrfs_chunk_map, rb_node);
1812 ret = map->start + map->chunk_len;
1814 read_unlock(&fs_info->mapping_tree_lock);
1819 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1823 struct btrfs_key key;
1824 struct btrfs_key found_key;
1825 struct btrfs_path *path;
1827 path = btrfs_alloc_path();
1831 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1832 key.type = BTRFS_DEV_ITEM_KEY;
1833 key.offset = (u64)-1;
1835 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1841 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1846 ret = btrfs_previous_item(fs_info->chunk_root, path,
1847 BTRFS_DEV_ITEMS_OBJECTID,
1848 BTRFS_DEV_ITEM_KEY);
1852 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1854 *devid_ret = found_key.offset + 1;
1858 btrfs_free_path(path);
1863 * the device information is stored in the chunk root
1864 * the btrfs_device struct should be fully filled in
1866 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1867 struct btrfs_device *device)
1870 struct btrfs_path *path;
1871 struct btrfs_dev_item *dev_item;
1872 struct extent_buffer *leaf;
1873 struct btrfs_key key;
1876 path = btrfs_alloc_path();
1880 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1881 key.type = BTRFS_DEV_ITEM_KEY;
1882 key.offset = device->devid;
1884 btrfs_reserve_chunk_metadata(trans, true);
1885 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1886 &key, sizeof(*dev_item));
1887 btrfs_trans_release_chunk_metadata(trans);
1891 leaf = path->nodes[0];
1892 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1894 btrfs_set_device_id(leaf, dev_item, device->devid);
1895 btrfs_set_device_generation(leaf, dev_item, 0);
1896 btrfs_set_device_type(leaf, dev_item, device->type);
1897 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1898 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1899 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1900 btrfs_set_device_total_bytes(leaf, dev_item,
1901 btrfs_device_get_disk_total_bytes(device));
1902 btrfs_set_device_bytes_used(leaf, dev_item,
1903 btrfs_device_get_bytes_used(device));
1904 btrfs_set_device_group(leaf, dev_item, 0);
1905 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1906 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1907 btrfs_set_device_start_offset(leaf, dev_item, 0);
1909 ptr = btrfs_device_uuid(dev_item);
1910 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1911 ptr = btrfs_device_fsid(dev_item);
1912 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1913 ptr, BTRFS_FSID_SIZE);
1914 btrfs_mark_buffer_dirty(trans, leaf);
1918 btrfs_free_path(path);
1923 * Function to update ctime/mtime for a given device path.
1924 * Mainly used for ctime/mtime based probe like libblkid.
1926 * We don't care about errors here, this is just to be kind to userspace.
1928 static void update_dev_time(const char *device_path)
1933 ret = kern_path(device_path, LOOKUP_FOLLOW, &path);
1937 inode_update_time(d_inode(path.dentry), S_MTIME | S_CTIME | S_VERSION);
1941 static int btrfs_rm_dev_item(struct btrfs_trans_handle *trans,
1942 struct btrfs_device *device)
1944 struct btrfs_root *root = device->fs_info->chunk_root;
1946 struct btrfs_path *path;
1947 struct btrfs_key key;
1949 path = btrfs_alloc_path();
1953 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1954 key.type = BTRFS_DEV_ITEM_KEY;
1955 key.offset = device->devid;
1957 btrfs_reserve_chunk_metadata(trans, false);
1958 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1959 btrfs_trans_release_chunk_metadata(trans);
1966 ret = btrfs_del_item(trans, root, path);
1968 btrfs_free_path(path);
1973 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1974 * filesystem. It's up to the caller to adjust that number regarding eg. device
1977 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1985 seq = read_seqbegin(&fs_info->profiles_lock);
1987 all_avail = fs_info->avail_data_alloc_bits |
1988 fs_info->avail_system_alloc_bits |
1989 fs_info->avail_metadata_alloc_bits;
1990 } while (read_seqretry(&fs_info->profiles_lock, seq));
1992 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1993 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1996 if (num_devices < btrfs_raid_array[i].devs_min)
1997 return btrfs_raid_array[i].mindev_error;
2003 static struct btrfs_device * btrfs_find_next_active_device(
2004 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2006 struct btrfs_device *next_device;
2008 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2009 if (next_device != device &&
2010 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2011 && next_device->bdev)
2019 * Helper function to check if the given device is part of s_bdev / latest_dev
2020 * and replace it with the provided or the next active device, in the context
2021 * where this function called, there should be always be another device (or
2022 * this_dev) which is active.
2024 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
2025 struct btrfs_device *next_device)
2027 struct btrfs_fs_info *fs_info = device->fs_info;
2030 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2032 ASSERT(next_device);
2034 if (fs_info->sb->s_bdev &&
2035 (fs_info->sb->s_bdev == device->bdev))
2036 fs_info->sb->s_bdev = next_device->bdev;
2038 if (fs_info->fs_devices->latest_dev->bdev == device->bdev)
2039 fs_info->fs_devices->latest_dev = next_device;
2043 * Return btrfs_fs_devices::num_devices excluding the device that's being
2044 * currently replaced.
2046 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2048 u64 num_devices = fs_info->fs_devices->num_devices;
2050 down_read(&fs_info->dev_replace.rwsem);
2051 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2052 ASSERT(num_devices > 1);
2055 up_read(&fs_info->dev_replace.rwsem);
2060 static void btrfs_scratch_superblock(struct btrfs_fs_info *fs_info,
2061 struct block_device *bdev, int copy_num)
2063 struct btrfs_super_block *disk_super;
2064 const size_t len = sizeof(disk_super->magic);
2065 const u64 bytenr = btrfs_sb_offset(copy_num);
2068 disk_super = btrfs_read_disk_super(bdev, bytenr, bytenr);
2069 if (IS_ERR(disk_super))
2072 memset(&disk_super->magic, 0, len);
2073 folio_mark_dirty(virt_to_folio(disk_super));
2074 btrfs_release_disk_super(disk_super);
2076 ret = sync_blockdev_range(bdev, bytenr, bytenr + len - 1);
2078 btrfs_warn(fs_info, "error clearing superblock number %d (%d)",
2082 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2083 struct block_device *bdev,
2084 const char *device_path)
2091 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2092 if (bdev_is_zoned(bdev))
2093 btrfs_reset_sb_log_zones(bdev, copy_num);
2095 btrfs_scratch_superblock(fs_info, bdev, copy_num);
2098 /* Notify udev that device has changed */
2099 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2101 /* Update ctime/mtime for device path for libblkid */
2102 update_dev_time(device_path);
2105 int btrfs_rm_device(struct btrfs_fs_info *fs_info,
2106 struct btrfs_dev_lookup_args *args,
2107 struct bdev_handle **bdev_handle)
2109 struct btrfs_trans_handle *trans;
2110 struct btrfs_device *device;
2111 struct btrfs_fs_devices *cur_devices;
2112 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2116 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2117 btrfs_err(fs_info, "device remove not supported on extent tree v2 yet");
2122 * The device list in fs_devices is accessed without locks (neither
2123 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2124 * filesystem and another device rm cannot run.
2126 num_devices = btrfs_num_devices(fs_info);
2128 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2132 device = btrfs_find_device(fs_info->fs_devices, args);
2135 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2141 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2142 btrfs_warn_in_rcu(fs_info,
2143 "cannot remove device %s (devid %llu) due to active swapfile",
2144 btrfs_dev_name(device), device->devid);
2148 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
2149 return BTRFS_ERROR_DEV_TGT_REPLACE;
2151 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2152 fs_info->fs_devices->rw_devices == 1)
2153 return BTRFS_ERROR_DEV_ONLY_WRITABLE;
2155 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2156 mutex_lock(&fs_info->chunk_mutex);
2157 list_del_init(&device->dev_alloc_list);
2158 device->fs_devices->rw_devices--;
2159 mutex_unlock(&fs_info->chunk_mutex);
2162 ret = btrfs_shrink_device(device, 0);
2166 trans = btrfs_start_transaction(fs_info->chunk_root, 0);
2167 if (IS_ERR(trans)) {
2168 ret = PTR_ERR(trans);
2172 ret = btrfs_rm_dev_item(trans, device);
2174 /* Any error in dev item removal is critical */
2176 "failed to remove device item for devid %llu: %d",
2177 device->devid, ret);
2178 btrfs_abort_transaction(trans, ret);
2179 btrfs_end_transaction(trans);
2183 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2184 btrfs_scrub_cancel_dev(device);
2187 * the device list mutex makes sure that we don't change
2188 * the device list while someone else is writing out all
2189 * the device supers. Whoever is writing all supers, should
2190 * lock the device list mutex before getting the number of
2191 * devices in the super block (super_copy). Conversely,
2192 * whoever updates the number of devices in the super block
2193 * (super_copy) should hold the device list mutex.
2197 * In normal cases the cur_devices == fs_devices. But in case
2198 * of deleting a seed device, the cur_devices should point to
2199 * its own fs_devices listed under the fs_devices->seed_list.
2201 cur_devices = device->fs_devices;
2202 mutex_lock(&fs_devices->device_list_mutex);
2203 list_del_rcu(&device->dev_list);
2205 cur_devices->num_devices--;
2206 cur_devices->total_devices--;
2207 /* Update total_devices of the parent fs_devices if it's seed */
2208 if (cur_devices != fs_devices)
2209 fs_devices->total_devices--;
2211 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2212 cur_devices->missing_devices--;
2214 btrfs_assign_next_active_device(device, NULL);
2216 if (device->bdev_handle) {
2217 cur_devices->open_devices--;
2218 /* remove sysfs entry */
2219 btrfs_sysfs_remove_device(device);
2222 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2223 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2224 mutex_unlock(&fs_devices->device_list_mutex);
2227 * At this point, the device is zero sized and detached from the
2228 * devices list. All that's left is to zero out the old supers and
2231 * We cannot call btrfs_close_bdev() here because we're holding the sb
2232 * write lock, and bdev_release() will pull in the ->open_mutex on
2233 * the block device and it's dependencies. Instead just flush the
2234 * device and let the caller do the final bdev_release.
2236 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2237 btrfs_scratch_superblocks(fs_info, device->bdev,
2240 sync_blockdev(device->bdev);
2241 invalidate_bdev(device->bdev);
2245 *bdev_handle = device->bdev_handle;
2247 btrfs_free_device(device);
2250 * This can happen if cur_devices is the private seed devices list. We
2251 * cannot call close_fs_devices() here because it expects the uuid_mutex
2252 * to be held, but in fact we don't need that for the private
2253 * seed_devices, we can simply decrement cur_devices->opened and then
2254 * remove it from our list and free the fs_devices.
2256 if (cur_devices->num_devices == 0) {
2257 list_del_init(&cur_devices->seed_list);
2258 ASSERT(cur_devices->opened == 1);
2259 cur_devices->opened--;
2260 free_fs_devices(cur_devices);
2263 ret = btrfs_commit_transaction(trans);
2268 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2269 mutex_lock(&fs_info->chunk_mutex);
2270 list_add(&device->dev_alloc_list,
2271 &fs_devices->alloc_list);
2272 device->fs_devices->rw_devices++;
2273 mutex_unlock(&fs_info->chunk_mutex);
2278 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2280 struct btrfs_fs_devices *fs_devices;
2282 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2285 * in case of fs with no seed, srcdev->fs_devices will point
2286 * to fs_devices of fs_info. However when the dev being replaced is
2287 * a seed dev it will point to the seed's local fs_devices. In short
2288 * srcdev will have its correct fs_devices in both the cases.
2290 fs_devices = srcdev->fs_devices;
2292 list_del_rcu(&srcdev->dev_list);
2293 list_del(&srcdev->dev_alloc_list);
2294 fs_devices->num_devices--;
2295 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2296 fs_devices->missing_devices--;
2298 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2299 fs_devices->rw_devices--;
2302 fs_devices->open_devices--;
2305 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2307 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2309 mutex_lock(&uuid_mutex);
2311 btrfs_close_bdev(srcdev);
2313 btrfs_free_device(srcdev);
2315 /* if this is no devs we rather delete the fs_devices */
2316 if (!fs_devices->num_devices) {
2318 * On a mounted FS, num_devices can't be zero unless it's a
2319 * seed. In case of a seed device being replaced, the replace
2320 * target added to the sprout FS, so there will be no more
2321 * device left under the seed FS.
2323 ASSERT(fs_devices->seeding);
2325 list_del_init(&fs_devices->seed_list);
2326 close_fs_devices(fs_devices);
2327 free_fs_devices(fs_devices);
2329 mutex_unlock(&uuid_mutex);
2332 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2334 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2336 mutex_lock(&fs_devices->device_list_mutex);
2338 btrfs_sysfs_remove_device(tgtdev);
2341 fs_devices->open_devices--;
2343 fs_devices->num_devices--;
2345 btrfs_assign_next_active_device(tgtdev, NULL);
2347 list_del_rcu(&tgtdev->dev_list);
2349 mutex_unlock(&fs_devices->device_list_mutex);
2351 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2354 btrfs_close_bdev(tgtdev);
2356 btrfs_free_device(tgtdev);
2360 * Populate args from device at path.
2362 * @fs_info: the filesystem
2363 * @args: the args to populate
2364 * @path: the path to the device
2366 * This will read the super block of the device at @path and populate @args with
2367 * the devid, fsid, and uuid. This is meant to be used for ioctls that need to
2368 * lookup a device to operate on, but need to do it before we take any locks.
2369 * This properly handles the special case of "missing" that a user may pass in,
2370 * and does some basic sanity checks. The caller must make sure that @path is
2371 * properly NUL terminated before calling in, and must call
2372 * btrfs_put_dev_args_from_path() in order to free up the temporary fsid and
2375 * Return: 0 for success, -errno for failure
2377 int btrfs_get_dev_args_from_path(struct btrfs_fs_info *fs_info,
2378 struct btrfs_dev_lookup_args *args,
2381 struct btrfs_super_block *disk_super;
2382 struct bdev_handle *bdev_handle;
2385 if (!path || !path[0])
2387 if (!strcmp(path, "missing")) {
2388 args->missing = true;
2392 args->uuid = kzalloc(BTRFS_UUID_SIZE, GFP_KERNEL);
2393 args->fsid = kzalloc(BTRFS_FSID_SIZE, GFP_KERNEL);
2394 if (!args->uuid || !args->fsid) {
2395 btrfs_put_dev_args_from_path(args);
2399 ret = btrfs_get_bdev_and_sb(path, BLK_OPEN_READ, NULL, 0,
2400 &bdev_handle, &disk_super);
2402 btrfs_put_dev_args_from_path(args);
2406 args->devid = btrfs_stack_device_id(&disk_super->dev_item);
2407 memcpy(args->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE);
2408 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2409 memcpy(args->fsid, disk_super->metadata_uuid, BTRFS_FSID_SIZE);
2411 memcpy(args->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
2412 btrfs_release_disk_super(disk_super);
2413 bdev_release(bdev_handle);
2418 * Only use this jointly with btrfs_get_dev_args_from_path() because we will
2419 * allocate our ->uuid and ->fsid pointers, everybody else uses local variables
2420 * that don't need to be freed.
2422 void btrfs_put_dev_args_from_path(struct btrfs_dev_lookup_args *args)
2430 struct btrfs_device *btrfs_find_device_by_devspec(
2431 struct btrfs_fs_info *fs_info, u64 devid,
2432 const char *device_path)
2434 BTRFS_DEV_LOOKUP_ARGS(args);
2435 struct btrfs_device *device;
2440 device = btrfs_find_device(fs_info->fs_devices, &args);
2442 return ERR_PTR(-ENOENT);
2446 ret = btrfs_get_dev_args_from_path(fs_info, &args, device_path);
2448 return ERR_PTR(ret);
2449 device = btrfs_find_device(fs_info->fs_devices, &args);
2450 btrfs_put_dev_args_from_path(&args);
2452 return ERR_PTR(-ENOENT);
2456 static struct btrfs_fs_devices *btrfs_init_sprout(struct btrfs_fs_info *fs_info)
2458 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2459 struct btrfs_fs_devices *old_devices;
2460 struct btrfs_fs_devices *seed_devices;
2462 lockdep_assert_held(&uuid_mutex);
2463 if (!fs_devices->seeding)
2464 return ERR_PTR(-EINVAL);
2467 * Private copy of the seed devices, anchored at
2468 * fs_info->fs_devices->seed_list
2470 seed_devices = alloc_fs_devices(NULL);
2471 if (IS_ERR(seed_devices))
2472 return seed_devices;
2475 * It's necessary to retain a copy of the original seed fs_devices in
2476 * fs_uuids so that filesystems which have been seeded can successfully
2477 * reference the seed device from open_seed_devices. This also supports
2480 old_devices = clone_fs_devices(fs_devices);
2481 if (IS_ERR(old_devices)) {
2482 kfree(seed_devices);
2486 list_add(&old_devices->fs_list, &fs_uuids);
2488 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2489 seed_devices->opened = 1;
2490 INIT_LIST_HEAD(&seed_devices->devices);
2491 INIT_LIST_HEAD(&seed_devices->alloc_list);
2492 mutex_init(&seed_devices->device_list_mutex);
2494 return seed_devices;
2498 * Splice seed devices into the sprout fs_devices.
2499 * Generate a new fsid for the sprouted read-write filesystem.
2501 static void btrfs_setup_sprout(struct btrfs_fs_info *fs_info,
2502 struct btrfs_fs_devices *seed_devices)
2504 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2505 struct btrfs_super_block *disk_super = fs_info->super_copy;
2506 struct btrfs_device *device;
2510 * We are updating the fsid, the thread leading to device_list_add()
2511 * could race, so uuid_mutex is needed.
2513 lockdep_assert_held(&uuid_mutex);
2516 * The threads listed below may traverse dev_list but can do that without
2517 * device_list_mutex:
2518 * - All device ops and balance - as we are in btrfs_exclop_start.
2519 * - Various dev_list readers - are using RCU.
2520 * - btrfs_ioctl_fitrim() - is using RCU.
2522 * For-read threads as below are using device_list_mutex:
2523 * - Readonly scrub btrfs_scrub_dev()
2524 * - Readonly scrub btrfs_scrub_progress()
2525 * - btrfs_get_dev_stats()
2527 lockdep_assert_held(&fs_devices->device_list_mutex);
2529 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2531 list_for_each_entry(device, &seed_devices->devices, dev_list)
2532 device->fs_devices = seed_devices;
2534 fs_devices->seeding = false;
2535 fs_devices->num_devices = 0;
2536 fs_devices->open_devices = 0;
2537 fs_devices->missing_devices = 0;
2538 fs_devices->rotating = false;
2539 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2541 generate_random_uuid(fs_devices->fsid);
2542 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2543 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2545 super_flags = btrfs_super_flags(disk_super) &
2546 ~BTRFS_SUPER_FLAG_SEEDING;
2547 btrfs_set_super_flags(disk_super, super_flags);
2551 * Store the expected generation for seed devices in device items.
2553 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2555 BTRFS_DEV_LOOKUP_ARGS(args);
2556 struct btrfs_fs_info *fs_info = trans->fs_info;
2557 struct btrfs_root *root = fs_info->chunk_root;
2558 struct btrfs_path *path;
2559 struct extent_buffer *leaf;
2560 struct btrfs_dev_item *dev_item;
2561 struct btrfs_device *device;
2562 struct btrfs_key key;
2563 u8 fs_uuid[BTRFS_FSID_SIZE];
2564 u8 dev_uuid[BTRFS_UUID_SIZE];
2567 path = btrfs_alloc_path();
2571 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2573 key.type = BTRFS_DEV_ITEM_KEY;
2576 btrfs_reserve_chunk_metadata(trans, false);
2577 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2578 btrfs_trans_release_chunk_metadata(trans);
2582 leaf = path->nodes[0];
2584 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2585 ret = btrfs_next_leaf(root, path);
2590 leaf = path->nodes[0];
2591 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2592 btrfs_release_path(path);
2596 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2597 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2598 key.type != BTRFS_DEV_ITEM_KEY)
2601 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2602 struct btrfs_dev_item);
2603 args.devid = btrfs_device_id(leaf, dev_item);
2604 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2606 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2608 args.uuid = dev_uuid;
2609 args.fsid = fs_uuid;
2610 device = btrfs_find_device(fs_info->fs_devices, &args);
2611 BUG_ON(!device); /* Logic error */
2613 if (device->fs_devices->seeding) {
2614 btrfs_set_device_generation(leaf, dev_item,
2615 device->generation);
2616 btrfs_mark_buffer_dirty(trans, leaf);
2624 btrfs_free_path(path);
2628 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2630 struct btrfs_root *root = fs_info->dev_root;
2631 struct btrfs_trans_handle *trans;
2632 struct btrfs_device *device;
2633 struct bdev_handle *bdev_handle;
2634 struct super_block *sb = fs_info->sb;
2635 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2636 struct btrfs_fs_devices *seed_devices = NULL;
2637 u64 orig_super_total_bytes;
2638 u64 orig_super_num_devices;
2640 bool seeding_dev = false;
2641 bool locked = false;
2643 if (sb_rdonly(sb) && !fs_devices->seeding)
2646 bdev_handle = bdev_open_by_path(device_path, BLK_OPEN_WRITE,
2647 fs_info->bdev_holder, NULL);
2648 if (IS_ERR(bdev_handle))
2649 return PTR_ERR(bdev_handle);
2651 if (!btrfs_check_device_zone_type(fs_info, bdev_handle->bdev)) {
2656 if (fs_devices->seeding) {
2658 down_write(&sb->s_umount);
2659 mutex_lock(&uuid_mutex);
2663 sync_blockdev(bdev_handle->bdev);
2666 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2667 if (device->bdev == bdev_handle->bdev) {
2675 device = btrfs_alloc_device(fs_info, NULL, NULL, device_path);
2676 if (IS_ERR(device)) {
2677 /* we can safely leave the fs_devices entry around */
2678 ret = PTR_ERR(device);
2682 device->fs_info = fs_info;
2683 device->bdev_handle = bdev_handle;
2684 device->bdev = bdev_handle->bdev;
2685 ret = lookup_bdev(device_path, &device->devt);
2687 goto error_free_device;
2689 ret = btrfs_get_dev_zone_info(device, false);
2691 goto error_free_device;
2693 trans = btrfs_start_transaction(root, 0);
2694 if (IS_ERR(trans)) {
2695 ret = PTR_ERR(trans);
2696 goto error_free_zone;
2699 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2700 device->generation = trans->transid;
2701 device->io_width = fs_info->sectorsize;
2702 device->io_align = fs_info->sectorsize;
2703 device->sector_size = fs_info->sectorsize;
2704 device->total_bytes =
2705 round_down(bdev_nr_bytes(device->bdev), fs_info->sectorsize);
2706 device->disk_total_bytes = device->total_bytes;
2707 device->commit_total_bytes = device->total_bytes;
2708 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2709 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2710 device->dev_stats_valid = 1;
2711 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2714 btrfs_clear_sb_rdonly(sb);
2716 /* GFP_KERNEL allocation must not be under device_list_mutex */
2717 seed_devices = btrfs_init_sprout(fs_info);
2718 if (IS_ERR(seed_devices)) {
2719 ret = PTR_ERR(seed_devices);
2720 btrfs_abort_transaction(trans, ret);
2725 mutex_lock(&fs_devices->device_list_mutex);
2727 btrfs_setup_sprout(fs_info, seed_devices);
2728 btrfs_assign_next_active_device(fs_info->fs_devices->latest_dev,
2732 device->fs_devices = fs_devices;
2734 mutex_lock(&fs_info->chunk_mutex);
2735 list_add_rcu(&device->dev_list, &fs_devices->devices);
2736 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2737 fs_devices->num_devices++;
2738 fs_devices->open_devices++;
2739 fs_devices->rw_devices++;
2740 fs_devices->total_devices++;
2741 fs_devices->total_rw_bytes += device->total_bytes;
2743 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2745 if (!bdev_nonrot(device->bdev))
2746 fs_devices->rotating = true;
2748 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2749 btrfs_set_super_total_bytes(fs_info->super_copy,
2750 round_down(orig_super_total_bytes + device->total_bytes,
2751 fs_info->sectorsize));
2753 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2754 btrfs_set_super_num_devices(fs_info->super_copy,
2755 orig_super_num_devices + 1);
2758 * we've got more storage, clear any full flags on the space
2761 btrfs_clear_space_info_full(fs_info);
2763 mutex_unlock(&fs_info->chunk_mutex);
2765 /* Add sysfs device entry */
2766 btrfs_sysfs_add_device(device);
2768 mutex_unlock(&fs_devices->device_list_mutex);
2771 mutex_lock(&fs_info->chunk_mutex);
2772 ret = init_first_rw_device(trans);
2773 mutex_unlock(&fs_info->chunk_mutex);
2775 btrfs_abort_transaction(trans, ret);
2780 ret = btrfs_add_dev_item(trans, device);
2782 btrfs_abort_transaction(trans, ret);
2787 ret = btrfs_finish_sprout(trans);
2789 btrfs_abort_transaction(trans, ret);
2794 * fs_devices now represents the newly sprouted filesystem and
2795 * its fsid has been changed by btrfs_sprout_splice().
2797 btrfs_sysfs_update_sprout_fsid(fs_devices);
2800 ret = btrfs_commit_transaction(trans);
2803 mutex_unlock(&uuid_mutex);
2804 up_write(&sb->s_umount);
2807 if (ret) /* transaction commit */
2810 ret = btrfs_relocate_sys_chunks(fs_info);
2812 btrfs_handle_fs_error(fs_info, ret,
2813 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2814 trans = btrfs_attach_transaction(root);
2815 if (IS_ERR(trans)) {
2816 if (PTR_ERR(trans) == -ENOENT)
2818 ret = PTR_ERR(trans);
2822 ret = btrfs_commit_transaction(trans);
2826 * Now that we have written a new super block to this device, check all
2827 * other fs_devices list if device_path alienates any other scanned
2829 * We can ignore the return value as it typically returns -EINVAL and
2830 * only succeeds if the device was an alien.
2832 btrfs_forget_devices(device->devt);
2834 /* Update ctime/mtime for blkid or udev */
2835 update_dev_time(device_path);
2840 btrfs_sysfs_remove_device(device);
2841 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2842 mutex_lock(&fs_info->chunk_mutex);
2843 list_del_rcu(&device->dev_list);
2844 list_del(&device->dev_alloc_list);
2845 fs_info->fs_devices->num_devices--;
2846 fs_info->fs_devices->open_devices--;
2847 fs_info->fs_devices->rw_devices--;
2848 fs_info->fs_devices->total_devices--;
2849 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2850 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2851 btrfs_set_super_total_bytes(fs_info->super_copy,
2852 orig_super_total_bytes);
2853 btrfs_set_super_num_devices(fs_info->super_copy,
2854 orig_super_num_devices);
2855 mutex_unlock(&fs_info->chunk_mutex);
2856 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2859 btrfs_set_sb_rdonly(sb);
2861 btrfs_end_transaction(trans);
2863 btrfs_destroy_dev_zone_info(device);
2865 btrfs_free_device(device);
2867 bdev_release(bdev_handle);
2869 mutex_unlock(&uuid_mutex);
2870 up_write(&sb->s_umount);
2875 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2876 struct btrfs_device *device)
2879 struct btrfs_path *path;
2880 struct btrfs_root *root = device->fs_info->chunk_root;
2881 struct btrfs_dev_item *dev_item;
2882 struct extent_buffer *leaf;
2883 struct btrfs_key key;
2885 path = btrfs_alloc_path();
2889 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2890 key.type = BTRFS_DEV_ITEM_KEY;
2891 key.offset = device->devid;
2893 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2902 leaf = path->nodes[0];
2903 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2905 btrfs_set_device_id(leaf, dev_item, device->devid);
2906 btrfs_set_device_type(leaf, dev_item, device->type);
2907 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2908 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2909 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2910 btrfs_set_device_total_bytes(leaf, dev_item,
2911 btrfs_device_get_disk_total_bytes(device));
2912 btrfs_set_device_bytes_used(leaf, dev_item,
2913 btrfs_device_get_bytes_used(device));
2914 btrfs_mark_buffer_dirty(trans, leaf);
2917 btrfs_free_path(path);
2921 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2922 struct btrfs_device *device, u64 new_size)
2924 struct btrfs_fs_info *fs_info = device->fs_info;
2925 struct btrfs_super_block *super_copy = fs_info->super_copy;
2930 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2933 new_size = round_down(new_size, fs_info->sectorsize);
2935 mutex_lock(&fs_info->chunk_mutex);
2936 old_total = btrfs_super_total_bytes(super_copy);
2937 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2939 if (new_size <= device->total_bytes ||
2940 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2941 mutex_unlock(&fs_info->chunk_mutex);
2945 btrfs_set_super_total_bytes(super_copy,
2946 round_down(old_total + diff, fs_info->sectorsize));
2947 device->fs_devices->total_rw_bytes += diff;
2948 atomic64_add(diff, &fs_info->free_chunk_space);
2950 btrfs_device_set_total_bytes(device, new_size);
2951 btrfs_device_set_disk_total_bytes(device, new_size);
2952 btrfs_clear_space_info_full(device->fs_info);
2953 if (list_empty(&device->post_commit_list))
2954 list_add_tail(&device->post_commit_list,
2955 &trans->transaction->dev_update_list);
2956 mutex_unlock(&fs_info->chunk_mutex);
2958 btrfs_reserve_chunk_metadata(trans, false);
2959 ret = btrfs_update_device(trans, device);
2960 btrfs_trans_release_chunk_metadata(trans);
2965 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2967 struct btrfs_fs_info *fs_info = trans->fs_info;
2968 struct btrfs_root *root = fs_info->chunk_root;
2970 struct btrfs_path *path;
2971 struct btrfs_key key;
2973 path = btrfs_alloc_path();
2977 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2978 key.offset = chunk_offset;
2979 key.type = BTRFS_CHUNK_ITEM_KEY;
2981 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2984 else if (ret > 0) { /* Logic error or corruption */
2985 btrfs_handle_fs_error(fs_info, -ENOENT,
2986 "Failed lookup while freeing chunk.");
2991 ret = btrfs_del_item(trans, root, path);
2993 btrfs_handle_fs_error(fs_info, ret,
2994 "Failed to delete chunk item.");
2996 btrfs_free_path(path);
3000 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3002 struct btrfs_super_block *super_copy = fs_info->super_copy;
3003 struct btrfs_disk_key *disk_key;
3004 struct btrfs_chunk *chunk;
3011 struct btrfs_key key;
3013 lockdep_assert_held(&fs_info->chunk_mutex);
3014 array_size = btrfs_super_sys_array_size(super_copy);
3016 ptr = super_copy->sys_chunk_array;
3019 while (cur < array_size) {
3020 disk_key = (struct btrfs_disk_key *)ptr;
3021 btrfs_disk_key_to_cpu(&key, disk_key);
3023 len = sizeof(*disk_key);
3025 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3026 chunk = (struct btrfs_chunk *)(ptr + len);
3027 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
3028 len += btrfs_chunk_item_size(num_stripes);
3033 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
3034 key.offset == chunk_offset) {
3035 memmove(ptr, ptr + len, array_size - (cur + len));
3037 btrfs_set_super_sys_array_size(super_copy, array_size);
3046 struct btrfs_chunk_map *btrfs_find_chunk_map_nolock(struct btrfs_fs_info *fs_info,
3047 u64 logical, u64 length)
3049 struct rb_node *node = fs_info->mapping_tree.rb_root.rb_node;
3050 struct rb_node *prev = NULL;
3051 struct rb_node *orig_prev;
3052 struct btrfs_chunk_map *map;
3053 struct btrfs_chunk_map *prev_map = NULL;
3056 map = rb_entry(node, struct btrfs_chunk_map, rb_node);
3060 if (logical < map->start) {
3061 node = node->rb_left;
3062 } else if (logical >= map->start + map->chunk_len) {
3063 node = node->rb_right;
3065 refcount_inc(&map->refs);
3074 while (prev && logical >= prev_map->start + prev_map->chunk_len) {
3075 prev = rb_next(prev);
3076 prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3081 prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3082 while (prev && logical < prev_map->start) {
3083 prev = rb_prev(prev);
3084 prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3089 u64 end = logical + length;
3092 * Caller can pass a U64_MAX length when it wants to get any
3093 * chunk starting at an offset of 'logical' or higher, so deal
3094 * with underflow by resetting the end offset to U64_MAX.
3099 if (end > prev_map->start &&
3100 logical < prev_map->start + prev_map->chunk_len) {
3101 refcount_inc(&prev_map->refs);
3109 struct btrfs_chunk_map *btrfs_find_chunk_map(struct btrfs_fs_info *fs_info,
3110 u64 logical, u64 length)
3112 struct btrfs_chunk_map *map;
3114 read_lock(&fs_info->mapping_tree_lock);
3115 map = btrfs_find_chunk_map_nolock(fs_info, logical, length);
3116 read_unlock(&fs_info->mapping_tree_lock);
3122 * Find the mapping containing the given logical extent.
3124 * @logical: Logical block offset in bytes.
3125 * @length: Length of extent in bytes.
3127 * Return: Chunk mapping or ERR_PTR.
3129 struct btrfs_chunk_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
3130 u64 logical, u64 length)
3132 struct btrfs_chunk_map *map;
3134 map = btrfs_find_chunk_map(fs_info, logical, length);
3136 if (unlikely(!map)) {
3138 "unable to find chunk map for logical %llu length %llu",
3140 return ERR_PTR(-EINVAL);
3143 if (unlikely(map->start > logical || map->start + map->chunk_len <= logical)) {
3145 "found a bad chunk map, wanted %llu-%llu, found %llu-%llu",
3146 logical, logical + length, map->start,
3147 map->start + map->chunk_len);
3148 btrfs_free_chunk_map(map);
3149 return ERR_PTR(-EINVAL);
3152 /* Callers are responsible for dropping the reference. */
3156 static int remove_chunk_item(struct btrfs_trans_handle *trans,
3157 struct btrfs_chunk_map *map, u64 chunk_offset)
3162 * Removing chunk items and updating the device items in the chunks btree
3163 * requires holding the chunk_mutex.
3164 * See the comment at btrfs_chunk_alloc() for the details.
3166 lockdep_assert_held(&trans->fs_info->chunk_mutex);
3168 for (i = 0; i < map->num_stripes; i++) {
3171 ret = btrfs_update_device(trans, map->stripes[i].dev);
3176 return btrfs_free_chunk(trans, chunk_offset);
3179 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3181 struct btrfs_fs_info *fs_info = trans->fs_info;
3182 struct btrfs_chunk_map *map;
3183 u64 dev_extent_len = 0;
3185 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3187 map = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3190 * This is a logic error, but we don't want to just rely on the
3191 * user having built with ASSERT enabled, so if ASSERT doesn't
3192 * do anything we still error out.
3195 return PTR_ERR(map);
3199 * First delete the device extent items from the devices btree.
3200 * We take the device_list_mutex to avoid racing with the finishing phase
3201 * of a device replace operation. See the comment below before acquiring
3202 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3203 * because that can result in a deadlock when deleting the device extent
3204 * items from the devices btree - COWing an extent buffer from the btree
3205 * may result in allocating a new metadata chunk, which would attempt to
3206 * lock again fs_info->chunk_mutex.
3208 mutex_lock(&fs_devices->device_list_mutex);
3209 for (i = 0; i < map->num_stripes; i++) {
3210 struct btrfs_device *device = map->stripes[i].dev;
3211 ret = btrfs_free_dev_extent(trans, device,
3212 map->stripes[i].physical,
3215 mutex_unlock(&fs_devices->device_list_mutex);
3216 btrfs_abort_transaction(trans, ret);
3220 if (device->bytes_used > 0) {
3221 mutex_lock(&fs_info->chunk_mutex);
3222 btrfs_device_set_bytes_used(device,
3223 device->bytes_used - dev_extent_len);
3224 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3225 btrfs_clear_space_info_full(fs_info);
3226 mutex_unlock(&fs_info->chunk_mutex);
3229 mutex_unlock(&fs_devices->device_list_mutex);
3232 * We acquire fs_info->chunk_mutex for 2 reasons:
3234 * 1) Just like with the first phase of the chunk allocation, we must
3235 * reserve system space, do all chunk btree updates and deletions, and
3236 * update the system chunk array in the superblock while holding this
3237 * mutex. This is for similar reasons as explained on the comment at
3238 * the top of btrfs_chunk_alloc();
3240 * 2) Prevent races with the final phase of a device replace operation
3241 * that replaces the device object associated with the map's stripes,
3242 * because the device object's id can change at any time during that
3243 * final phase of the device replace operation
3244 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3245 * replaced device and then see it with an ID of
3246 * BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3247 * the device item, which does not exists on the chunk btree.
3248 * The finishing phase of device replace acquires both the
3249 * device_list_mutex and the chunk_mutex, in that order, so we are
3250 * safe by just acquiring the chunk_mutex.
3252 trans->removing_chunk = true;
3253 mutex_lock(&fs_info->chunk_mutex);
3255 check_system_chunk(trans, map->type);
3257 ret = remove_chunk_item(trans, map, chunk_offset);
3259 * Normally we should not get -ENOSPC since we reserved space before
3260 * through the call to check_system_chunk().
3262 * Despite our system space_info having enough free space, we may not
3263 * be able to allocate extents from its block groups, because all have
3264 * an incompatible profile, which will force us to allocate a new system
3265 * block group with the right profile, or right after we called
3266 * check_system_space() above, a scrub turned the only system block group
3267 * with enough free space into RO mode.
3268 * This is explained with more detail at do_chunk_alloc().
3270 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3272 if (ret == -ENOSPC) {
3273 const u64 sys_flags = btrfs_system_alloc_profile(fs_info);
3274 struct btrfs_block_group *sys_bg;
3276 sys_bg = btrfs_create_chunk(trans, sys_flags);
3277 if (IS_ERR(sys_bg)) {
3278 ret = PTR_ERR(sys_bg);
3279 btrfs_abort_transaction(trans, ret);
3283 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3285 btrfs_abort_transaction(trans, ret);
3289 ret = remove_chunk_item(trans, map, chunk_offset);
3291 btrfs_abort_transaction(trans, ret);
3295 btrfs_abort_transaction(trans, ret);
3299 trace_btrfs_chunk_free(fs_info, map, chunk_offset, map->chunk_len);
3301 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3302 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3304 btrfs_abort_transaction(trans, ret);
3309 mutex_unlock(&fs_info->chunk_mutex);
3310 trans->removing_chunk = false;
3313 * We are done with chunk btree updates and deletions, so release the
3314 * system space we previously reserved (with check_system_chunk()).
3316 btrfs_trans_release_chunk_metadata(trans);
3318 ret = btrfs_remove_block_group(trans, map);
3320 btrfs_abort_transaction(trans, ret);
3325 if (trans->removing_chunk) {
3326 mutex_unlock(&fs_info->chunk_mutex);
3327 trans->removing_chunk = false;
3330 btrfs_free_chunk_map(map);
3334 int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3336 struct btrfs_root *root = fs_info->chunk_root;
3337 struct btrfs_trans_handle *trans;
3338 struct btrfs_block_group *block_group;
3342 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3344 "relocate: not supported on extent tree v2 yet");
3349 * Prevent races with automatic removal of unused block groups.
3350 * After we relocate and before we remove the chunk with offset
3351 * chunk_offset, automatic removal of the block group can kick in,
3352 * resulting in a failure when calling btrfs_remove_chunk() below.
3354 * Make sure to acquire this mutex before doing a tree search (dev
3355 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3356 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3357 * we release the path used to search the chunk/dev tree and before
3358 * the current task acquires this mutex and calls us.
3360 lockdep_assert_held(&fs_info->reclaim_bgs_lock);
3362 /* step one, relocate all the extents inside this chunk */
3363 btrfs_scrub_pause(fs_info);
3364 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3365 btrfs_scrub_continue(fs_info);
3368 * If we had a transaction abort, stop all running scrubs.
3369 * See transaction.c:cleanup_transaction() why we do it here.
3371 if (BTRFS_FS_ERROR(fs_info))
3372 btrfs_scrub_cancel(fs_info);
3376 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3379 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3380 length = block_group->length;
3381 btrfs_put_block_group(block_group);
3384 * On a zoned file system, discard the whole block group, this will
3385 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3386 * resetting the zone fails, don't treat it as a fatal problem from the
3387 * filesystem's point of view.
3389 if (btrfs_is_zoned(fs_info)) {
3390 ret = btrfs_discard_extent(fs_info, chunk_offset, length, NULL);
3393 "failed to reset zone %llu after relocation",
3397 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3399 if (IS_ERR(trans)) {
3400 ret = PTR_ERR(trans);
3401 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3406 * step two, delete the device extents and the
3407 * chunk tree entries
3409 ret = btrfs_remove_chunk(trans, chunk_offset);
3410 btrfs_end_transaction(trans);
3414 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3416 struct btrfs_root *chunk_root = fs_info->chunk_root;
3417 struct btrfs_path *path;
3418 struct extent_buffer *leaf;
3419 struct btrfs_chunk *chunk;
3420 struct btrfs_key key;
3421 struct btrfs_key found_key;
3423 bool retried = false;
3427 path = btrfs_alloc_path();
3432 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3433 key.offset = (u64)-1;
3434 key.type = BTRFS_CHUNK_ITEM_KEY;
3437 mutex_lock(&fs_info->reclaim_bgs_lock);
3438 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3440 mutex_unlock(&fs_info->reclaim_bgs_lock);
3445 * On the first search we would find chunk tree with
3446 * offset -1, which is not possible. On subsequent
3447 * loops this would find an existing item on an invalid
3448 * offset (one less than the previous one, wrong
3449 * alignment and size).
3455 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3458 mutex_unlock(&fs_info->reclaim_bgs_lock);
3464 leaf = path->nodes[0];
3465 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3467 chunk = btrfs_item_ptr(leaf, path->slots[0],
3468 struct btrfs_chunk);
3469 chunk_type = btrfs_chunk_type(leaf, chunk);
3470 btrfs_release_path(path);
3472 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3473 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3479 mutex_unlock(&fs_info->reclaim_bgs_lock);
3481 if (found_key.offset == 0)
3483 key.offset = found_key.offset - 1;
3486 if (failed && !retried) {
3490 } else if (WARN_ON(failed && retried)) {
3494 btrfs_free_path(path);
3499 * return 1 : allocate a data chunk successfully,
3500 * return <0: errors during allocating a data chunk,
3501 * return 0 : no need to allocate a data chunk.
3503 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3506 struct btrfs_block_group *cache;
3510 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3512 chunk_type = cache->flags;
3513 btrfs_put_block_group(cache);
3515 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3518 spin_lock(&fs_info->data_sinfo->lock);
3519 bytes_used = fs_info->data_sinfo->bytes_used;
3520 spin_unlock(&fs_info->data_sinfo->lock);
3523 struct btrfs_trans_handle *trans;
3526 trans = btrfs_join_transaction(fs_info->tree_root);
3528 return PTR_ERR(trans);
3530 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3531 btrfs_end_transaction(trans);
3540 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3541 struct btrfs_balance_control *bctl)
3543 struct btrfs_root *root = fs_info->tree_root;
3544 struct btrfs_trans_handle *trans;
3545 struct btrfs_balance_item *item;
3546 struct btrfs_disk_balance_args disk_bargs;
3547 struct btrfs_path *path;
3548 struct extent_buffer *leaf;
3549 struct btrfs_key key;
3552 path = btrfs_alloc_path();
3556 trans = btrfs_start_transaction(root, 0);
3557 if (IS_ERR(trans)) {
3558 btrfs_free_path(path);
3559 return PTR_ERR(trans);
3562 key.objectid = BTRFS_BALANCE_OBJECTID;
3563 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3566 ret = btrfs_insert_empty_item(trans, root, path, &key,
3571 leaf = path->nodes[0];
3572 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3574 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3576 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3577 btrfs_set_balance_data(leaf, item, &disk_bargs);
3578 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3579 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3580 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3581 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3583 btrfs_set_balance_flags(leaf, item, bctl->flags);
3585 btrfs_mark_buffer_dirty(trans, leaf);
3587 btrfs_free_path(path);
3588 err = btrfs_commit_transaction(trans);
3594 static int del_balance_item(struct btrfs_fs_info *fs_info)
3596 struct btrfs_root *root = fs_info->tree_root;
3597 struct btrfs_trans_handle *trans;
3598 struct btrfs_path *path;
3599 struct btrfs_key key;
3602 path = btrfs_alloc_path();
3606 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3607 if (IS_ERR(trans)) {
3608 btrfs_free_path(path);
3609 return PTR_ERR(trans);
3612 key.objectid = BTRFS_BALANCE_OBJECTID;
3613 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3616 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3624 ret = btrfs_del_item(trans, root, path);
3626 btrfs_free_path(path);
3627 err = btrfs_commit_transaction(trans);
3634 * This is a heuristic used to reduce the number of chunks balanced on
3635 * resume after balance was interrupted.
3637 static void update_balance_args(struct btrfs_balance_control *bctl)
3640 * Turn on soft mode for chunk types that were being converted.
3642 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3643 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3644 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3645 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3646 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3647 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3650 * Turn on usage filter if is not already used. The idea is
3651 * that chunks that we have already balanced should be
3652 * reasonably full. Don't do it for chunks that are being
3653 * converted - that will keep us from relocating unconverted
3654 * (albeit full) chunks.
3656 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3657 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3658 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3659 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3660 bctl->data.usage = 90;
3662 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3663 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3664 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3665 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3666 bctl->sys.usage = 90;
3668 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3669 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3670 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3671 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3672 bctl->meta.usage = 90;
3677 * Clear the balance status in fs_info and delete the balance item from disk.
3679 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3681 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3684 BUG_ON(!fs_info->balance_ctl);
3686 spin_lock(&fs_info->balance_lock);
3687 fs_info->balance_ctl = NULL;
3688 spin_unlock(&fs_info->balance_lock);
3691 ret = del_balance_item(fs_info);
3693 btrfs_handle_fs_error(fs_info, ret, NULL);
3697 * Balance filters. Return 1 if chunk should be filtered out
3698 * (should not be balanced).
3700 static int chunk_profiles_filter(u64 chunk_type,
3701 struct btrfs_balance_args *bargs)
3703 chunk_type = chunk_to_extended(chunk_type) &
3704 BTRFS_EXTENDED_PROFILE_MASK;
3706 if (bargs->profiles & chunk_type)
3712 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3713 struct btrfs_balance_args *bargs)
3715 struct btrfs_block_group *cache;
3717 u64 user_thresh_min;
3718 u64 user_thresh_max;
3721 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3722 chunk_used = cache->used;
3724 if (bargs->usage_min == 0)
3725 user_thresh_min = 0;
3727 user_thresh_min = mult_perc(cache->length, bargs->usage_min);
3729 if (bargs->usage_max == 0)
3730 user_thresh_max = 1;
3731 else if (bargs->usage_max > 100)
3732 user_thresh_max = cache->length;
3734 user_thresh_max = mult_perc(cache->length, bargs->usage_max);
3736 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3739 btrfs_put_block_group(cache);
3743 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3744 u64 chunk_offset, struct btrfs_balance_args *bargs)
3746 struct btrfs_block_group *cache;
3747 u64 chunk_used, user_thresh;
3750 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3751 chunk_used = cache->used;
3753 if (bargs->usage_min == 0)
3755 else if (bargs->usage > 100)
3756 user_thresh = cache->length;
3758 user_thresh = mult_perc(cache->length, bargs->usage);
3760 if (chunk_used < user_thresh)
3763 btrfs_put_block_group(cache);
3767 static int chunk_devid_filter(struct extent_buffer *leaf,
3768 struct btrfs_chunk *chunk,
3769 struct btrfs_balance_args *bargs)
3771 struct btrfs_stripe *stripe;
3772 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3775 for (i = 0; i < num_stripes; i++) {
3776 stripe = btrfs_stripe_nr(chunk, i);
3777 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3784 static u64 calc_data_stripes(u64 type, int num_stripes)
3786 const int index = btrfs_bg_flags_to_raid_index(type);
3787 const int ncopies = btrfs_raid_array[index].ncopies;
3788 const int nparity = btrfs_raid_array[index].nparity;
3790 return (num_stripes - nparity) / ncopies;
3793 /* [pstart, pend) */
3794 static int chunk_drange_filter(struct extent_buffer *leaf,
3795 struct btrfs_chunk *chunk,
3796 struct btrfs_balance_args *bargs)
3798 struct btrfs_stripe *stripe;
3799 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3806 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3809 type = btrfs_chunk_type(leaf, chunk);
3810 factor = calc_data_stripes(type, num_stripes);
3812 for (i = 0; i < num_stripes; i++) {
3813 stripe = btrfs_stripe_nr(chunk, i);
3814 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3817 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3818 stripe_length = btrfs_chunk_length(leaf, chunk);
3819 stripe_length = div_u64(stripe_length, factor);
3821 if (stripe_offset < bargs->pend &&
3822 stripe_offset + stripe_length > bargs->pstart)
3829 /* [vstart, vend) */
3830 static int chunk_vrange_filter(struct extent_buffer *leaf,
3831 struct btrfs_chunk *chunk,
3833 struct btrfs_balance_args *bargs)
3835 if (chunk_offset < bargs->vend &&
3836 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3837 /* at least part of the chunk is inside this vrange */
3843 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3844 struct btrfs_chunk *chunk,
3845 struct btrfs_balance_args *bargs)
3847 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3849 if (bargs->stripes_min <= num_stripes
3850 && num_stripes <= bargs->stripes_max)
3856 static int chunk_soft_convert_filter(u64 chunk_type,
3857 struct btrfs_balance_args *bargs)
3859 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3862 chunk_type = chunk_to_extended(chunk_type) &
3863 BTRFS_EXTENDED_PROFILE_MASK;
3865 if (bargs->target == chunk_type)
3871 static int should_balance_chunk(struct extent_buffer *leaf,
3872 struct btrfs_chunk *chunk, u64 chunk_offset)
3874 struct btrfs_fs_info *fs_info = leaf->fs_info;
3875 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3876 struct btrfs_balance_args *bargs = NULL;
3877 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3880 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3881 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3885 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3886 bargs = &bctl->data;
3887 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3889 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3890 bargs = &bctl->meta;
3892 /* profiles filter */
3893 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3894 chunk_profiles_filter(chunk_type, bargs)) {
3899 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3900 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3902 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3903 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3908 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3909 chunk_devid_filter(leaf, chunk, bargs)) {
3913 /* drange filter, makes sense only with devid filter */
3914 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3915 chunk_drange_filter(leaf, chunk, bargs)) {
3920 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3921 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3925 /* stripes filter */
3926 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3927 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3931 /* soft profile changing mode */
3932 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3933 chunk_soft_convert_filter(chunk_type, bargs)) {
3938 * limited by count, must be the last filter
3940 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3941 if (bargs->limit == 0)
3945 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3947 * Same logic as the 'limit' filter; the minimum cannot be
3948 * determined here because we do not have the global information
3949 * about the count of all chunks that satisfy the filters.
3951 if (bargs->limit_max == 0)
3960 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3962 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3963 struct btrfs_root *chunk_root = fs_info->chunk_root;
3965 struct btrfs_chunk *chunk;
3966 struct btrfs_path *path = NULL;
3967 struct btrfs_key key;
3968 struct btrfs_key found_key;
3969 struct extent_buffer *leaf;
3972 int enospc_errors = 0;
3973 bool counting = true;
3974 /* The single value limit and min/max limits use the same bytes in the */
3975 u64 limit_data = bctl->data.limit;
3976 u64 limit_meta = bctl->meta.limit;
3977 u64 limit_sys = bctl->sys.limit;
3981 int chunk_reserved = 0;
3983 path = btrfs_alloc_path();
3989 /* zero out stat counters */
3990 spin_lock(&fs_info->balance_lock);
3991 memset(&bctl->stat, 0, sizeof(bctl->stat));
3992 spin_unlock(&fs_info->balance_lock);
3996 * The single value limit and min/max limits use the same bytes
3999 bctl->data.limit = limit_data;
4000 bctl->meta.limit = limit_meta;
4001 bctl->sys.limit = limit_sys;
4003 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4004 key.offset = (u64)-1;
4005 key.type = BTRFS_CHUNK_ITEM_KEY;
4008 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
4009 atomic_read(&fs_info->balance_cancel_req)) {
4014 mutex_lock(&fs_info->reclaim_bgs_lock);
4015 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
4017 mutex_unlock(&fs_info->reclaim_bgs_lock);
4022 * this shouldn't happen, it means the last relocate
4026 BUG(); /* FIXME break ? */
4028 ret = btrfs_previous_item(chunk_root, path, 0,
4029 BTRFS_CHUNK_ITEM_KEY);
4031 mutex_unlock(&fs_info->reclaim_bgs_lock);
4036 leaf = path->nodes[0];
4037 slot = path->slots[0];
4038 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4040 if (found_key.objectid != key.objectid) {
4041 mutex_unlock(&fs_info->reclaim_bgs_lock);
4045 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4046 chunk_type = btrfs_chunk_type(leaf, chunk);
4049 spin_lock(&fs_info->balance_lock);
4050 bctl->stat.considered++;
4051 spin_unlock(&fs_info->balance_lock);
4054 ret = should_balance_chunk(leaf, chunk, found_key.offset);
4056 btrfs_release_path(path);
4058 mutex_unlock(&fs_info->reclaim_bgs_lock);
4063 mutex_unlock(&fs_info->reclaim_bgs_lock);
4064 spin_lock(&fs_info->balance_lock);
4065 bctl->stat.expected++;
4066 spin_unlock(&fs_info->balance_lock);
4068 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
4070 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
4072 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
4079 * Apply limit_min filter, no need to check if the LIMITS
4080 * filter is used, limit_min is 0 by default
4082 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
4083 count_data < bctl->data.limit_min)
4084 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
4085 count_meta < bctl->meta.limit_min)
4086 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
4087 count_sys < bctl->sys.limit_min)) {
4088 mutex_unlock(&fs_info->reclaim_bgs_lock);
4092 if (!chunk_reserved) {
4094 * We may be relocating the only data chunk we have,
4095 * which could potentially end up with losing data's
4096 * raid profile, so lets allocate an empty one in
4099 ret = btrfs_may_alloc_data_chunk(fs_info,
4102 mutex_unlock(&fs_info->reclaim_bgs_lock);
4104 } else if (ret == 1) {
4109 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
4110 mutex_unlock(&fs_info->reclaim_bgs_lock);
4111 if (ret == -ENOSPC) {
4113 } else if (ret == -ETXTBSY) {
4115 "skipping relocation of block group %llu due to active swapfile",
4121 spin_lock(&fs_info->balance_lock);
4122 bctl->stat.completed++;
4123 spin_unlock(&fs_info->balance_lock);
4126 if (found_key.offset == 0)
4128 key.offset = found_key.offset - 1;
4132 btrfs_release_path(path);
4137 btrfs_free_path(path);
4138 if (enospc_errors) {
4139 btrfs_info(fs_info, "%d enospc errors during balance",
4149 * See if a given profile is valid and reduced.
4151 * @flags: profile to validate
4152 * @extended: if true @flags is treated as an extended profile
4154 static int alloc_profile_is_valid(u64 flags, int extended)
4156 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
4157 BTRFS_BLOCK_GROUP_PROFILE_MASK);
4159 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
4161 /* 1) check that all other bits are zeroed */
4165 /* 2) see if profile is reduced */
4167 return !extended; /* "0" is valid for usual profiles */
4169 return has_single_bit_set(flags);
4173 * Validate target profile against allowed profiles and return true if it's OK.
4174 * Otherwise print the error message and return false.
4176 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
4177 const struct btrfs_balance_args *bargs,
4178 u64 allowed, const char *type)
4180 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4183 /* Profile is valid and does not have bits outside of the allowed set */
4184 if (alloc_profile_is_valid(bargs->target, 1) &&
4185 (bargs->target & ~allowed) == 0)
4188 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
4189 type, btrfs_bg_type_to_raid_name(bargs->target));
4194 * Fill @buf with textual description of balance filter flags @bargs, up to
4195 * @size_buf including the terminating null. The output may be trimmed if it
4196 * does not fit into the provided buffer.
4198 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4202 u32 size_bp = size_buf;
4204 u64 flags = bargs->flags;
4205 char tmp_buf[128] = {'\0'};
4210 #define CHECK_APPEND_NOARG(a) \
4212 ret = snprintf(bp, size_bp, (a)); \
4213 if (ret < 0 || ret >= size_bp) \
4214 goto out_overflow; \
4219 #define CHECK_APPEND_1ARG(a, v1) \
4221 ret = snprintf(bp, size_bp, (a), (v1)); \
4222 if (ret < 0 || ret >= size_bp) \
4223 goto out_overflow; \
4228 #define CHECK_APPEND_2ARG(a, v1, v2) \
4230 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
4231 if (ret < 0 || ret >= size_bp) \
4232 goto out_overflow; \
4237 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4238 CHECK_APPEND_1ARG("convert=%s,",
4239 btrfs_bg_type_to_raid_name(bargs->target));
4241 if (flags & BTRFS_BALANCE_ARGS_SOFT)
4242 CHECK_APPEND_NOARG("soft,");
4244 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4245 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4247 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4250 if (flags & BTRFS_BALANCE_ARGS_USAGE)
4251 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4253 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4254 CHECK_APPEND_2ARG("usage=%u..%u,",
4255 bargs->usage_min, bargs->usage_max);
4257 if (flags & BTRFS_BALANCE_ARGS_DEVID)
4258 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4260 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4261 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4262 bargs->pstart, bargs->pend);
4264 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4265 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4266 bargs->vstart, bargs->vend);
4268 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4269 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4271 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4272 CHECK_APPEND_2ARG("limit=%u..%u,",
4273 bargs->limit_min, bargs->limit_max);
4275 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4276 CHECK_APPEND_2ARG("stripes=%u..%u,",
4277 bargs->stripes_min, bargs->stripes_max);
4279 #undef CHECK_APPEND_2ARG
4280 #undef CHECK_APPEND_1ARG
4281 #undef CHECK_APPEND_NOARG
4285 if (size_bp < size_buf)
4286 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4291 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4293 u32 size_buf = 1024;
4294 char tmp_buf[192] = {'\0'};
4297 u32 size_bp = size_buf;
4299 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4301 buf = kzalloc(size_buf, GFP_KERNEL);
4307 #define CHECK_APPEND_1ARG(a, v1) \
4309 ret = snprintf(bp, size_bp, (a), (v1)); \
4310 if (ret < 0 || ret >= size_bp) \
4311 goto out_overflow; \
4316 if (bctl->flags & BTRFS_BALANCE_FORCE)
4317 CHECK_APPEND_1ARG("%s", "-f ");
4319 if (bctl->flags & BTRFS_BALANCE_DATA) {
4320 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4321 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4324 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4325 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4326 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4329 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4330 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4331 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4334 #undef CHECK_APPEND_1ARG
4338 if (size_bp < size_buf)
4339 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4340 btrfs_info(fs_info, "balance: %s %s",
4341 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4342 "resume" : "start", buf);
4348 * Should be called with balance mutexe held
4350 int btrfs_balance(struct btrfs_fs_info *fs_info,
4351 struct btrfs_balance_control *bctl,
4352 struct btrfs_ioctl_balance_args *bargs)
4354 u64 meta_target, data_target;
4360 bool reducing_redundancy;
4361 bool paused = false;
4364 if (btrfs_fs_closing(fs_info) ||
4365 atomic_read(&fs_info->balance_pause_req) ||
4366 btrfs_should_cancel_balance(fs_info)) {
4371 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4372 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4376 * In case of mixed groups both data and meta should be picked,
4377 * and identical options should be given for both of them.
4379 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4380 if (mixed && (bctl->flags & allowed)) {
4381 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4382 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4383 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4385 "balance: mixed groups data and metadata options must be the same");
4392 * rw_devices will not change at the moment, device add/delete/replace
4395 num_devices = fs_info->fs_devices->rw_devices;
4398 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4399 * special bit for it, to make it easier to distinguish. Thus we need
4400 * to set it manually, or balance would refuse the profile.
4402 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4403 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4404 if (num_devices >= btrfs_raid_array[i].devs_min)
4405 allowed |= btrfs_raid_array[i].bg_flag;
4407 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4408 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4409 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
4415 * Allow to reduce metadata or system integrity only if force set for
4416 * profiles with redundancy (copies, parity)
4419 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4420 if (btrfs_raid_array[i].ncopies >= 2 ||
4421 btrfs_raid_array[i].tolerated_failures >= 1)
4422 allowed |= btrfs_raid_array[i].bg_flag;
4425 seq = read_seqbegin(&fs_info->profiles_lock);
4427 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4428 (fs_info->avail_system_alloc_bits & allowed) &&
4429 !(bctl->sys.target & allowed)) ||
4430 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4431 (fs_info->avail_metadata_alloc_bits & allowed) &&
4432 !(bctl->meta.target & allowed)))
4433 reducing_redundancy = true;
4435 reducing_redundancy = false;
4437 /* if we're not converting, the target field is uninitialized */
4438 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4439 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4440 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4441 bctl->data.target : fs_info->avail_data_alloc_bits;
4442 } while (read_seqretry(&fs_info->profiles_lock, seq));
4444 if (reducing_redundancy) {
4445 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4447 "balance: force reducing metadata redundancy");
4450 "balance: reduces metadata redundancy, use --force if you want this");
4456 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4457 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4459 "balance: metadata profile %s has lower redundancy than data profile %s",
4460 btrfs_bg_type_to_raid_name(meta_target),
4461 btrfs_bg_type_to_raid_name(data_target));
4464 ret = insert_balance_item(fs_info, bctl);
4465 if (ret && ret != -EEXIST)
4468 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4469 BUG_ON(ret == -EEXIST);
4470 BUG_ON(fs_info->balance_ctl);
4471 spin_lock(&fs_info->balance_lock);
4472 fs_info->balance_ctl = bctl;
4473 spin_unlock(&fs_info->balance_lock);
4475 BUG_ON(ret != -EEXIST);
4476 spin_lock(&fs_info->balance_lock);
4477 update_balance_args(bctl);
4478 spin_unlock(&fs_info->balance_lock);
4481 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4482 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4483 describe_balance_start_or_resume(fs_info);
4484 mutex_unlock(&fs_info->balance_mutex);
4486 ret = __btrfs_balance(fs_info);
4488 mutex_lock(&fs_info->balance_mutex);
4489 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req)) {
4490 btrfs_info(fs_info, "balance: paused");
4491 btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
4495 * Balance can be canceled by:
4497 * - Regular cancel request
4498 * Then ret == -ECANCELED and balance_cancel_req > 0
4500 * - Fatal signal to "btrfs" process
4501 * Either the signal caught by wait_reserve_ticket() and callers
4502 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4504 * Either way, in this case balance_cancel_req = 0, and
4505 * ret == -EINTR or ret == -ECANCELED.
4507 * So here we only check the return value to catch canceled balance.
4509 else if (ret == -ECANCELED || ret == -EINTR)
4510 btrfs_info(fs_info, "balance: canceled");
4512 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4514 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4517 memset(bargs, 0, sizeof(*bargs));
4518 btrfs_update_ioctl_balance_args(fs_info, bargs);
4521 /* We didn't pause, we can clean everything up. */
4523 reset_balance_state(fs_info);
4524 btrfs_exclop_finish(fs_info);
4527 wake_up(&fs_info->balance_wait_q);
4531 if (bctl->flags & BTRFS_BALANCE_RESUME)
4532 reset_balance_state(fs_info);
4535 btrfs_exclop_finish(fs_info);
4540 static int balance_kthread(void *data)
4542 struct btrfs_fs_info *fs_info = data;
4545 sb_start_write(fs_info->sb);
4546 mutex_lock(&fs_info->balance_mutex);
4547 if (fs_info->balance_ctl)
4548 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4549 mutex_unlock(&fs_info->balance_mutex);
4550 sb_end_write(fs_info->sb);
4555 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4557 struct task_struct *tsk;
4559 mutex_lock(&fs_info->balance_mutex);
4560 if (!fs_info->balance_ctl) {
4561 mutex_unlock(&fs_info->balance_mutex);
4564 mutex_unlock(&fs_info->balance_mutex);
4566 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4567 btrfs_info(fs_info, "balance: resume skipped");
4571 spin_lock(&fs_info->super_lock);
4572 ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED);
4573 fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
4574 spin_unlock(&fs_info->super_lock);
4576 * A ro->rw remount sequence should continue with the paused balance
4577 * regardless of who pauses it, system or the user as of now, so set
4580 spin_lock(&fs_info->balance_lock);
4581 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4582 spin_unlock(&fs_info->balance_lock);
4584 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4585 return PTR_ERR_OR_ZERO(tsk);
4588 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4590 struct btrfs_balance_control *bctl;
4591 struct btrfs_balance_item *item;
4592 struct btrfs_disk_balance_args disk_bargs;
4593 struct btrfs_path *path;
4594 struct extent_buffer *leaf;
4595 struct btrfs_key key;
4598 path = btrfs_alloc_path();
4602 key.objectid = BTRFS_BALANCE_OBJECTID;
4603 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4606 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4609 if (ret > 0) { /* ret = -ENOENT; */
4614 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4620 leaf = path->nodes[0];
4621 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4623 bctl->flags = btrfs_balance_flags(leaf, item);
4624 bctl->flags |= BTRFS_BALANCE_RESUME;
4626 btrfs_balance_data(leaf, item, &disk_bargs);
4627 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4628 btrfs_balance_meta(leaf, item, &disk_bargs);
4629 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4630 btrfs_balance_sys(leaf, item, &disk_bargs);
4631 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4634 * This should never happen, as the paused balance state is recovered
4635 * during mount without any chance of other exclusive ops to collide.
4637 * This gives the exclusive op status to balance and keeps in paused
4638 * state until user intervention (cancel or umount). If the ownership
4639 * cannot be assigned, show a message but do not fail. The balance
4640 * is in a paused state and must have fs_info::balance_ctl properly
4643 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED))
4645 "balance: cannot set exclusive op status, resume manually");
4647 btrfs_release_path(path);
4649 mutex_lock(&fs_info->balance_mutex);
4650 BUG_ON(fs_info->balance_ctl);
4651 spin_lock(&fs_info->balance_lock);
4652 fs_info->balance_ctl = bctl;
4653 spin_unlock(&fs_info->balance_lock);
4654 mutex_unlock(&fs_info->balance_mutex);
4656 btrfs_free_path(path);
4660 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4664 mutex_lock(&fs_info->balance_mutex);
4665 if (!fs_info->balance_ctl) {
4666 mutex_unlock(&fs_info->balance_mutex);
4670 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4671 atomic_inc(&fs_info->balance_pause_req);
4672 mutex_unlock(&fs_info->balance_mutex);
4674 wait_event(fs_info->balance_wait_q,
4675 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4677 mutex_lock(&fs_info->balance_mutex);
4678 /* we are good with balance_ctl ripped off from under us */
4679 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4680 atomic_dec(&fs_info->balance_pause_req);
4685 mutex_unlock(&fs_info->balance_mutex);
4689 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4691 mutex_lock(&fs_info->balance_mutex);
4692 if (!fs_info->balance_ctl) {
4693 mutex_unlock(&fs_info->balance_mutex);
4698 * A paused balance with the item stored on disk can be resumed at
4699 * mount time if the mount is read-write. Otherwise it's still paused
4700 * and we must not allow cancelling as it deletes the item.
4702 if (sb_rdonly(fs_info->sb)) {
4703 mutex_unlock(&fs_info->balance_mutex);
4707 atomic_inc(&fs_info->balance_cancel_req);
4709 * if we are running just wait and return, balance item is
4710 * deleted in btrfs_balance in this case
4712 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4713 mutex_unlock(&fs_info->balance_mutex);
4714 wait_event(fs_info->balance_wait_q,
4715 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4716 mutex_lock(&fs_info->balance_mutex);
4718 mutex_unlock(&fs_info->balance_mutex);
4720 * Lock released to allow other waiters to continue, we'll
4721 * reexamine the status again.
4723 mutex_lock(&fs_info->balance_mutex);
4725 if (fs_info->balance_ctl) {
4726 reset_balance_state(fs_info);
4727 btrfs_exclop_finish(fs_info);
4728 btrfs_info(fs_info, "balance: canceled");
4732 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4733 atomic_dec(&fs_info->balance_cancel_req);
4734 mutex_unlock(&fs_info->balance_mutex);
4738 int btrfs_uuid_scan_kthread(void *data)
4740 struct btrfs_fs_info *fs_info = data;
4741 struct btrfs_root *root = fs_info->tree_root;
4742 struct btrfs_key key;
4743 struct btrfs_path *path = NULL;
4745 struct extent_buffer *eb;
4747 struct btrfs_root_item root_item;
4749 struct btrfs_trans_handle *trans = NULL;
4750 bool closing = false;
4752 path = btrfs_alloc_path();
4759 key.type = BTRFS_ROOT_ITEM_KEY;
4763 if (btrfs_fs_closing(fs_info)) {
4767 ret = btrfs_search_forward(root, &key, path,
4768 BTRFS_OLDEST_GENERATION);
4775 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4776 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4777 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4778 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4781 eb = path->nodes[0];
4782 slot = path->slots[0];
4783 item_size = btrfs_item_size(eb, slot);
4784 if (item_size < sizeof(root_item))
4787 read_extent_buffer(eb, &root_item,
4788 btrfs_item_ptr_offset(eb, slot),
4789 (int)sizeof(root_item));
4790 if (btrfs_root_refs(&root_item) == 0)
4793 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4794 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4798 btrfs_release_path(path);
4800 * 1 - subvol uuid item
4801 * 1 - received_subvol uuid item
4803 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4804 if (IS_ERR(trans)) {
4805 ret = PTR_ERR(trans);
4813 btrfs_release_path(path);
4814 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4815 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4816 BTRFS_UUID_KEY_SUBVOL,
4819 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4825 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4826 ret = btrfs_uuid_tree_add(trans,
4827 root_item.received_uuid,
4828 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4831 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4838 btrfs_release_path(path);
4840 ret = btrfs_end_transaction(trans);
4846 if (key.offset < (u64)-1) {
4848 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4850 key.type = BTRFS_ROOT_ITEM_KEY;
4851 } else if (key.objectid < (u64)-1) {
4853 key.type = BTRFS_ROOT_ITEM_KEY;
4862 btrfs_free_path(path);
4863 if (trans && !IS_ERR(trans))
4864 btrfs_end_transaction(trans);
4866 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4868 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4869 up(&fs_info->uuid_tree_rescan_sem);
4873 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4875 struct btrfs_trans_handle *trans;
4876 struct btrfs_root *tree_root = fs_info->tree_root;
4877 struct btrfs_root *uuid_root;
4878 struct task_struct *task;
4885 trans = btrfs_start_transaction(tree_root, 2);
4887 return PTR_ERR(trans);
4889 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4890 if (IS_ERR(uuid_root)) {
4891 ret = PTR_ERR(uuid_root);
4892 btrfs_abort_transaction(trans, ret);
4893 btrfs_end_transaction(trans);
4897 fs_info->uuid_root = uuid_root;
4899 ret = btrfs_commit_transaction(trans);
4903 down(&fs_info->uuid_tree_rescan_sem);
4904 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4906 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4907 btrfs_warn(fs_info, "failed to start uuid_scan task");
4908 up(&fs_info->uuid_tree_rescan_sem);
4909 return PTR_ERR(task);
4916 * shrinking a device means finding all of the device extents past
4917 * the new size, and then following the back refs to the chunks.
4918 * The chunk relocation code actually frees the device extent
4920 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4922 struct btrfs_fs_info *fs_info = device->fs_info;
4923 struct btrfs_root *root = fs_info->dev_root;
4924 struct btrfs_trans_handle *trans;
4925 struct btrfs_dev_extent *dev_extent = NULL;
4926 struct btrfs_path *path;
4932 bool retried = false;
4933 struct extent_buffer *l;
4934 struct btrfs_key key;
4935 struct btrfs_super_block *super_copy = fs_info->super_copy;
4936 u64 old_total = btrfs_super_total_bytes(super_copy);
4937 u64 old_size = btrfs_device_get_total_bytes(device);
4942 new_size = round_down(new_size, fs_info->sectorsize);
4944 diff = round_down(old_size - new_size, fs_info->sectorsize);
4946 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4949 path = btrfs_alloc_path();
4953 path->reada = READA_BACK;
4955 trans = btrfs_start_transaction(root, 0);
4956 if (IS_ERR(trans)) {
4957 btrfs_free_path(path);
4958 return PTR_ERR(trans);
4961 mutex_lock(&fs_info->chunk_mutex);
4963 btrfs_device_set_total_bytes(device, new_size);
4964 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4965 device->fs_devices->total_rw_bytes -= diff;
4968 * The new free_chunk_space is new_size - used, so we have to
4969 * subtract the delta of the old free_chunk_space which included
4970 * old_size - used. If used > new_size then just subtract this
4971 * entire device's free space.
4973 if (device->bytes_used < new_size)
4974 free_diff = (old_size - device->bytes_used) -
4975 (new_size - device->bytes_used);
4977 free_diff = old_size - device->bytes_used;
4978 atomic64_sub(free_diff, &fs_info->free_chunk_space);
4982 * Once the device's size has been set to the new size, ensure all
4983 * in-memory chunks are synced to disk so that the loop below sees them
4984 * and relocates them accordingly.
4986 if (contains_pending_extent(device, &start, diff)) {
4987 mutex_unlock(&fs_info->chunk_mutex);
4988 ret = btrfs_commit_transaction(trans);
4992 mutex_unlock(&fs_info->chunk_mutex);
4993 btrfs_end_transaction(trans);
4997 key.objectid = device->devid;
4998 key.offset = (u64)-1;
4999 key.type = BTRFS_DEV_EXTENT_KEY;
5002 mutex_lock(&fs_info->reclaim_bgs_lock);
5003 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5005 mutex_unlock(&fs_info->reclaim_bgs_lock);
5009 ret = btrfs_previous_item(root, path, 0, key.type);
5011 mutex_unlock(&fs_info->reclaim_bgs_lock);
5015 btrfs_release_path(path);
5020 slot = path->slots[0];
5021 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
5023 if (key.objectid != device->devid) {
5024 mutex_unlock(&fs_info->reclaim_bgs_lock);
5025 btrfs_release_path(path);
5029 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
5030 length = btrfs_dev_extent_length(l, dev_extent);
5032 if (key.offset + length <= new_size) {
5033 mutex_unlock(&fs_info->reclaim_bgs_lock);
5034 btrfs_release_path(path);
5038 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
5039 btrfs_release_path(path);
5042 * We may be relocating the only data chunk we have,
5043 * which could potentially end up with losing data's
5044 * raid profile, so lets allocate an empty one in
5047 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
5049 mutex_unlock(&fs_info->reclaim_bgs_lock);
5053 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
5054 mutex_unlock(&fs_info->reclaim_bgs_lock);
5055 if (ret == -ENOSPC) {
5058 if (ret == -ETXTBSY) {
5060 "could not shrink block group %llu due to active swapfile",
5065 } while (key.offset-- > 0);
5067 if (failed && !retried) {
5071 } else if (failed && retried) {
5076 /* Shrinking succeeded, else we would be at "done". */
5077 trans = btrfs_start_transaction(root, 0);
5078 if (IS_ERR(trans)) {
5079 ret = PTR_ERR(trans);
5083 mutex_lock(&fs_info->chunk_mutex);
5084 /* Clear all state bits beyond the shrunk device size */
5085 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
5088 btrfs_device_set_disk_total_bytes(device, new_size);
5089 if (list_empty(&device->post_commit_list))
5090 list_add_tail(&device->post_commit_list,
5091 &trans->transaction->dev_update_list);
5093 WARN_ON(diff > old_total);
5094 btrfs_set_super_total_bytes(super_copy,
5095 round_down(old_total - diff, fs_info->sectorsize));
5096 mutex_unlock(&fs_info->chunk_mutex);
5098 btrfs_reserve_chunk_metadata(trans, false);
5099 /* Now btrfs_update_device() will change the on-disk size. */
5100 ret = btrfs_update_device(trans, device);
5101 btrfs_trans_release_chunk_metadata(trans);
5103 btrfs_abort_transaction(trans, ret);
5104 btrfs_end_transaction(trans);
5106 ret = btrfs_commit_transaction(trans);
5109 btrfs_free_path(path);
5111 mutex_lock(&fs_info->chunk_mutex);
5112 btrfs_device_set_total_bytes(device, old_size);
5113 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5114 device->fs_devices->total_rw_bytes += diff;
5115 atomic64_add(free_diff, &fs_info->free_chunk_space);
5117 mutex_unlock(&fs_info->chunk_mutex);
5122 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
5123 struct btrfs_key *key,
5124 struct btrfs_chunk *chunk, int item_size)
5126 struct btrfs_super_block *super_copy = fs_info->super_copy;
5127 struct btrfs_disk_key disk_key;
5131 lockdep_assert_held(&fs_info->chunk_mutex);
5133 array_size = btrfs_super_sys_array_size(super_copy);
5134 if (array_size + item_size + sizeof(disk_key)
5135 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
5138 ptr = super_copy->sys_chunk_array + array_size;
5139 btrfs_cpu_key_to_disk(&disk_key, key);
5140 memcpy(ptr, &disk_key, sizeof(disk_key));
5141 ptr += sizeof(disk_key);
5142 memcpy(ptr, chunk, item_size);
5143 item_size += sizeof(disk_key);
5144 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
5150 * sort the devices in descending order by max_avail, total_avail
5152 static int btrfs_cmp_device_info(const void *a, const void *b)
5154 const struct btrfs_device_info *di_a = a;
5155 const struct btrfs_device_info *di_b = b;
5157 if (di_a->max_avail > di_b->max_avail)
5159 if (di_a->max_avail < di_b->max_avail)
5161 if (di_a->total_avail > di_b->total_avail)
5163 if (di_a->total_avail < di_b->total_avail)
5168 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
5170 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5173 btrfs_set_fs_incompat(info, RAID56);
5176 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
5178 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
5181 btrfs_set_fs_incompat(info, RAID1C34);
5185 * Structure used internally for btrfs_create_chunk() function.
5186 * Wraps needed parameters.
5188 struct alloc_chunk_ctl {
5191 /* Total number of stripes to allocate */
5193 /* sub_stripes info for map */
5195 /* Stripes per device */
5197 /* Maximum number of devices to use */
5199 /* Minimum number of devices to use */
5201 /* ndevs has to be a multiple of this */
5203 /* Number of copies */
5205 /* Number of stripes worth of bytes to store parity information */
5207 u64 max_stripe_size;
5215 static void init_alloc_chunk_ctl_policy_regular(
5216 struct btrfs_fs_devices *fs_devices,
5217 struct alloc_chunk_ctl *ctl)
5219 struct btrfs_space_info *space_info;
5221 space_info = btrfs_find_space_info(fs_devices->fs_info, ctl->type);
5224 ctl->max_chunk_size = READ_ONCE(space_info->chunk_size);
5225 ctl->max_stripe_size = min_t(u64, ctl->max_chunk_size, SZ_1G);
5227 if (ctl->type & BTRFS_BLOCK_GROUP_SYSTEM)
5228 ctl->devs_max = min_t(int, ctl->devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
5230 /* We don't want a chunk larger than 10% of writable space */
5231 ctl->max_chunk_size = min(mult_perc(fs_devices->total_rw_bytes, 10),
5232 ctl->max_chunk_size);
5233 ctl->dev_extent_min = btrfs_stripe_nr_to_offset(ctl->dev_stripes);
5236 static void init_alloc_chunk_ctl_policy_zoned(
5237 struct btrfs_fs_devices *fs_devices,
5238 struct alloc_chunk_ctl *ctl)
5240 u64 zone_size = fs_devices->fs_info->zone_size;
5242 int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5243 int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5244 u64 min_chunk_size = min_data_stripes * zone_size;
5245 u64 type = ctl->type;
5247 ctl->max_stripe_size = zone_size;
5248 if (type & BTRFS_BLOCK_GROUP_DATA) {
5249 ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5251 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5252 ctl->max_chunk_size = ctl->max_stripe_size;
5253 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5254 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5255 ctl->devs_max = min_t(int, ctl->devs_max,
5256 BTRFS_MAX_DEVS_SYS_CHUNK);
5261 /* We don't want a chunk larger than 10% of writable space */
5262 limit = max(round_down(mult_perc(fs_devices->total_rw_bytes, 10),
5265 ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5266 ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5269 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5270 struct alloc_chunk_ctl *ctl)
5272 int index = btrfs_bg_flags_to_raid_index(ctl->type);
5274 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5275 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5276 ctl->devs_max = btrfs_raid_array[index].devs_max;
5278 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5279 ctl->devs_min = btrfs_raid_array[index].devs_min;
5280 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5281 ctl->ncopies = btrfs_raid_array[index].ncopies;
5282 ctl->nparity = btrfs_raid_array[index].nparity;
5285 switch (fs_devices->chunk_alloc_policy) {
5286 case BTRFS_CHUNK_ALLOC_REGULAR:
5287 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5289 case BTRFS_CHUNK_ALLOC_ZONED:
5290 init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5297 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5298 struct alloc_chunk_ctl *ctl,
5299 struct btrfs_device_info *devices_info)
5301 struct btrfs_fs_info *info = fs_devices->fs_info;
5302 struct btrfs_device *device;
5304 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5311 * in the first pass through the devices list, we gather information
5312 * about the available holes on each device.
5314 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5315 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5317 "BTRFS: read-only device in alloc_list\n");
5321 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5322 &device->dev_state) ||
5323 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5326 if (device->total_bytes > device->bytes_used)
5327 total_avail = device->total_bytes - device->bytes_used;
5331 /* If there is no space on this device, skip it. */
5332 if (total_avail < ctl->dev_extent_min)
5335 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5337 if (ret && ret != -ENOSPC)
5341 max_avail = dev_extent_want;
5343 if (max_avail < ctl->dev_extent_min) {
5344 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5346 "%s: devid %llu has no free space, have=%llu want=%llu",
5347 __func__, device->devid, max_avail,
5348 ctl->dev_extent_min);
5352 if (ndevs == fs_devices->rw_devices) {
5353 WARN(1, "%s: found more than %llu devices\n",
5354 __func__, fs_devices->rw_devices);
5357 devices_info[ndevs].dev_offset = dev_offset;
5358 devices_info[ndevs].max_avail = max_avail;
5359 devices_info[ndevs].total_avail = total_avail;
5360 devices_info[ndevs].dev = device;
5366 * now sort the devices by hole size / available space
5368 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5369 btrfs_cmp_device_info, NULL);
5374 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5375 struct btrfs_device_info *devices_info)
5377 /* Number of stripes that count for block group size */
5381 * The primary goal is to maximize the number of stripes, so use as
5382 * many devices as possible, even if the stripes are not maximum sized.
5384 * The DUP profile stores more than one stripe per device, the
5385 * max_avail is the total size so we have to adjust.
5387 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5389 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5391 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5392 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5395 * Use the number of data stripes to figure out how big this chunk is
5396 * really going to be in terms of logical address space, and compare
5397 * that answer with the max chunk size. If it's higher, we try to
5398 * reduce stripe_size.
5400 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5402 * Reduce stripe_size, round it up to a 16MB boundary again and
5403 * then use it, unless it ends up being even bigger than the
5404 * previous value we had already.
5406 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5407 data_stripes), SZ_16M),
5411 /* Stripe size should not go beyond 1G. */
5412 ctl->stripe_size = min_t(u64, ctl->stripe_size, SZ_1G);
5414 /* Align to BTRFS_STRIPE_LEN */
5415 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5416 ctl->chunk_size = ctl->stripe_size * data_stripes;
5421 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5422 struct btrfs_device_info *devices_info)
5424 u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5425 /* Number of stripes that count for block group size */
5429 * It should hold because:
5430 * dev_extent_min == dev_extent_want == zone_size * dev_stripes
5432 ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min);
5434 ctl->stripe_size = zone_size;
5435 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5436 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5438 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */
5439 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5440 ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5441 ctl->stripe_size) + ctl->nparity,
5443 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5444 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5445 ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size);
5448 ctl->chunk_size = ctl->stripe_size * data_stripes;
5453 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5454 struct alloc_chunk_ctl *ctl,
5455 struct btrfs_device_info *devices_info)
5457 struct btrfs_fs_info *info = fs_devices->fs_info;
5460 * Round down to number of usable stripes, devs_increment can be any
5461 * number so we can't use round_down() that requires power of 2, while
5462 * rounddown is safe.
5464 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5466 if (ctl->ndevs < ctl->devs_min) {
5467 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5469 "%s: not enough devices with free space: have=%d minimum required=%d",
5470 __func__, ctl->ndevs, ctl->devs_min);
5475 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5477 switch (fs_devices->chunk_alloc_policy) {
5478 case BTRFS_CHUNK_ALLOC_REGULAR:
5479 return decide_stripe_size_regular(ctl, devices_info);
5480 case BTRFS_CHUNK_ALLOC_ZONED:
5481 return decide_stripe_size_zoned(ctl, devices_info);
5487 static void chunk_map_device_set_bits(struct btrfs_chunk_map *map, unsigned int bits)
5489 for (int i = 0; i < map->num_stripes; i++) {
5490 struct btrfs_io_stripe *stripe = &map->stripes[i];
5491 struct btrfs_device *device = stripe->dev;
5493 set_extent_bit(&device->alloc_state, stripe->physical,
5494 stripe->physical + map->stripe_size - 1,
5495 bits | EXTENT_NOWAIT, NULL);
5499 static void chunk_map_device_clear_bits(struct btrfs_chunk_map *map, unsigned int bits)
5501 for (int i = 0; i < map->num_stripes; i++) {
5502 struct btrfs_io_stripe *stripe = &map->stripes[i];
5503 struct btrfs_device *device = stripe->dev;
5505 __clear_extent_bit(&device->alloc_state, stripe->physical,
5506 stripe->physical + map->stripe_size - 1,
5507 bits | EXTENT_NOWAIT,
5512 void btrfs_remove_chunk_map(struct btrfs_fs_info *fs_info, struct btrfs_chunk_map *map)
5514 write_lock(&fs_info->mapping_tree_lock);
5515 rb_erase_cached(&map->rb_node, &fs_info->mapping_tree);
5516 RB_CLEAR_NODE(&map->rb_node);
5517 chunk_map_device_clear_bits(map, CHUNK_ALLOCATED);
5518 write_unlock(&fs_info->mapping_tree_lock);
5520 /* Once for the tree reference. */
5521 btrfs_free_chunk_map(map);
5525 int btrfs_add_chunk_map(struct btrfs_fs_info *fs_info, struct btrfs_chunk_map *map)
5528 struct rb_node *parent = NULL;
5529 bool leftmost = true;
5531 write_lock(&fs_info->mapping_tree_lock);
5532 p = &fs_info->mapping_tree.rb_root.rb_node;
5534 struct btrfs_chunk_map *entry;
5537 entry = rb_entry(parent, struct btrfs_chunk_map, rb_node);
5539 if (map->start < entry->start) {
5541 } else if (map->start > entry->start) {
5542 p = &(*p)->rb_right;
5545 write_unlock(&fs_info->mapping_tree_lock);
5549 rb_link_node(&map->rb_node, parent, p);
5550 rb_insert_color_cached(&map->rb_node, &fs_info->mapping_tree, leftmost);
5551 chunk_map_device_set_bits(map, CHUNK_ALLOCATED);
5552 chunk_map_device_clear_bits(map, CHUNK_TRIMMED);
5553 write_unlock(&fs_info->mapping_tree_lock);
5559 struct btrfs_chunk_map *btrfs_alloc_chunk_map(int num_stripes, gfp_t gfp)
5561 struct btrfs_chunk_map *map;
5563 map = kmalloc(btrfs_chunk_map_size(num_stripes), gfp);
5567 refcount_set(&map->refs, 1);
5568 RB_CLEAR_NODE(&map->rb_node);
5573 struct btrfs_chunk_map *btrfs_clone_chunk_map(struct btrfs_chunk_map *map, gfp_t gfp)
5575 const int size = btrfs_chunk_map_size(map->num_stripes);
5576 struct btrfs_chunk_map *clone;
5578 clone = kmemdup(map, size, gfp);
5582 refcount_set(&clone->refs, 1);
5583 RB_CLEAR_NODE(&clone->rb_node);
5588 static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
5589 struct alloc_chunk_ctl *ctl,
5590 struct btrfs_device_info *devices_info)
5592 struct btrfs_fs_info *info = trans->fs_info;
5593 struct btrfs_chunk_map *map;
5594 struct btrfs_block_group *block_group;
5595 u64 start = ctl->start;
5596 u64 type = ctl->type;
5601 map = btrfs_alloc_chunk_map(ctl->num_stripes, GFP_NOFS);
5603 return ERR_PTR(-ENOMEM);
5606 map->chunk_len = ctl->chunk_size;
5607 map->stripe_size = ctl->stripe_size;
5609 map->io_align = BTRFS_STRIPE_LEN;
5610 map->io_width = BTRFS_STRIPE_LEN;
5611 map->sub_stripes = ctl->sub_stripes;
5612 map->num_stripes = ctl->num_stripes;
5614 for (i = 0; i < ctl->ndevs; ++i) {
5615 for (j = 0; j < ctl->dev_stripes; ++j) {
5616 int s = i * ctl->dev_stripes + j;
5617 map->stripes[s].dev = devices_info[i].dev;
5618 map->stripes[s].physical = devices_info[i].dev_offset +
5619 j * ctl->stripe_size;
5623 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5625 ret = btrfs_add_chunk_map(info, map);
5627 btrfs_free_chunk_map(map);
5628 return ERR_PTR(ret);
5631 block_group = btrfs_make_block_group(trans, type, start, ctl->chunk_size);
5632 if (IS_ERR(block_group)) {
5633 btrfs_remove_chunk_map(info, map);
5637 for (int i = 0; i < map->num_stripes; i++) {
5638 struct btrfs_device *dev = map->stripes[i].dev;
5640 btrfs_device_set_bytes_used(dev,
5641 dev->bytes_used + ctl->stripe_size);
5642 if (list_empty(&dev->post_commit_list))
5643 list_add_tail(&dev->post_commit_list,
5644 &trans->transaction->dev_update_list);
5647 atomic64_sub(ctl->stripe_size * map->num_stripes,
5648 &info->free_chunk_space);
5650 check_raid56_incompat_flag(info, type);
5651 check_raid1c34_incompat_flag(info, type);
5656 struct btrfs_block_group *btrfs_create_chunk(struct btrfs_trans_handle *trans,
5659 struct btrfs_fs_info *info = trans->fs_info;
5660 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5661 struct btrfs_device_info *devices_info = NULL;
5662 struct alloc_chunk_ctl ctl;
5663 struct btrfs_block_group *block_group;
5666 lockdep_assert_held(&info->chunk_mutex);
5668 if (!alloc_profile_is_valid(type, 0)) {
5670 return ERR_PTR(-EINVAL);
5673 if (list_empty(&fs_devices->alloc_list)) {
5674 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5675 btrfs_debug(info, "%s: no writable device", __func__);
5676 return ERR_PTR(-ENOSPC);
5679 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5680 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5682 return ERR_PTR(-EINVAL);
5685 ctl.start = find_next_chunk(info);
5687 init_alloc_chunk_ctl(fs_devices, &ctl);
5689 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5692 return ERR_PTR(-ENOMEM);
5694 ret = gather_device_info(fs_devices, &ctl, devices_info);
5696 block_group = ERR_PTR(ret);
5700 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5702 block_group = ERR_PTR(ret);
5706 block_group = create_chunk(trans, &ctl, devices_info);
5709 kfree(devices_info);
5714 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5715 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5718 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5721 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
5722 struct btrfs_block_group *bg)
5724 struct btrfs_fs_info *fs_info = trans->fs_info;
5725 struct btrfs_root *chunk_root = fs_info->chunk_root;
5726 struct btrfs_key key;
5727 struct btrfs_chunk *chunk;
5728 struct btrfs_stripe *stripe;
5729 struct btrfs_chunk_map *map;
5735 * We take the chunk_mutex for 2 reasons:
5737 * 1) Updates and insertions in the chunk btree must be done while holding
5738 * the chunk_mutex, as well as updating the system chunk array in the
5739 * superblock. See the comment on top of btrfs_chunk_alloc() for the
5742 * 2) To prevent races with the final phase of a device replace operation
5743 * that replaces the device object associated with the map's stripes,
5744 * because the device object's id can change at any time during that
5745 * final phase of the device replace operation
5746 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5747 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5748 * which would cause a failure when updating the device item, which does
5749 * not exists, or persisting a stripe of the chunk item with such ID.
5750 * Here we can't use the device_list_mutex because our caller already
5751 * has locked the chunk_mutex, and the final phase of device replace
5752 * acquires both mutexes - first the device_list_mutex and then the
5753 * chunk_mutex. Using any of those two mutexes protects us from a
5754 * concurrent device replace.
5756 lockdep_assert_held(&fs_info->chunk_mutex);
5758 map = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
5761 btrfs_abort_transaction(trans, ret);
5765 item_size = btrfs_chunk_item_size(map->num_stripes);
5767 chunk = kzalloc(item_size, GFP_NOFS);
5770 btrfs_abort_transaction(trans, ret);
5774 for (i = 0; i < map->num_stripes; i++) {
5775 struct btrfs_device *device = map->stripes[i].dev;
5777 ret = btrfs_update_device(trans, device);
5782 stripe = &chunk->stripe;
5783 for (i = 0; i < map->num_stripes; i++) {
5784 struct btrfs_device *device = map->stripes[i].dev;
5785 const u64 dev_offset = map->stripes[i].physical;
5787 btrfs_set_stack_stripe_devid(stripe, device->devid);
5788 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5789 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5793 btrfs_set_stack_chunk_length(chunk, bg->length);
5794 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
5795 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
5796 btrfs_set_stack_chunk_type(chunk, map->type);
5797 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5798 btrfs_set_stack_chunk_io_align(chunk, BTRFS_STRIPE_LEN);
5799 btrfs_set_stack_chunk_io_width(chunk, BTRFS_STRIPE_LEN);
5800 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5801 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5803 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5804 key.type = BTRFS_CHUNK_ITEM_KEY;
5805 key.offset = bg->start;
5807 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5811 set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED, &bg->runtime_flags);
5813 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5814 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5821 btrfs_free_chunk_map(map);
5825 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5827 struct btrfs_fs_info *fs_info = trans->fs_info;
5829 struct btrfs_block_group *meta_bg;
5830 struct btrfs_block_group *sys_bg;
5833 * When adding a new device for sprouting, the seed device is read-only
5834 * so we must first allocate a metadata and a system chunk. But before
5835 * adding the block group items to the extent, device and chunk btrees,
5838 * 1) Create both chunks without doing any changes to the btrees, as
5839 * otherwise we would get -ENOSPC since the block groups from the
5840 * seed device are read-only;
5842 * 2) Add the device item for the new sprout device - finishing the setup
5843 * of a new block group requires updating the device item in the chunk
5844 * btree, so it must exist when we attempt to do it. The previous step
5845 * ensures this does not fail with -ENOSPC.
5847 * After that we can add the block group items to their btrees:
5848 * update existing device item in the chunk btree, add a new block group
5849 * item to the extent btree, add a new chunk item to the chunk btree and
5850 * finally add the new device extent items to the devices btree.
5853 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5854 meta_bg = btrfs_create_chunk(trans, alloc_profile);
5855 if (IS_ERR(meta_bg))
5856 return PTR_ERR(meta_bg);
5858 alloc_profile = btrfs_system_alloc_profile(fs_info);
5859 sys_bg = btrfs_create_chunk(trans, alloc_profile);
5861 return PTR_ERR(sys_bg);
5866 static inline int btrfs_chunk_max_errors(struct btrfs_chunk_map *map)
5868 const int index = btrfs_bg_flags_to_raid_index(map->type);
5870 return btrfs_raid_array[index].tolerated_failures;
5873 bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5875 struct btrfs_chunk_map *map;
5880 map = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5884 for (i = 0; i < map->num_stripes; i++) {
5885 if (test_bit(BTRFS_DEV_STATE_MISSING,
5886 &map->stripes[i].dev->dev_state)) {
5890 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5891 &map->stripes[i].dev->dev_state)) {
5898 * If the number of missing devices is larger than max errors, we can
5899 * not write the data into that chunk successfully.
5901 if (miss_ndevs > btrfs_chunk_max_errors(map))
5904 btrfs_free_chunk_map(map);
5908 void btrfs_mapping_tree_free(struct btrfs_fs_info *fs_info)
5910 write_lock(&fs_info->mapping_tree_lock);
5911 while (!RB_EMPTY_ROOT(&fs_info->mapping_tree.rb_root)) {
5912 struct btrfs_chunk_map *map;
5913 struct rb_node *node;
5915 node = rb_first_cached(&fs_info->mapping_tree);
5916 map = rb_entry(node, struct btrfs_chunk_map, rb_node);
5917 rb_erase_cached(&map->rb_node, &fs_info->mapping_tree);
5918 RB_CLEAR_NODE(&map->rb_node);
5919 chunk_map_device_clear_bits(map, CHUNK_ALLOCATED);
5920 /* Once for the tree ref. */
5921 btrfs_free_chunk_map(map);
5922 cond_resched_rwlock_write(&fs_info->mapping_tree_lock);
5924 write_unlock(&fs_info->mapping_tree_lock);
5927 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5929 struct btrfs_chunk_map *map;
5930 enum btrfs_raid_types index;
5933 map = btrfs_get_chunk_map(fs_info, logical, len);
5936 * We could return errors for these cases, but that could get
5937 * ugly and we'd probably do the same thing which is just not do
5938 * anything else and exit, so return 1 so the callers don't try
5939 * to use other copies.
5943 index = btrfs_bg_flags_to_raid_index(map->type);
5945 /* Non-RAID56, use their ncopies from btrfs_raid_array. */
5946 if (!(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5947 ret = btrfs_raid_array[index].ncopies;
5948 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5950 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5952 * There could be two corrupted data stripes, we need
5953 * to loop retry in order to rebuild the correct data.
5955 * Fail a stripe at a time on every retry except the
5956 * stripe under reconstruction.
5958 ret = map->num_stripes;
5959 btrfs_free_chunk_map(map);
5963 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5966 struct btrfs_chunk_map *map;
5967 unsigned long len = fs_info->sectorsize;
5969 if (!btrfs_fs_incompat(fs_info, RAID56))
5972 map = btrfs_get_chunk_map(fs_info, logical, len);
5974 if (!WARN_ON(IS_ERR(map))) {
5975 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5976 len = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
5977 btrfs_free_chunk_map(map);
5982 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5984 struct btrfs_chunk_map *map;
5987 if (!btrfs_fs_incompat(fs_info, RAID56))
5990 map = btrfs_get_chunk_map(fs_info, logical, len);
5992 if (!WARN_ON(IS_ERR(map))) {
5993 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5995 btrfs_free_chunk_map(map);
6000 static int find_live_mirror(struct btrfs_fs_info *fs_info,
6001 struct btrfs_chunk_map *map, int first,
6002 int dev_replace_is_ongoing)
6006 int preferred_mirror;
6008 struct btrfs_device *srcdev;
6011 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
6013 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6014 num_stripes = map->sub_stripes;
6016 num_stripes = map->num_stripes;
6018 switch (fs_info->fs_devices->read_policy) {
6020 /* Shouldn't happen, just warn and use pid instead of failing */
6021 btrfs_warn_rl(fs_info,
6022 "unknown read_policy type %u, reset to pid",
6023 fs_info->fs_devices->read_policy);
6024 fs_info->fs_devices->read_policy = BTRFS_READ_POLICY_PID;
6026 case BTRFS_READ_POLICY_PID:
6027 preferred_mirror = first + (current->pid % num_stripes);
6031 if (dev_replace_is_ongoing &&
6032 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
6033 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
6034 srcdev = fs_info->dev_replace.srcdev;
6039 * try to avoid the drive that is the source drive for a
6040 * dev-replace procedure, only choose it if no other non-missing
6041 * mirror is available
6043 for (tolerance = 0; tolerance < 2; tolerance++) {
6044 if (map->stripes[preferred_mirror].dev->bdev &&
6045 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
6046 return preferred_mirror;
6047 for (i = first; i < first + num_stripes; i++) {
6048 if (map->stripes[i].dev->bdev &&
6049 (tolerance || map->stripes[i].dev != srcdev))
6054 /* we couldn't find one that doesn't fail. Just return something
6055 * and the io error handling code will clean up eventually
6057 return preferred_mirror;
6060 static struct btrfs_io_context *alloc_btrfs_io_context(struct btrfs_fs_info *fs_info,
6064 struct btrfs_io_context *bioc;
6067 /* The size of btrfs_io_context */
6068 sizeof(struct btrfs_io_context) +
6069 /* Plus the variable array for the stripes */
6070 sizeof(struct btrfs_io_stripe) * (total_stripes),
6076 refcount_set(&bioc->refs, 1);
6078 bioc->fs_info = fs_info;
6079 bioc->replace_stripe_src = -1;
6080 bioc->full_stripe_logical = (u64)-1;
6081 bioc->logical = logical;
6086 void btrfs_get_bioc(struct btrfs_io_context *bioc)
6088 WARN_ON(!refcount_read(&bioc->refs));
6089 refcount_inc(&bioc->refs);
6092 void btrfs_put_bioc(struct btrfs_io_context *bioc)
6096 if (refcount_dec_and_test(&bioc->refs))
6101 * Please note that, discard won't be sent to target device of device
6104 struct btrfs_discard_stripe *btrfs_map_discard(struct btrfs_fs_info *fs_info,
6105 u64 logical, u64 *length_ret,
6108 struct btrfs_chunk_map *map;
6109 struct btrfs_discard_stripe *stripes;
6110 u64 length = *length_ret;
6115 u64 stripe_end_offset;
6119 u32 sub_stripes = 0;
6120 u32 stripes_per_dev = 0;
6121 u32 remaining_stripes = 0;
6122 u32 last_stripe = 0;
6126 map = btrfs_get_chunk_map(fs_info, logical, length);
6128 return ERR_CAST(map);
6130 /* we don't discard raid56 yet */
6131 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6136 offset = logical - map->start;
6137 length = min_t(u64, map->start + map->chunk_len - logical, length);
6138 *length_ret = length;
6141 * stripe_nr counts the total number of stripes we have to stride
6142 * to get to this block
6144 stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6146 /* stripe_offset is the offset of this block in its stripe */
6147 stripe_offset = offset - btrfs_stripe_nr_to_offset(stripe_nr);
6149 stripe_nr_end = round_up(offset + length, BTRFS_STRIPE_LEN) >>
6150 BTRFS_STRIPE_LEN_SHIFT;
6151 stripe_cnt = stripe_nr_end - stripe_nr;
6152 stripe_end_offset = btrfs_stripe_nr_to_offset(stripe_nr_end) -
6155 * after this, stripe_nr is the number of stripes on this
6156 * device we have to walk to find the data, and stripe_index is
6157 * the number of our device in the stripe array
6161 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6162 BTRFS_BLOCK_GROUP_RAID10)) {
6163 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6166 sub_stripes = map->sub_stripes;
6168 factor = map->num_stripes / sub_stripes;
6169 *num_stripes = min_t(u64, map->num_stripes,
6170 sub_stripes * stripe_cnt);
6171 stripe_index = stripe_nr % factor;
6172 stripe_nr /= factor;
6173 stripe_index *= sub_stripes;
6175 remaining_stripes = stripe_cnt % factor;
6176 stripes_per_dev = stripe_cnt / factor;
6177 last_stripe = ((stripe_nr_end - 1) % factor) * sub_stripes;
6178 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
6179 BTRFS_BLOCK_GROUP_DUP)) {
6180 *num_stripes = map->num_stripes;
6182 stripe_index = stripe_nr % map->num_stripes;
6183 stripe_nr /= map->num_stripes;
6186 stripes = kcalloc(*num_stripes, sizeof(*stripes), GFP_NOFS);
6192 for (i = 0; i < *num_stripes; i++) {
6193 stripes[i].physical =
6194 map->stripes[stripe_index].physical +
6195 stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr);
6196 stripes[i].dev = map->stripes[stripe_index].dev;
6198 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6199 BTRFS_BLOCK_GROUP_RAID10)) {
6200 stripes[i].length = btrfs_stripe_nr_to_offset(stripes_per_dev);
6202 if (i / sub_stripes < remaining_stripes)
6203 stripes[i].length += BTRFS_STRIPE_LEN;
6206 * Special for the first stripe and
6209 * |-------|...|-------|
6213 if (i < sub_stripes)
6214 stripes[i].length -= stripe_offset;
6216 if (stripe_index >= last_stripe &&
6217 stripe_index <= (last_stripe +
6219 stripes[i].length -= stripe_end_offset;
6221 if (i == sub_stripes - 1)
6224 stripes[i].length = length;
6228 if (stripe_index == map->num_stripes) {
6234 btrfs_free_chunk_map(map);
6237 btrfs_free_chunk_map(map);
6238 return ERR_PTR(ret);
6241 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6243 struct btrfs_block_group *cache;
6246 /* Non zoned filesystem does not use "to_copy" flag */
6247 if (!btrfs_is_zoned(fs_info))
6250 cache = btrfs_lookup_block_group(fs_info, logical);
6252 ret = test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
6254 btrfs_put_block_group(cache);
6258 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
6259 struct btrfs_io_context *bioc,
6260 struct btrfs_dev_replace *dev_replace,
6262 int *num_stripes_ret, int *max_errors_ret)
6264 u64 srcdev_devid = dev_replace->srcdev->devid;
6266 * At this stage, num_stripes is still the real number of stripes,
6267 * excluding the duplicated stripes.
6269 int num_stripes = *num_stripes_ret;
6270 int nr_extra_stripes = 0;
6271 int max_errors = *max_errors_ret;
6275 * A block group which has "to_copy" set will eventually be copied by
6276 * the dev-replace process. We can avoid cloning IO here.
6278 if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6282 * Duplicate the write operations while the dev-replace procedure is
6283 * running. Since the copying of the old disk to the new disk takes
6284 * place at run time while the filesystem is mounted writable, the
6285 * regular write operations to the old disk have to be duplicated to go
6286 * to the new disk as well.
6288 * Note that device->missing is handled by the caller, and that the
6289 * write to the old disk is already set up in the stripes array.
6291 for (i = 0; i < num_stripes; i++) {
6292 struct btrfs_io_stripe *old = &bioc->stripes[i];
6293 struct btrfs_io_stripe *new = &bioc->stripes[num_stripes + nr_extra_stripes];
6295 if (old->dev->devid != srcdev_devid)
6298 new->physical = old->physical;
6299 new->dev = dev_replace->tgtdev;
6300 if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK)
6301 bioc->replace_stripe_src = i;
6305 /* We can only have at most 2 extra nr_stripes (for DUP). */
6306 ASSERT(nr_extra_stripes <= 2);
6308 * For GET_READ_MIRRORS, we can only return at most 1 extra stripe for
6310 * If we have 2 extra stripes, only choose the one with smaller physical.
6312 if (op == BTRFS_MAP_GET_READ_MIRRORS && nr_extra_stripes == 2) {
6313 struct btrfs_io_stripe *first = &bioc->stripes[num_stripes];
6314 struct btrfs_io_stripe *second = &bioc->stripes[num_stripes + 1];
6316 /* Only DUP can have two extra stripes. */
6317 ASSERT(bioc->map_type & BTRFS_BLOCK_GROUP_DUP);
6320 * Swap the last stripe stripes and reduce @nr_extra_stripes.
6321 * The extra stripe would still be there, but won't be accessed.
6323 if (first->physical > second->physical) {
6324 swap(second->physical, first->physical);
6325 swap(second->dev, first->dev);
6330 *num_stripes_ret = num_stripes + nr_extra_stripes;
6331 *max_errors_ret = max_errors + nr_extra_stripes;
6332 bioc->replace_nr_stripes = nr_extra_stripes;
6335 static u64 btrfs_max_io_len(struct btrfs_chunk_map *map, u64 offset,
6336 struct btrfs_io_geometry *io_geom)
6339 * Stripe_nr is the stripe where this block falls. stripe_offset is
6340 * the offset of this block in its stripe.
6342 io_geom->stripe_offset = offset & BTRFS_STRIPE_LEN_MASK;
6343 io_geom->stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6344 ASSERT(io_geom->stripe_offset < U32_MAX);
6346 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6347 unsigned long full_stripe_len =
6348 btrfs_stripe_nr_to_offset(nr_data_stripes(map));
6351 * For full stripe start, we use previously calculated
6352 * @stripe_nr. Align it to nr_data_stripes, then multiply with
6355 * By this we can avoid u64 division completely. And we have
6356 * to go rounddown(), not round_down(), as nr_data_stripes is
6357 * not ensured to be power of 2.
6359 io_geom->raid56_full_stripe_start = btrfs_stripe_nr_to_offset(
6360 rounddown(io_geom->stripe_nr, nr_data_stripes(map)));
6362 ASSERT(io_geom->raid56_full_stripe_start + full_stripe_len > offset);
6363 ASSERT(io_geom->raid56_full_stripe_start <= offset);
6365 * For writes to RAID56, allow to write a full stripe set, but
6366 * no straddling of stripe sets.
6368 if (io_geom->op == BTRFS_MAP_WRITE)
6369 return full_stripe_len - (offset - io_geom->raid56_full_stripe_start);
6373 * For other RAID types and for RAID56 reads, allow a single stripe (on
6376 if (map->type & BTRFS_BLOCK_GROUP_STRIPE_MASK)
6377 return BTRFS_STRIPE_LEN - io_geom->stripe_offset;
6381 static int set_io_stripe(struct btrfs_fs_info *fs_info, u64 logical,
6382 u64 *length, struct btrfs_io_stripe *dst,
6383 struct btrfs_chunk_map *map,
6384 struct btrfs_io_geometry *io_geom)
6386 dst->dev = map->stripes[io_geom->stripe_index].dev;
6388 if (io_geom->op == BTRFS_MAP_READ &&
6389 btrfs_need_stripe_tree_update(fs_info, map->type))
6390 return btrfs_get_raid_extent_offset(fs_info, logical, length,
6392 io_geom->stripe_index, dst);
6394 dst->physical = map->stripes[io_geom->stripe_index].physical +
6395 io_geom->stripe_offset +
6396 btrfs_stripe_nr_to_offset(io_geom->stripe_nr);
6400 static bool is_single_device_io(struct btrfs_fs_info *fs_info,
6401 const struct btrfs_io_stripe *smap,
6402 const struct btrfs_chunk_map *map,
6403 int num_alloc_stripes,
6404 enum btrfs_map_op op, int mirror_num)
6409 if (num_alloc_stripes != 1)
6412 if (btrfs_need_stripe_tree_update(fs_info, map->type) && op != BTRFS_MAP_READ)
6415 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) && mirror_num > 1)
6421 static void map_blocks_raid0(const struct btrfs_chunk_map *map,
6422 struct btrfs_io_geometry *io_geom)
6424 io_geom->stripe_index = io_geom->stripe_nr % map->num_stripes;
6425 io_geom->stripe_nr /= map->num_stripes;
6426 if (io_geom->op == BTRFS_MAP_READ)
6427 io_geom->mirror_num = 1;
6430 static void map_blocks_raid1(struct btrfs_fs_info *fs_info,
6431 struct btrfs_chunk_map *map,
6432 struct btrfs_io_geometry *io_geom,
6433 bool dev_replace_is_ongoing)
6435 if (io_geom->op != BTRFS_MAP_READ) {
6436 io_geom->num_stripes = map->num_stripes;
6440 if (io_geom->mirror_num) {
6441 io_geom->stripe_index = io_geom->mirror_num - 1;
6445 io_geom->stripe_index = find_live_mirror(fs_info, map, 0,
6446 dev_replace_is_ongoing);
6447 io_geom->mirror_num = io_geom->stripe_index + 1;
6450 static void map_blocks_dup(const struct btrfs_chunk_map *map,
6451 struct btrfs_io_geometry *io_geom)
6453 if (io_geom->op != BTRFS_MAP_READ) {
6454 io_geom->num_stripes = map->num_stripes;
6458 if (io_geom->mirror_num) {
6459 io_geom->stripe_index = io_geom->mirror_num - 1;
6463 io_geom->mirror_num = 1;
6466 static void map_blocks_raid10(struct btrfs_fs_info *fs_info,
6467 struct btrfs_chunk_map *map,
6468 struct btrfs_io_geometry *io_geom,
6469 bool dev_replace_is_ongoing)
6471 u32 factor = map->num_stripes / map->sub_stripes;
6472 int old_stripe_index;
6474 io_geom->stripe_index = (io_geom->stripe_nr % factor) * map->sub_stripes;
6475 io_geom->stripe_nr /= factor;
6477 if (io_geom->op != BTRFS_MAP_READ) {
6478 io_geom->num_stripes = map->sub_stripes;
6482 if (io_geom->mirror_num) {
6483 io_geom->stripe_index += io_geom->mirror_num - 1;
6487 old_stripe_index = io_geom->stripe_index;
6488 io_geom->stripe_index = find_live_mirror(fs_info, map,
6489 io_geom->stripe_index,
6490 dev_replace_is_ongoing);
6491 io_geom->mirror_num = io_geom->stripe_index - old_stripe_index + 1;
6494 static void map_blocks_raid56_write(struct btrfs_chunk_map *map,
6495 struct btrfs_io_geometry *io_geom,
6496 u64 logical, u64 *length)
6498 int data_stripes = nr_data_stripes(map);
6501 * Needs full stripe mapping.
6503 * Push stripe_nr back to the start of the full stripe For those cases
6504 * needing a full stripe, @stripe_nr is the full stripe number.
6506 * Originally we go raid56_full_stripe_start / full_stripe_len, but
6507 * that can be expensive. Here we just divide @stripe_nr with
6510 io_geom->stripe_nr /= data_stripes;
6512 /* RAID[56] write or recovery. Return all stripes */
6513 io_geom->num_stripes = map->num_stripes;
6514 io_geom->max_errors = btrfs_chunk_max_errors(map);
6516 /* Return the length to the full stripe end. */
6517 *length = min(logical + *length,
6518 io_geom->raid56_full_stripe_start + map->start +
6519 btrfs_stripe_nr_to_offset(data_stripes)) -
6521 io_geom->stripe_index = 0;
6522 io_geom->stripe_offset = 0;
6525 static void map_blocks_raid56_read(struct btrfs_chunk_map *map,
6526 struct btrfs_io_geometry *io_geom)
6528 int data_stripes = nr_data_stripes(map);
6530 ASSERT(io_geom->mirror_num <= 1);
6531 /* Just grab the data stripe directly. */
6532 io_geom->stripe_index = io_geom->stripe_nr % data_stripes;
6533 io_geom->stripe_nr /= data_stripes;
6535 /* We distribute the parity blocks across stripes. */
6536 io_geom->stripe_index =
6537 (io_geom->stripe_nr + io_geom->stripe_index) % map->num_stripes;
6539 if (io_geom->op == BTRFS_MAP_READ && io_geom->mirror_num < 1)
6540 io_geom->mirror_num = 1;
6543 static void map_blocks_single(const struct btrfs_chunk_map *map,
6544 struct btrfs_io_geometry *io_geom)
6546 io_geom->stripe_index = io_geom->stripe_nr % map->num_stripes;
6547 io_geom->stripe_nr /= map->num_stripes;
6548 io_geom->mirror_num = io_geom->stripe_index + 1;
6552 * Map one logical range to one or more physical ranges.
6554 * @length: (Mandatory) mapped length of this run.
6555 * One logical range can be split into different segments
6556 * due to factors like zones and RAID0/5/6/10 stripe
6559 * @bioc_ret: (Mandatory) returned btrfs_io_context structure.
6560 * which has one or more physical ranges (btrfs_io_stripe)
6562 * Caller should call btrfs_put_bioc() to free it after use.
6564 * @smap: (Optional) single physical range optimization.
6565 * If the map request can be fulfilled by one single
6566 * physical range, and this is parameter is not NULL,
6567 * then @bioc_ret would be NULL, and @smap would be
6570 * @mirror_num_ret: (Mandatory) returned mirror number if the original
6573 * Mirror number 0 means to choose any live mirrors.
6575 * For non-RAID56 profiles, non-zero mirror_num means
6576 * the Nth mirror. (e.g. mirror_num 1 means the first
6579 * For RAID56 profile, mirror 1 means rebuild from P and
6580 * the remaining data stripes.
6582 * For RAID6 profile, mirror > 2 means mark another
6583 * data/P stripe error and rebuild from the remaining
6586 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6587 u64 logical, u64 *length,
6588 struct btrfs_io_context **bioc_ret,
6589 struct btrfs_io_stripe *smap, int *mirror_num_ret)
6591 struct btrfs_chunk_map *map;
6592 struct btrfs_io_geometry io_geom = { 0 };
6597 struct btrfs_io_context *bioc = NULL;
6598 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6599 int dev_replace_is_ongoing = 0;
6600 u16 num_alloc_stripes;
6605 io_geom.mirror_num = (mirror_num_ret ? *mirror_num_ret : 0);
6606 io_geom.num_stripes = 1;
6607 io_geom.stripe_index = 0;
6610 num_copies = btrfs_num_copies(fs_info, logical, fs_info->sectorsize);
6611 if (io_geom.mirror_num > num_copies)
6614 map = btrfs_get_chunk_map(fs_info, logical, *length);
6616 return PTR_ERR(map);
6618 map_offset = logical - map->start;
6619 io_geom.raid56_full_stripe_start = (u64)-1;
6620 max_len = btrfs_max_io_len(map, map_offset, &io_geom);
6621 *length = min_t(u64, map->chunk_len - map_offset, max_len);
6623 down_read(&dev_replace->rwsem);
6624 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6626 * Hold the semaphore for read during the whole operation, write is
6627 * requested at commit time but must wait.
6629 if (!dev_replace_is_ongoing)
6630 up_read(&dev_replace->rwsem);
6632 switch (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6633 case BTRFS_BLOCK_GROUP_RAID0:
6634 map_blocks_raid0(map, &io_geom);
6636 case BTRFS_BLOCK_GROUP_RAID1:
6637 case BTRFS_BLOCK_GROUP_RAID1C3:
6638 case BTRFS_BLOCK_GROUP_RAID1C4:
6639 map_blocks_raid1(fs_info, map, &io_geom, dev_replace_is_ongoing);
6641 case BTRFS_BLOCK_GROUP_DUP:
6642 map_blocks_dup(map, &io_geom);
6644 case BTRFS_BLOCK_GROUP_RAID10:
6645 map_blocks_raid10(fs_info, map, &io_geom, dev_replace_is_ongoing);
6647 case BTRFS_BLOCK_GROUP_RAID5:
6648 case BTRFS_BLOCK_GROUP_RAID6:
6649 if (op != BTRFS_MAP_READ || io_geom.mirror_num > 1)
6650 map_blocks_raid56_write(map, &io_geom, logical, length);
6652 map_blocks_raid56_read(map, &io_geom);
6656 * After this, stripe_nr is the number of stripes on this
6657 * device we have to walk to find the data, and stripe_index is
6658 * the number of our device in the stripe array
6660 map_blocks_single(map, &io_geom);
6663 if (io_geom.stripe_index >= map->num_stripes) {
6665 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6666 io_geom.stripe_index, map->num_stripes);
6671 num_alloc_stripes = io_geom.num_stripes;
6672 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6673 op != BTRFS_MAP_READ)
6675 * For replace case, we need to add extra stripes for extra
6676 * duplicated stripes.
6678 * For both WRITE and GET_READ_MIRRORS, we may have at most
6679 * 2 more stripes (DUP types, otherwise 1).
6681 num_alloc_stripes += 2;
6684 * If this I/O maps to a single device, try to return the device and
6685 * physical block information on the stack instead of allocating an
6686 * I/O context structure.
6688 if (is_single_device_io(fs_info, smap, map, num_alloc_stripes, op,
6689 io_geom.mirror_num)) {
6690 ret = set_io_stripe(fs_info, logical, length, smap, map, &io_geom);
6692 *mirror_num_ret = io_geom.mirror_num;
6697 bioc = alloc_btrfs_io_context(fs_info, logical, num_alloc_stripes);
6702 bioc->map_type = map->type;
6705 * For RAID56 full map, we need to make sure the stripes[] follows the
6706 * rule that data stripes are all ordered, then followed with P and Q
6709 * It's still mostly the same as other profiles, just with extra rotation.
6711 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
6712 (op != BTRFS_MAP_READ || io_geom.mirror_num > 1)) {
6714 * For RAID56 @stripe_nr is already the number of full stripes
6715 * before us, which is also the rotation value (needs to modulo
6716 * with num_stripes).
6718 * In this case, we just add @stripe_nr with @i, then do the
6719 * modulo, to reduce one modulo call.
6721 bioc->full_stripe_logical = map->start +
6722 btrfs_stripe_nr_to_offset(io_geom.stripe_nr *
6723 nr_data_stripes(map));
6724 for (int i = 0; i < io_geom.num_stripes; i++) {
6725 struct btrfs_io_stripe *dst = &bioc->stripes[i];
6728 stripe_index = (i + io_geom.stripe_nr) % io_geom.num_stripes;
6729 dst->dev = map->stripes[stripe_index].dev;
6731 map->stripes[stripe_index].physical +
6732 io_geom.stripe_offset +
6733 btrfs_stripe_nr_to_offset(io_geom.stripe_nr);
6737 * For all other non-RAID56 profiles, just copy the target
6738 * stripe into the bioc.
6740 for (i = 0; i < io_geom.num_stripes; i++) {
6741 ret = set_io_stripe(fs_info, logical, length,
6742 &bioc->stripes[i], map, &io_geom);
6745 io_geom.stripe_index++;
6751 btrfs_put_bioc(bioc);
6755 if (op != BTRFS_MAP_READ)
6756 io_geom.max_errors = btrfs_chunk_max_errors(map);
6758 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6759 op != BTRFS_MAP_READ) {
6760 handle_ops_on_dev_replace(op, bioc, dev_replace, logical,
6761 &io_geom.num_stripes, &io_geom.max_errors);
6765 bioc->num_stripes = io_geom.num_stripes;
6766 bioc->max_errors = io_geom.max_errors;
6767 bioc->mirror_num = io_geom.mirror_num;
6770 if (dev_replace_is_ongoing) {
6771 lockdep_assert_held(&dev_replace->rwsem);
6772 /* Unlock and let waiting writers proceed */
6773 up_read(&dev_replace->rwsem);
6775 btrfs_free_chunk_map(map);
6779 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args *args,
6780 const struct btrfs_fs_devices *fs_devices)
6782 if (args->fsid == NULL)
6784 if (memcmp(fs_devices->metadata_uuid, args->fsid, BTRFS_FSID_SIZE) == 0)
6789 static bool dev_args_match_device(const struct btrfs_dev_lookup_args *args,
6790 const struct btrfs_device *device)
6792 if (args->missing) {
6793 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) &&
6799 if (device->devid != args->devid)
6801 if (args->uuid && memcmp(device->uuid, args->uuid, BTRFS_UUID_SIZE) != 0)
6807 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6810 * If devid and uuid are both specified, the match must be exact, otherwise
6811 * only devid is used.
6813 struct btrfs_device *btrfs_find_device(const struct btrfs_fs_devices *fs_devices,
6814 const struct btrfs_dev_lookup_args *args)
6816 struct btrfs_device *device;
6817 struct btrfs_fs_devices *seed_devs;
6819 if (dev_args_match_fs_devices(args, fs_devices)) {
6820 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6821 if (dev_args_match_device(args, device))
6826 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6827 if (!dev_args_match_fs_devices(args, seed_devs))
6829 list_for_each_entry(device, &seed_devs->devices, dev_list) {
6830 if (dev_args_match_device(args, device))
6838 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6839 u64 devid, u8 *dev_uuid)
6841 struct btrfs_device *device;
6842 unsigned int nofs_flag;
6845 * We call this under the chunk_mutex, so we want to use NOFS for this
6846 * allocation, however we don't want to change btrfs_alloc_device() to
6847 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6851 nofs_flag = memalloc_nofs_save();
6852 device = btrfs_alloc_device(NULL, &devid, dev_uuid, NULL);
6853 memalloc_nofs_restore(nofs_flag);
6857 list_add(&device->dev_list, &fs_devices->devices);
6858 device->fs_devices = fs_devices;
6859 fs_devices->num_devices++;
6861 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6862 fs_devices->missing_devices++;
6868 * Allocate new device struct, set up devid and UUID.
6870 * @fs_info: used only for generating a new devid, can be NULL if
6871 * devid is provided (i.e. @devid != NULL).
6872 * @devid: a pointer to devid for this device. If NULL a new devid
6874 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6876 * @path: a pointer to device path if available, NULL otherwise.
6878 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6879 * on error. Returned struct is not linked onto any lists and must be
6880 * destroyed with btrfs_free_device.
6882 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6883 const u64 *devid, const u8 *uuid,
6886 struct btrfs_device *dev;
6889 if (WARN_ON(!devid && !fs_info))
6890 return ERR_PTR(-EINVAL);
6892 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
6894 return ERR_PTR(-ENOMEM);
6896 INIT_LIST_HEAD(&dev->dev_list);
6897 INIT_LIST_HEAD(&dev->dev_alloc_list);
6898 INIT_LIST_HEAD(&dev->post_commit_list);
6900 atomic_set(&dev->dev_stats_ccnt, 0);
6901 btrfs_device_data_ordered_init(dev);
6902 extent_io_tree_init(fs_info, &dev->alloc_state, IO_TREE_DEVICE_ALLOC_STATE);
6909 ret = find_next_devid(fs_info, &tmp);
6911 btrfs_free_device(dev);
6912 return ERR_PTR(ret);
6918 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6920 generate_random_uuid(dev->uuid);
6923 struct rcu_string *name;
6925 name = rcu_string_strdup(path, GFP_KERNEL);
6927 btrfs_free_device(dev);
6928 return ERR_PTR(-ENOMEM);
6930 rcu_assign_pointer(dev->name, name);
6936 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6937 u64 devid, u8 *uuid, bool error)
6940 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6943 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6947 u64 btrfs_calc_stripe_length(const struct btrfs_chunk_map *map)
6949 const int data_stripes = calc_data_stripes(map->type, map->num_stripes);
6951 return div_u64(map->chunk_len, data_stripes);
6954 #if BITS_PER_LONG == 32
6956 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
6957 * can't be accessed on 32bit systems.
6959 * This function do mount time check to reject the fs if it already has
6960 * metadata chunk beyond that limit.
6962 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6963 u64 logical, u64 length, u64 type)
6965 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6968 if (logical + length < MAX_LFS_FILESIZE)
6971 btrfs_err_32bit_limit(fs_info);
6976 * This is to give early warning for any metadata chunk reaching
6977 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
6978 * Although we can still access the metadata, it's not going to be possible
6979 * once the limit is reached.
6981 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6982 u64 logical, u64 length, u64 type)
6984 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6987 if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6990 btrfs_warn_32bit_limit(fs_info);
6994 static struct btrfs_device *handle_missing_device(struct btrfs_fs_info *fs_info,
6995 u64 devid, u8 *uuid)
6997 struct btrfs_device *dev;
6999 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7000 btrfs_report_missing_device(fs_info, devid, uuid, true);
7001 return ERR_PTR(-ENOENT);
7004 dev = add_missing_dev(fs_info->fs_devices, devid, uuid);
7006 btrfs_err(fs_info, "failed to init missing device %llu: %ld",
7007 devid, PTR_ERR(dev));
7010 btrfs_report_missing_device(fs_info, devid, uuid, false);
7015 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
7016 struct btrfs_chunk *chunk)
7018 BTRFS_DEV_LOOKUP_ARGS(args);
7019 struct btrfs_fs_info *fs_info = leaf->fs_info;
7020 struct btrfs_chunk_map *map;
7025 u8 uuid[BTRFS_UUID_SIZE];
7031 logical = key->offset;
7032 length = btrfs_chunk_length(leaf, chunk);
7033 type = btrfs_chunk_type(leaf, chunk);
7034 index = btrfs_bg_flags_to_raid_index(type);
7035 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
7037 #if BITS_PER_LONG == 32
7038 ret = check_32bit_meta_chunk(fs_info, logical, length, type);
7041 warn_32bit_meta_chunk(fs_info, logical, length, type);
7045 * Only need to verify chunk item if we're reading from sys chunk array,
7046 * as chunk item in tree block is already verified by tree-checker.
7048 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
7049 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
7054 map = btrfs_find_chunk_map(fs_info, logical, 1);
7056 /* already mapped? */
7057 if (map && map->start <= logical && map->start + map->chunk_len > logical) {
7058 btrfs_free_chunk_map(map);
7061 btrfs_free_chunk_map(map);
7064 map = btrfs_alloc_chunk_map(num_stripes, GFP_NOFS);
7068 map->start = logical;
7069 map->chunk_len = length;
7070 map->num_stripes = num_stripes;
7071 map->io_width = btrfs_chunk_io_width(leaf, chunk);
7072 map->io_align = btrfs_chunk_io_align(leaf, chunk);
7075 * We can't use the sub_stripes value, as for profiles other than
7076 * RAID10, they may have 0 as sub_stripes for filesystems created by
7077 * older mkfs (<v5.4).
7078 * In that case, it can cause divide-by-zero errors later.
7079 * Since currently sub_stripes is fixed for each profile, let's
7080 * use the trusted value instead.
7082 map->sub_stripes = btrfs_raid_array[index].sub_stripes;
7083 map->verified_stripes = 0;
7084 map->stripe_size = btrfs_calc_stripe_length(map);
7085 for (i = 0; i < num_stripes; i++) {
7086 map->stripes[i].physical =
7087 btrfs_stripe_offset_nr(leaf, chunk, i);
7088 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
7090 read_extent_buffer(leaf, uuid, (unsigned long)
7091 btrfs_stripe_dev_uuid_nr(chunk, i),
7094 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, &args);
7095 if (!map->stripes[i].dev) {
7096 map->stripes[i].dev = handle_missing_device(fs_info,
7098 if (IS_ERR(map->stripes[i].dev)) {
7099 ret = PTR_ERR(map->stripes[i].dev);
7100 btrfs_free_chunk_map(map);
7105 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
7106 &(map->stripes[i].dev->dev_state));
7109 ret = btrfs_add_chunk_map(fs_info, map);
7112 "failed to add chunk map, start=%llu len=%llu: %d",
7113 map->start, map->chunk_len, ret);
7119 static void fill_device_from_item(struct extent_buffer *leaf,
7120 struct btrfs_dev_item *dev_item,
7121 struct btrfs_device *device)
7125 device->devid = btrfs_device_id(leaf, dev_item);
7126 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7127 device->total_bytes = device->disk_total_bytes;
7128 device->commit_total_bytes = device->disk_total_bytes;
7129 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
7130 device->commit_bytes_used = device->bytes_used;
7131 device->type = btrfs_device_type(leaf, dev_item);
7132 device->io_align = btrfs_device_io_align(leaf, dev_item);
7133 device->io_width = btrfs_device_io_width(leaf, dev_item);
7134 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
7135 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
7136 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
7138 ptr = btrfs_device_uuid(dev_item);
7139 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
7142 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
7145 struct btrfs_fs_devices *fs_devices;
7148 lockdep_assert_held(&uuid_mutex);
7151 /* This will match only for multi-device seed fs */
7152 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
7153 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7157 fs_devices = find_fsid(fsid, NULL);
7159 if (!btrfs_test_opt(fs_info, DEGRADED))
7160 return ERR_PTR(-ENOENT);
7162 fs_devices = alloc_fs_devices(fsid);
7163 if (IS_ERR(fs_devices))
7166 fs_devices->seeding = true;
7167 fs_devices->opened = 1;
7172 * Upon first call for a seed fs fsid, just create a private copy of the
7173 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7175 fs_devices = clone_fs_devices(fs_devices);
7176 if (IS_ERR(fs_devices))
7179 ret = open_fs_devices(fs_devices, BLK_OPEN_READ, fs_info->bdev_holder);
7181 free_fs_devices(fs_devices);
7182 return ERR_PTR(ret);
7185 if (!fs_devices->seeding) {
7186 close_fs_devices(fs_devices);
7187 free_fs_devices(fs_devices);
7188 return ERR_PTR(-EINVAL);
7191 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7196 static int read_one_dev(struct extent_buffer *leaf,
7197 struct btrfs_dev_item *dev_item)
7199 BTRFS_DEV_LOOKUP_ARGS(args);
7200 struct btrfs_fs_info *fs_info = leaf->fs_info;
7201 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7202 struct btrfs_device *device;
7205 u8 fs_uuid[BTRFS_FSID_SIZE];
7206 u8 dev_uuid[BTRFS_UUID_SIZE];
7208 devid = btrfs_device_id(leaf, dev_item);
7210 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7212 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7214 args.uuid = dev_uuid;
7215 args.fsid = fs_uuid;
7217 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7218 fs_devices = open_seed_devices(fs_info, fs_uuid);
7219 if (IS_ERR(fs_devices))
7220 return PTR_ERR(fs_devices);
7223 device = btrfs_find_device(fs_info->fs_devices, &args);
7225 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7226 btrfs_report_missing_device(fs_info, devid,
7231 device = add_missing_dev(fs_devices, devid, dev_uuid);
7232 if (IS_ERR(device)) {
7234 "failed to add missing dev %llu: %ld",
7235 devid, PTR_ERR(device));
7236 return PTR_ERR(device);
7238 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7240 if (!device->bdev) {
7241 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7242 btrfs_report_missing_device(fs_info,
7243 devid, dev_uuid, true);
7246 btrfs_report_missing_device(fs_info, devid,
7250 if (!device->bdev &&
7251 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7253 * this happens when a device that was properly setup
7254 * in the device info lists suddenly goes bad.
7255 * device->bdev is NULL, and so we have to set
7256 * device->missing to one here
7258 device->fs_devices->missing_devices++;
7259 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7262 /* Move the device to its own fs_devices */
7263 if (device->fs_devices != fs_devices) {
7264 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7265 &device->dev_state));
7267 list_move(&device->dev_list, &fs_devices->devices);
7268 device->fs_devices->num_devices--;
7269 fs_devices->num_devices++;
7271 device->fs_devices->missing_devices--;
7272 fs_devices->missing_devices++;
7274 device->fs_devices = fs_devices;
7278 if (device->fs_devices != fs_info->fs_devices) {
7279 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7280 if (device->generation !=
7281 btrfs_device_generation(leaf, dev_item))
7285 fill_device_from_item(leaf, dev_item, device);
7287 u64 max_total_bytes = bdev_nr_bytes(device->bdev);
7289 if (device->total_bytes > max_total_bytes) {
7291 "device total_bytes should be at most %llu but found %llu",
7292 max_total_bytes, device->total_bytes);
7296 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7297 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7298 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7299 device->fs_devices->total_rw_bytes += device->total_bytes;
7300 atomic64_add(device->total_bytes - device->bytes_used,
7301 &fs_info->free_chunk_space);
7307 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7309 struct btrfs_super_block *super_copy = fs_info->super_copy;
7310 struct extent_buffer *sb;
7311 struct btrfs_disk_key *disk_key;
7312 struct btrfs_chunk *chunk;
7314 unsigned long sb_array_offset;
7321 struct btrfs_key key;
7323 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7326 * We allocated a dummy extent, just to use extent buffer accessors.
7327 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
7328 * that's fine, we will not go beyond system chunk array anyway.
7330 sb = alloc_dummy_extent_buffer(fs_info, BTRFS_SUPER_INFO_OFFSET);
7333 set_extent_buffer_uptodate(sb);
7335 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7336 array_size = btrfs_super_sys_array_size(super_copy);
7338 array_ptr = super_copy->sys_chunk_array;
7339 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7342 while (cur_offset < array_size) {
7343 disk_key = (struct btrfs_disk_key *)array_ptr;
7344 len = sizeof(*disk_key);
7345 if (cur_offset + len > array_size)
7346 goto out_short_read;
7348 btrfs_disk_key_to_cpu(&key, disk_key);
7351 sb_array_offset += len;
7354 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
7356 "unexpected item type %u in sys_array at offset %u",
7357 (u32)key.type, cur_offset);
7362 chunk = (struct btrfs_chunk *)sb_array_offset;
7364 * At least one btrfs_chunk with one stripe must be present,
7365 * exact stripe count check comes afterwards
7367 len = btrfs_chunk_item_size(1);
7368 if (cur_offset + len > array_size)
7369 goto out_short_read;
7371 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7374 "invalid number of stripes %u in sys_array at offset %u",
7375 num_stripes, cur_offset);
7380 type = btrfs_chunk_type(sb, chunk);
7381 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7383 "invalid chunk type %llu in sys_array at offset %u",
7389 len = btrfs_chunk_item_size(num_stripes);
7390 if (cur_offset + len > array_size)
7391 goto out_short_read;
7393 ret = read_one_chunk(&key, sb, chunk);
7398 sb_array_offset += len;
7401 clear_extent_buffer_uptodate(sb);
7402 free_extent_buffer_stale(sb);
7406 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7408 clear_extent_buffer_uptodate(sb);
7409 free_extent_buffer_stale(sb);
7414 * Check if all chunks in the fs are OK for read-write degraded mount
7416 * If the @failing_dev is specified, it's accounted as missing.
7418 * Return true if all chunks meet the minimal RW mount requirements.
7419 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7421 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7422 struct btrfs_device *failing_dev)
7424 struct btrfs_chunk_map *map;
7428 map = btrfs_find_chunk_map(fs_info, 0, U64_MAX);
7429 /* No chunk at all? Return false anyway */
7440 btrfs_get_num_tolerated_disk_barrier_failures(
7442 for (i = 0; i < map->num_stripes; i++) {
7443 struct btrfs_device *dev = map->stripes[i].dev;
7445 if (!dev || !dev->bdev ||
7446 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7447 dev->last_flush_error)
7449 else if (failing_dev && failing_dev == dev)
7452 if (missing > max_tolerated) {
7455 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7456 map->start, missing, max_tolerated);
7457 btrfs_free_chunk_map(map);
7461 next_start = map->start + map->chunk_len;
7462 btrfs_free_chunk_map(map);
7464 map = btrfs_find_chunk_map(fs_info, next_start, U64_MAX - next_start);
7470 static void readahead_tree_node_children(struct extent_buffer *node)
7473 const int nr_items = btrfs_header_nritems(node);
7475 for (i = 0; i < nr_items; i++)
7476 btrfs_readahead_node_child(node, i);
7479 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7481 struct btrfs_root *root = fs_info->chunk_root;
7482 struct btrfs_path *path;
7483 struct extent_buffer *leaf;
7484 struct btrfs_key key;
7485 struct btrfs_key found_key;
7490 u64 last_ra_node = 0;
7492 path = btrfs_alloc_path();
7497 * uuid_mutex is needed only if we are mounting a sprout FS
7498 * otherwise we don't need it.
7500 mutex_lock(&uuid_mutex);
7503 * It is possible for mount and umount to race in such a way that
7504 * we execute this code path, but open_fs_devices failed to clear
7505 * total_rw_bytes. We certainly want it cleared before reading the
7506 * device items, so clear it here.
7508 fs_info->fs_devices->total_rw_bytes = 0;
7511 * Lockdep complains about possible circular locking dependency between
7512 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7513 * used for freeze procection of a fs (struct super_block.s_writers),
7514 * which we take when starting a transaction, and extent buffers of the
7515 * chunk tree if we call read_one_dev() while holding a lock on an
7516 * extent buffer of the chunk tree. Since we are mounting the filesystem
7517 * and at this point there can't be any concurrent task modifying the
7518 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7520 ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
7521 path->skip_locking = 1;
7524 * Read all device items, and then all the chunk items. All
7525 * device items are found before any chunk item (their object id
7526 * is smaller than the lowest possible object id for a chunk
7527 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7529 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7532 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
7533 struct extent_buffer *node = path->nodes[1];
7535 leaf = path->nodes[0];
7536 slot = path->slots[0];
7539 if (last_ra_node != node->start) {
7540 readahead_tree_node_children(node);
7541 last_ra_node = node->start;
7544 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7545 struct btrfs_dev_item *dev_item;
7546 dev_item = btrfs_item_ptr(leaf, slot,
7547 struct btrfs_dev_item);
7548 ret = read_one_dev(leaf, dev_item);
7552 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7553 struct btrfs_chunk *chunk;
7556 * We are only called at mount time, so no need to take
7557 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7558 * we always lock first fs_info->chunk_mutex before
7559 * acquiring any locks on the chunk tree. This is a
7560 * requirement for chunk allocation, see the comment on
7561 * top of btrfs_chunk_alloc() for details.
7563 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7564 ret = read_one_chunk(&found_key, leaf, chunk);
7569 /* Catch error found during iteration */
7576 * After loading chunk tree, we've got all device information,
7577 * do another round of validation checks.
7579 if (total_dev != fs_info->fs_devices->total_devices) {
7581 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7582 btrfs_super_num_devices(fs_info->super_copy),
7584 fs_info->fs_devices->total_devices = total_dev;
7585 btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
7587 if (btrfs_super_total_bytes(fs_info->super_copy) <
7588 fs_info->fs_devices->total_rw_bytes) {
7590 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7591 btrfs_super_total_bytes(fs_info->super_copy),
7592 fs_info->fs_devices->total_rw_bytes);
7598 mutex_unlock(&uuid_mutex);
7600 btrfs_free_path(path);
7604 int btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7606 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7607 struct btrfs_device *device;
7610 fs_devices->fs_info = fs_info;
7612 mutex_lock(&fs_devices->device_list_mutex);
7613 list_for_each_entry(device, &fs_devices->devices, dev_list)
7614 device->fs_info = fs_info;
7616 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7617 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7618 device->fs_info = fs_info;
7619 ret = btrfs_get_dev_zone_info(device, false);
7624 seed_devs->fs_info = fs_info;
7626 mutex_unlock(&fs_devices->device_list_mutex);
7631 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7632 const struct btrfs_dev_stats_item *ptr,
7637 read_extent_buffer(eb, &val,
7638 offsetof(struct btrfs_dev_stats_item, values) +
7639 ((unsigned long)ptr) + (index * sizeof(u64)),
7644 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7645 struct btrfs_dev_stats_item *ptr,
7648 write_extent_buffer(eb, &val,
7649 offsetof(struct btrfs_dev_stats_item, values) +
7650 ((unsigned long)ptr) + (index * sizeof(u64)),
7654 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7655 struct btrfs_path *path)
7657 struct btrfs_dev_stats_item *ptr;
7658 struct extent_buffer *eb;
7659 struct btrfs_key key;
7663 if (!device->fs_info->dev_root)
7666 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7667 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7668 key.offset = device->devid;
7669 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7671 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7672 btrfs_dev_stat_set(device, i, 0);
7673 device->dev_stats_valid = 1;
7674 btrfs_release_path(path);
7675 return ret < 0 ? ret : 0;
7677 slot = path->slots[0];
7678 eb = path->nodes[0];
7679 item_size = btrfs_item_size(eb, slot);
7681 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7683 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7684 if (item_size >= (1 + i) * sizeof(__le64))
7685 btrfs_dev_stat_set(device, i,
7686 btrfs_dev_stats_value(eb, ptr, i));
7688 btrfs_dev_stat_set(device, i, 0);
7691 device->dev_stats_valid = 1;
7692 btrfs_dev_stat_print_on_load(device);
7693 btrfs_release_path(path);
7698 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7700 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7701 struct btrfs_device *device;
7702 struct btrfs_path *path = NULL;
7705 path = btrfs_alloc_path();
7709 mutex_lock(&fs_devices->device_list_mutex);
7710 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7711 ret = btrfs_device_init_dev_stats(device, path);
7715 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7716 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7717 ret = btrfs_device_init_dev_stats(device, path);
7723 mutex_unlock(&fs_devices->device_list_mutex);
7725 btrfs_free_path(path);
7729 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7730 struct btrfs_device *device)
7732 struct btrfs_fs_info *fs_info = trans->fs_info;
7733 struct btrfs_root *dev_root = fs_info->dev_root;
7734 struct btrfs_path *path;
7735 struct btrfs_key key;
7736 struct extent_buffer *eb;
7737 struct btrfs_dev_stats_item *ptr;
7741 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7742 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7743 key.offset = device->devid;
7745 path = btrfs_alloc_path();
7748 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7750 btrfs_warn_in_rcu(fs_info,
7751 "error %d while searching for dev_stats item for device %s",
7752 ret, btrfs_dev_name(device));
7757 btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7758 /* need to delete old one and insert a new one */
7759 ret = btrfs_del_item(trans, dev_root, path);
7761 btrfs_warn_in_rcu(fs_info,
7762 "delete too small dev_stats item for device %s failed %d",
7763 btrfs_dev_name(device), ret);
7770 /* need to insert a new item */
7771 btrfs_release_path(path);
7772 ret = btrfs_insert_empty_item(trans, dev_root, path,
7773 &key, sizeof(*ptr));
7775 btrfs_warn_in_rcu(fs_info,
7776 "insert dev_stats item for device %s failed %d",
7777 btrfs_dev_name(device), ret);
7782 eb = path->nodes[0];
7783 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7784 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7785 btrfs_set_dev_stats_value(eb, ptr, i,
7786 btrfs_dev_stat_read(device, i));
7787 btrfs_mark_buffer_dirty(trans, eb);
7790 btrfs_free_path(path);
7795 * called from commit_transaction. Writes all changed device stats to disk.
7797 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7799 struct btrfs_fs_info *fs_info = trans->fs_info;
7800 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7801 struct btrfs_device *device;
7805 mutex_lock(&fs_devices->device_list_mutex);
7806 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7807 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7808 if (!device->dev_stats_valid || stats_cnt == 0)
7813 * There is a LOAD-LOAD control dependency between the value of
7814 * dev_stats_ccnt and updating the on-disk values which requires
7815 * reading the in-memory counters. Such control dependencies
7816 * require explicit read memory barriers.
7818 * This memory barriers pairs with smp_mb__before_atomic in
7819 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7820 * barrier implied by atomic_xchg in
7821 * btrfs_dev_stats_read_and_reset
7825 ret = update_dev_stat_item(trans, device);
7827 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7829 mutex_unlock(&fs_devices->device_list_mutex);
7834 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7836 btrfs_dev_stat_inc(dev, index);
7838 if (!dev->dev_stats_valid)
7840 btrfs_err_rl_in_rcu(dev->fs_info,
7841 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7842 btrfs_dev_name(dev),
7843 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7844 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7845 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7846 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7847 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7850 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7854 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7855 if (btrfs_dev_stat_read(dev, i) != 0)
7857 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7858 return; /* all values == 0, suppress message */
7860 btrfs_info_in_rcu(dev->fs_info,
7861 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7862 btrfs_dev_name(dev),
7863 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7864 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7865 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7866 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7867 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7870 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7871 struct btrfs_ioctl_get_dev_stats *stats)
7873 BTRFS_DEV_LOOKUP_ARGS(args);
7874 struct btrfs_device *dev;
7875 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7878 mutex_lock(&fs_devices->device_list_mutex);
7879 args.devid = stats->devid;
7880 dev = btrfs_find_device(fs_info->fs_devices, &args);
7881 mutex_unlock(&fs_devices->device_list_mutex);
7884 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7886 } else if (!dev->dev_stats_valid) {
7887 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7889 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7890 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7891 if (stats->nr_items > i)
7893 btrfs_dev_stat_read_and_reset(dev, i);
7895 btrfs_dev_stat_set(dev, i, 0);
7897 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7898 current->comm, task_pid_nr(current));
7900 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7901 if (stats->nr_items > i)
7902 stats->values[i] = btrfs_dev_stat_read(dev, i);
7904 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7905 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7910 * Update the size and bytes used for each device where it changed. This is
7911 * delayed since we would otherwise get errors while writing out the
7914 * Must be invoked during transaction commit.
7916 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7918 struct btrfs_device *curr, *next;
7920 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7922 if (list_empty(&trans->dev_update_list))
7926 * We don't need the device_list_mutex here. This list is owned by the
7927 * transaction and the transaction must complete before the device is
7930 mutex_lock(&trans->fs_info->chunk_mutex);
7931 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7933 list_del_init(&curr->post_commit_list);
7934 curr->commit_total_bytes = curr->disk_total_bytes;
7935 curr->commit_bytes_used = curr->bytes_used;
7937 mutex_unlock(&trans->fs_info->chunk_mutex);
7941 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7943 int btrfs_bg_type_to_factor(u64 flags)
7945 const int index = btrfs_bg_flags_to_raid_index(flags);
7947 return btrfs_raid_array[index].ncopies;
7952 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7953 u64 chunk_offset, u64 devid,
7954 u64 physical_offset, u64 physical_len)
7956 struct btrfs_dev_lookup_args args = { .devid = devid };
7957 struct btrfs_chunk_map *map;
7958 struct btrfs_device *dev;
7964 map = btrfs_find_chunk_map(fs_info, chunk_offset, 1);
7967 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7968 physical_offset, devid);
7973 stripe_len = btrfs_calc_stripe_length(map);
7974 if (physical_len != stripe_len) {
7976 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7977 physical_offset, devid, map->start, physical_len,
7984 * Very old mkfs.btrfs (before v4.1) will not respect the reserved
7985 * space. Although kernel can handle it without problem, better to warn
7988 if (physical_offset < BTRFS_DEVICE_RANGE_RESERVED)
7990 "devid %llu physical %llu len %llu inside the reserved space",
7991 devid, physical_offset, physical_len);
7993 for (i = 0; i < map->num_stripes; i++) {
7994 if (map->stripes[i].dev->devid == devid &&
7995 map->stripes[i].physical == physical_offset) {
7997 if (map->verified_stripes >= map->num_stripes) {
7999 "too many dev extents for chunk %llu found",
8004 map->verified_stripes++;
8010 "dev extent physical offset %llu devid %llu has no corresponding chunk",
8011 physical_offset, devid);
8015 /* Make sure no dev extent is beyond device boundary */
8016 dev = btrfs_find_device(fs_info->fs_devices, &args);
8018 btrfs_err(fs_info, "failed to find devid %llu", devid);
8023 if (physical_offset + physical_len > dev->disk_total_bytes) {
8025 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
8026 devid, physical_offset, physical_len,
8027 dev->disk_total_bytes);
8032 if (dev->zone_info) {
8033 u64 zone_size = dev->zone_info->zone_size;
8035 if (!IS_ALIGNED(physical_offset, zone_size) ||
8036 !IS_ALIGNED(physical_len, zone_size)) {
8038 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
8039 devid, physical_offset, physical_len);
8046 btrfs_free_chunk_map(map);
8050 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
8052 struct rb_node *node;
8055 read_lock(&fs_info->mapping_tree_lock);
8056 for (node = rb_first_cached(&fs_info->mapping_tree); node; node = rb_next(node)) {
8057 struct btrfs_chunk_map *map;
8059 map = rb_entry(node, struct btrfs_chunk_map, rb_node);
8060 if (map->num_stripes != map->verified_stripes) {
8062 "chunk %llu has missing dev extent, have %d expect %d",
8063 map->start, map->verified_stripes, map->num_stripes);
8069 read_unlock(&fs_info->mapping_tree_lock);
8074 * Ensure that all dev extents are mapped to correct chunk, otherwise
8075 * later chunk allocation/free would cause unexpected behavior.
8077 * NOTE: This will iterate through the whole device tree, which should be of
8078 * the same size level as the chunk tree. This slightly increases mount time.
8080 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
8082 struct btrfs_path *path;
8083 struct btrfs_root *root = fs_info->dev_root;
8084 struct btrfs_key key;
8086 u64 prev_dev_ext_end = 0;
8090 * We don't have a dev_root because we mounted with ignorebadroots and
8091 * failed to load the root, so we want to skip the verification in this
8094 * However if the dev root is fine, but the tree itself is corrupted
8095 * we'd still fail to mount. This verification is only to make sure
8096 * writes can happen safely, so instead just bypass this check
8097 * completely in the case of IGNOREBADROOTS.
8099 if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
8103 key.type = BTRFS_DEV_EXTENT_KEY;
8106 path = btrfs_alloc_path();
8110 path->reada = READA_FORWARD;
8111 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8115 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8116 ret = btrfs_next_leaf(root, path);
8119 /* No dev extents at all? Not good */
8126 struct extent_buffer *leaf = path->nodes[0];
8127 struct btrfs_dev_extent *dext;
8128 int slot = path->slots[0];
8130 u64 physical_offset;
8134 btrfs_item_key_to_cpu(leaf, &key, slot);
8135 if (key.type != BTRFS_DEV_EXTENT_KEY)
8137 devid = key.objectid;
8138 physical_offset = key.offset;
8140 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
8141 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
8142 physical_len = btrfs_dev_extent_length(leaf, dext);
8144 /* Check if this dev extent overlaps with the previous one */
8145 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
8147 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8148 devid, physical_offset, prev_dev_ext_end);
8153 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8154 physical_offset, physical_len);
8158 prev_dev_ext_end = physical_offset + physical_len;
8160 ret = btrfs_next_item(root, path);
8169 /* Ensure all chunks have corresponding dev extents */
8170 ret = verify_chunk_dev_extent_mapping(fs_info);
8172 btrfs_free_path(path);
8177 * Check whether the given block group or device is pinned by any inode being
8178 * used as a swapfile.
8180 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8182 struct btrfs_swapfile_pin *sp;
8183 struct rb_node *node;
8185 spin_lock(&fs_info->swapfile_pins_lock);
8186 node = fs_info->swapfile_pins.rb_node;
8188 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8190 node = node->rb_left;
8191 else if (ptr > sp->ptr)
8192 node = node->rb_right;
8196 spin_unlock(&fs_info->swapfile_pins_lock);
8197 return node != NULL;
8200 static int relocating_repair_kthread(void *data)
8202 struct btrfs_block_group *cache = data;
8203 struct btrfs_fs_info *fs_info = cache->fs_info;
8207 target = cache->start;
8208 btrfs_put_block_group(cache);
8210 sb_start_write(fs_info->sb);
8211 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8213 "zoned: skip relocating block group %llu to repair: EBUSY",
8215 sb_end_write(fs_info->sb);
8219 mutex_lock(&fs_info->reclaim_bgs_lock);
8221 /* Ensure block group still exists */
8222 cache = btrfs_lookup_block_group(fs_info, target);
8226 if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags))
8229 ret = btrfs_may_alloc_data_chunk(fs_info, target);
8234 "zoned: relocating block group %llu to repair IO failure",
8236 ret = btrfs_relocate_chunk(fs_info, target);
8240 btrfs_put_block_group(cache);
8241 mutex_unlock(&fs_info->reclaim_bgs_lock);
8242 btrfs_exclop_finish(fs_info);
8243 sb_end_write(fs_info->sb);
8248 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8250 struct btrfs_block_group *cache;
8252 if (!btrfs_is_zoned(fs_info))
8255 /* Do not attempt to repair in degraded state */
8256 if (btrfs_test_opt(fs_info, DEGRADED))
8259 cache = btrfs_lookup_block_group(fs_info, logical);
8263 if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) {
8264 btrfs_put_block_group(cache);
8268 kthread_run(relocating_repair_kthread, cache,
8269 "btrfs-relocating-repair");
8274 static void map_raid56_repair_block(struct btrfs_io_context *bioc,
8275 struct btrfs_io_stripe *smap,
8278 int data_stripes = nr_bioc_data_stripes(bioc);
8281 for (i = 0; i < data_stripes; i++) {
8282 u64 stripe_start = bioc->full_stripe_logical +
8283 btrfs_stripe_nr_to_offset(i);
8285 if (logical >= stripe_start &&
8286 logical < stripe_start + BTRFS_STRIPE_LEN)
8289 ASSERT(i < data_stripes);
8290 smap->dev = bioc->stripes[i].dev;
8291 smap->physical = bioc->stripes[i].physical +
8292 ((logical - bioc->full_stripe_logical) &
8293 BTRFS_STRIPE_LEN_MASK);
8297 * Map a repair write into a single device.
8299 * A repair write is triggered by read time repair or scrub, which would only
8300 * update the contents of a single device.
8301 * Not update any other mirrors nor go through RMW path.
8303 * Callers should ensure:
8305 * - Call btrfs_bio_counter_inc_blocked() first
8306 * - The range does not cross stripe boundary
8307 * - Has a valid @mirror_num passed in.
8309 int btrfs_map_repair_block(struct btrfs_fs_info *fs_info,
8310 struct btrfs_io_stripe *smap, u64 logical,
8311 u32 length, int mirror_num)
8313 struct btrfs_io_context *bioc = NULL;
8314 u64 map_length = length;
8315 int mirror_ret = mirror_num;
8318 ASSERT(mirror_num > 0);
8320 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical, &map_length,
8321 &bioc, smap, &mirror_ret);
8325 /* The map range should not cross stripe boundary. */
8326 ASSERT(map_length >= length);
8328 /* Already mapped to single stripe. */
8332 /* Map the RAID56 multi-stripe writes to a single one. */
8333 if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
8334 map_raid56_repair_block(bioc, smap, logical);
8338 ASSERT(mirror_num <= bioc->num_stripes);
8339 smap->dev = bioc->stripes[mirror_num - 1].dev;
8340 smap->physical = bioc->stripes[mirror_num - 1].physical;
8342 btrfs_put_bioc(bioc);