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 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
45 [BTRFS_RAID_RAID10] = {
48 .devs_max = 0, /* 0 == as many as possible */
50 .tolerated_failures = 1,
54 .raid_name = "raid10",
55 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
56 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
58 [BTRFS_RAID_RAID1] = {
63 .tolerated_failures = 1,
68 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
69 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
71 [BTRFS_RAID_RAID1C3] = {
76 .tolerated_failures = 2,
80 .raid_name = "raid1c3",
81 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
82 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
84 [BTRFS_RAID_RAID1C4] = {
89 .tolerated_failures = 3,
93 .raid_name = "raid1c4",
94 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
95 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
102 .tolerated_failures = 0,
107 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
110 [BTRFS_RAID_RAID0] = {
115 .tolerated_failures = 0,
119 .raid_name = "raid0",
120 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
123 [BTRFS_RAID_SINGLE] = {
128 .tolerated_failures = 0,
132 .raid_name = "single",
136 [BTRFS_RAID_RAID5] = {
141 .tolerated_failures = 1,
145 .raid_name = "raid5",
146 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
147 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
149 [BTRFS_RAID_RAID6] = {
154 .tolerated_failures = 2,
158 .raid_name = "raid6",
159 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
160 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
165 * Convert block group flags (BTRFS_BLOCK_GROUP_*) to btrfs_raid_types, which
166 * can be used as index to access btrfs_raid_array[].
168 enum btrfs_raid_types __attribute_const__ btrfs_bg_flags_to_raid_index(u64 flags)
170 const u64 profile = (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK);
173 return BTRFS_RAID_SINGLE;
175 return BTRFS_BG_FLAG_TO_INDEX(profile);
178 const char *btrfs_bg_type_to_raid_name(u64 flags)
180 const int index = btrfs_bg_flags_to_raid_index(flags);
182 if (index >= BTRFS_NR_RAID_TYPES)
185 return btrfs_raid_array[index].raid_name;
188 int btrfs_nr_parity_stripes(u64 type)
190 enum btrfs_raid_types index = btrfs_bg_flags_to_raid_index(type);
192 return btrfs_raid_array[index].nparity;
196 * Fill @buf with textual description of @bg_flags, no more than @size_buf
197 * bytes including terminating null byte.
199 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
204 u64 flags = bg_flags;
205 u32 size_bp = size_buf;
212 #define DESCRIBE_FLAG(flag, desc) \
214 if (flags & (flag)) { \
215 ret = snprintf(bp, size_bp, "%s|", (desc)); \
216 if (ret < 0 || ret >= size_bp) \
224 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
225 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
226 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
228 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
229 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
230 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
231 btrfs_raid_array[i].raid_name);
235 ret = snprintf(bp, size_bp, "0x%llx|", flags);
239 if (size_bp < size_buf)
240 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
243 * The text is trimmed, it's up to the caller to provide sufficiently
249 static int init_first_rw_device(struct btrfs_trans_handle *trans);
250 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
251 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
257 * There are several mutexes that protect manipulation of devices and low-level
258 * structures like chunks but not block groups, extents or files
260 * uuid_mutex (global lock)
261 * ------------------------
262 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
263 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
264 * device) or requested by the device= mount option
266 * the mutex can be very coarse and can cover long-running operations
268 * protects: updates to fs_devices counters like missing devices, rw devices,
269 * seeding, structure cloning, opening/closing devices at mount/umount time
271 * global::fs_devs - add, remove, updates to the global list
273 * does not protect: manipulation of the fs_devices::devices list in general
274 * but in mount context it could be used to exclude list modifications by eg.
277 * btrfs_device::name - renames (write side), read is RCU
279 * fs_devices::device_list_mutex (per-fs, with RCU)
280 * ------------------------------------------------
281 * protects updates to fs_devices::devices, ie. adding and deleting
283 * simple list traversal with read-only actions can be done with RCU protection
285 * may be used to exclude some operations from running concurrently without any
286 * modifications to the list (see write_all_supers)
288 * Is not required at mount and close times, because our device list is
289 * protected by the uuid_mutex at that point.
293 * protects balance structures (status, state) and context accessed from
294 * several places (internally, ioctl)
298 * protects chunks, adding or removing during allocation, trim or when a new
299 * device is added/removed. Additionally it also protects post_commit_list of
300 * individual devices, since they can be added to the transaction's
301 * post_commit_list only with chunk_mutex held.
305 * a big lock that is held by the cleaner thread and prevents running subvolume
306 * cleaning together with relocation or delayed iputs
318 * Exclusive operations
319 * ====================
321 * Maintains the exclusivity of the following operations that apply to the
322 * whole filesystem and cannot run in parallel.
327 * - Device replace (*)
330 * The device operations (as above) can be in one of the following states:
336 * Only device operations marked with (*) can go into the Paused state for the
339 * - ioctl (only Balance can be Paused through ioctl)
340 * - filesystem remounted as read-only
341 * - filesystem unmounted and mounted as read-only
342 * - system power-cycle and filesystem mounted as read-only
343 * - filesystem or device errors leading to forced read-only
345 * The status of exclusive operation is set and cleared atomically.
346 * During the course of Paused state, fs_info::exclusive_operation remains set.
347 * A device operation in Paused or Running state can be canceled or resumed
348 * either by ioctl (Balance only) or when remounted as read-write.
349 * The exclusive status is cleared when the device operation is canceled or
353 DEFINE_MUTEX(uuid_mutex);
354 static LIST_HEAD(fs_uuids);
355 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
361 * Allocate new btrfs_fs_devices structure identified by a fsid.
363 * @fsid: if not NULL, copy the UUID to fs_devices::fsid and to
364 * fs_devices::metadata_fsid
366 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
367 * The returned struct is not linked onto any lists and can be destroyed with
368 * kfree() right away.
370 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
372 struct btrfs_fs_devices *fs_devs;
374 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
376 return ERR_PTR(-ENOMEM);
378 mutex_init(&fs_devs->device_list_mutex);
380 INIT_LIST_HEAD(&fs_devs->devices);
381 INIT_LIST_HEAD(&fs_devs->alloc_list);
382 INIT_LIST_HEAD(&fs_devs->fs_list);
383 INIT_LIST_HEAD(&fs_devs->seed_list);
386 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
387 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
393 static void btrfs_free_device(struct btrfs_device *device)
395 WARN_ON(!list_empty(&device->post_commit_list));
396 rcu_string_free(device->name);
397 extent_io_tree_release(&device->alloc_state);
398 btrfs_destroy_dev_zone_info(device);
402 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
404 struct btrfs_device *device;
406 WARN_ON(fs_devices->opened);
407 while (!list_empty(&fs_devices->devices)) {
408 device = list_entry(fs_devices->devices.next,
409 struct btrfs_device, dev_list);
410 list_del(&device->dev_list);
411 btrfs_free_device(device);
416 void __exit btrfs_cleanup_fs_uuids(void)
418 struct btrfs_fs_devices *fs_devices;
420 while (!list_empty(&fs_uuids)) {
421 fs_devices = list_entry(fs_uuids.next,
422 struct btrfs_fs_devices, fs_list);
423 list_del(&fs_devices->fs_list);
424 free_fs_devices(fs_devices);
428 static bool match_fsid_fs_devices(const struct btrfs_fs_devices *fs_devices,
429 const u8 *fsid, const u8 *metadata_fsid)
431 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) != 0)
437 if (memcmp(metadata_fsid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE) != 0)
443 static noinline struct btrfs_fs_devices *find_fsid(
444 const u8 *fsid, const u8 *metadata_fsid)
446 struct btrfs_fs_devices *fs_devices;
450 /* Handle non-split brain cases */
451 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
452 if (match_fsid_fs_devices(fs_devices, fsid, metadata_fsid))
459 btrfs_get_bdev_and_sb(const char *device_path, blk_mode_t flags, void *holder,
460 int flush, struct bdev_handle **bdev_handle,
461 struct btrfs_super_block **disk_super)
463 struct block_device *bdev;
466 *bdev_handle = bdev_open_by_path(device_path, flags, holder, NULL);
468 if (IS_ERR(*bdev_handle)) {
469 ret = PTR_ERR(*bdev_handle);
472 bdev = (*bdev_handle)->bdev;
476 ret = set_blocksize(bdev, BTRFS_BDEV_BLOCKSIZE);
478 bdev_release(*bdev_handle);
481 invalidate_bdev(bdev);
482 *disk_super = btrfs_read_dev_super(bdev);
483 if (IS_ERR(*disk_super)) {
484 ret = PTR_ERR(*disk_super);
485 bdev_release(*bdev_handle);
497 * Search and remove all stale devices (which are not mounted). When both
498 * inputs are NULL, it will search and release all stale devices.
500 * @devt: Optional. When provided will it release all unmounted devices
501 * matching this devt only.
502 * @skip_device: Optional. Will skip this device when searching for the stale
505 * Return: 0 for success or if @devt is 0.
506 * -EBUSY if @devt is a mounted device.
507 * -ENOENT if @devt does not match any device in the list.
509 static int btrfs_free_stale_devices(dev_t devt, struct btrfs_device *skip_device)
511 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
512 struct btrfs_device *device, *tmp_device;
516 lockdep_assert_held(&uuid_mutex);
518 /* Return good status if there is no instance of devt. */
520 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
522 mutex_lock(&fs_devices->device_list_mutex);
523 list_for_each_entry_safe(device, tmp_device,
524 &fs_devices->devices, dev_list) {
525 if (skip_device && skip_device == device)
527 if (devt && devt != device->devt)
529 if (fs_devices->opened) {
535 /* delete the stale device */
536 fs_devices->num_devices--;
537 list_del(&device->dev_list);
538 btrfs_free_device(device);
542 mutex_unlock(&fs_devices->device_list_mutex);
544 if (fs_devices->num_devices == 0) {
545 btrfs_sysfs_remove_fsid(fs_devices);
546 list_del(&fs_devices->fs_list);
547 free_fs_devices(fs_devices);
551 /* If there is at least one freed device return 0. */
558 static struct btrfs_fs_devices *find_fsid_by_device(
559 struct btrfs_super_block *disk_super,
560 dev_t devt, bool *same_fsid_diff_dev)
562 struct btrfs_fs_devices *fsid_fs_devices;
563 struct btrfs_fs_devices *devt_fs_devices;
564 const bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
565 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
566 bool found_by_devt = false;
568 /* Find the fs_device by the usual method, if found use it. */
569 fsid_fs_devices = find_fsid(disk_super->fsid,
570 has_metadata_uuid ? disk_super->metadata_uuid : NULL);
572 /* The temp_fsid feature is supported only with single device filesystem. */
573 if (btrfs_super_num_devices(disk_super) != 1)
574 return fsid_fs_devices;
577 * A seed device is an integral component of the sprout device, which
578 * functions as a multi-device filesystem. So, temp-fsid feature is
581 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING)
582 return fsid_fs_devices;
584 /* Try to find a fs_devices by matching devt. */
585 list_for_each_entry(devt_fs_devices, &fs_uuids, fs_list) {
586 struct btrfs_device *device;
588 list_for_each_entry(device, &devt_fs_devices->devices, dev_list) {
589 if (device->devt == devt) {
590 found_by_devt = true;
599 /* Existing device. */
600 if (fsid_fs_devices == NULL) {
601 if (devt_fs_devices->opened == 0) {
605 /* temp_fsid is mounting a subvol. */
606 return devt_fs_devices;
609 /* Regular or temp_fsid device mounting a subvol. */
610 return devt_fs_devices;
614 if (fsid_fs_devices == NULL) {
617 /* sb::fsid is already used create a new temp_fsid. */
618 *same_fsid_diff_dev = true;
627 * This is only used on mount, and we are protected from competing things
628 * messing with our fs_devices by the uuid_mutex, thus we do not need the
629 * fs_devices->device_list_mutex here.
631 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
632 struct btrfs_device *device, blk_mode_t flags,
635 struct bdev_handle *bdev_handle;
636 struct btrfs_super_block *disk_super;
645 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
646 &bdev_handle, &disk_super);
650 devid = btrfs_stack_device_id(&disk_super->dev_item);
651 if (devid != device->devid)
652 goto error_free_page;
654 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
655 goto error_free_page;
657 device->generation = btrfs_super_generation(disk_super);
659 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
660 if (btrfs_super_incompat_flags(disk_super) &
661 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
663 "BTRFS: Invalid seeding and uuid-changed device detected\n");
664 goto error_free_page;
667 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
668 fs_devices->seeding = true;
670 if (bdev_read_only(bdev_handle->bdev))
671 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
673 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
676 if (!bdev_nonrot(bdev_handle->bdev))
677 fs_devices->rotating = true;
679 if (bdev_max_discard_sectors(bdev_handle->bdev))
680 fs_devices->discardable = true;
682 device->bdev_handle = bdev_handle;
683 device->bdev = bdev_handle->bdev;
684 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
686 fs_devices->open_devices++;
687 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
688 device->devid != BTRFS_DEV_REPLACE_DEVID) {
689 fs_devices->rw_devices++;
690 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
692 btrfs_release_disk_super(disk_super);
697 btrfs_release_disk_super(disk_super);
698 bdev_release(bdev_handle);
703 u8 *btrfs_sb_fsid_ptr(struct btrfs_super_block *sb)
705 bool has_metadata_uuid = (btrfs_super_incompat_flags(sb) &
706 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
708 return has_metadata_uuid ? sb->metadata_uuid : sb->fsid;
712 * Add new device to list of registered devices
715 * device pointer which was just added or updated when successful
716 * error pointer when failed
718 static noinline struct btrfs_device *device_list_add(const char *path,
719 struct btrfs_super_block *disk_super,
720 bool *new_device_added)
722 struct btrfs_device *device;
723 struct btrfs_fs_devices *fs_devices = NULL;
724 struct rcu_string *name;
725 u64 found_transid = btrfs_super_generation(disk_super);
726 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
729 bool same_fsid_diff_dev = false;
730 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
731 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
733 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
735 "device %s has incomplete metadata_uuid change, please use btrfstune to complete",
737 return ERR_PTR(-EAGAIN);
740 error = lookup_bdev(path, &path_devt);
742 btrfs_err(NULL, "failed to lookup block device for path %s: %d",
744 return ERR_PTR(error);
747 fs_devices = find_fsid_by_device(disk_super, path_devt, &same_fsid_diff_dev);
750 fs_devices = alloc_fs_devices(disk_super->fsid);
751 if (IS_ERR(fs_devices))
752 return ERR_CAST(fs_devices);
754 if (has_metadata_uuid)
755 memcpy(fs_devices->metadata_uuid,
756 disk_super->metadata_uuid, BTRFS_FSID_SIZE);
758 if (same_fsid_diff_dev) {
759 generate_random_uuid(fs_devices->fsid);
760 fs_devices->temp_fsid = true;
761 pr_info("BTRFS: device %s using temp-fsid %pU\n",
762 path, fs_devices->fsid);
765 mutex_lock(&fs_devices->device_list_mutex);
766 list_add(&fs_devices->fs_list, &fs_uuids);
770 struct btrfs_dev_lookup_args args = {
772 .uuid = disk_super->dev_item.uuid,
775 mutex_lock(&fs_devices->device_list_mutex);
776 device = btrfs_find_device(fs_devices, &args);
778 if (found_transid > fs_devices->latest_generation) {
779 memcpy(fs_devices->fsid, disk_super->fsid,
781 memcpy(fs_devices->metadata_uuid,
782 btrfs_sb_fsid_ptr(disk_super), BTRFS_FSID_SIZE);
787 unsigned int nofs_flag;
789 if (fs_devices->opened) {
791 "device %s belongs to fsid %pU, and the fs is already mounted, scanned by %s (%d)",
792 path, fs_devices->fsid, current->comm,
793 task_pid_nr(current));
794 mutex_unlock(&fs_devices->device_list_mutex);
795 return ERR_PTR(-EBUSY);
798 nofs_flag = memalloc_nofs_save();
799 device = btrfs_alloc_device(NULL, &devid,
800 disk_super->dev_item.uuid, path);
801 memalloc_nofs_restore(nofs_flag);
802 if (IS_ERR(device)) {
803 mutex_unlock(&fs_devices->device_list_mutex);
804 /* we can safely leave the fs_devices entry around */
808 device->devt = path_devt;
810 list_add_rcu(&device->dev_list, &fs_devices->devices);
811 fs_devices->num_devices++;
813 device->fs_devices = fs_devices;
814 *new_device_added = true;
816 if (disk_super->label[0])
818 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
819 disk_super->label, devid, found_transid, path,
820 current->comm, task_pid_nr(current));
823 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
824 disk_super->fsid, devid, found_transid, path,
825 current->comm, task_pid_nr(current));
827 } else if (!device->name || strcmp(device->name->str, path)) {
829 * When FS is already mounted.
830 * 1. If you are here and if the device->name is NULL that
831 * means this device was missing at time of FS mount.
832 * 2. If you are here and if the device->name is different
833 * from 'path' that means either
834 * a. The same device disappeared and reappeared with
836 * b. The missing-disk-which-was-replaced, has
839 * We must allow 1 and 2a above. But 2b would be a spurious
842 * Further in case of 1 and 2a above, the disk at 'path'
843 * would have missed some transaction when it was away and
844 * in case of 2a the stale bdev has to be updated as well.
845 * 2b must not be allowed at all time.
849 * For now, we do allow update to btrfs_fs_device through the
850 * btrfs dev scan cli after FS has been mounted. We're still
851 * tracking a problem where systems fail mount by subvolume id
852 * when we reject replacement on a mounted FS.
854 if (!fs_devices->opened && found_transid < device->generation) {
856 * That is if the FS is _not_ mounted and if you
857 * are here, that means there is more than one
858 * disk with same uuid and devid.We keep the one
859 * with larger generation number or the last-in if
860 * generation are equal.
862 mutex_unlock(&fs_devices->device_list_mutex);
864 "device %s already registered with a higher generation, found %llu expect %llu",
865 path, found_transid, device->generation);
866 return ERR_PTR(-EEXIST);
870 * We are going to replace the device path for a given devid,
871 * make sure it's the same device if the device is mounted
873 * NOTE: the device->fs_info may not be reliable here so pass
874 * in a NULL to message helpers instead. This avoids a possible
875 * use-after-free when the fs_info and fs_info->sb are already
879 if (device->devt != path_devt) {
880 mutex_unlock(&fs_devices->device_list_mutex);
881 btrfs_warn_in_rcu(NULL,
882 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
883 path, devid, found_transid,
885 task_pid_nr(current));
886 return ERR_PTR(-EEXIST);
888 btrfs_info_in_rcu(NULL,
889 "devid %llu device path %s changed to %s scanned by %s (%d)",
890 devid, btrfs_dev_name(device),
892 task_pid_nr(current));
895 name = rcu_string_strdup(path, GFP_NOFS);
897 mutex_unlock(&fs_devices->device_list_mutex);
898 return ERR_PTR(-ENOMEM);
900 rcu_string_free(device->name);
901 rcu_assign_pointer(device->name, name);
902 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
903 fs_devices->missing_devices--;
904 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
906 device->devt = path_devt;
910 * Unmount does not free the btrfs_device struct but would zero
911 * generation along with most of the other members. So just update
912 * it back. We need it to pick the disk with largest generation
915 if (!fs_devices->opened) {
916 device->generation = found_transid;
917 fs_devices->latest_generation = max_t(u64, found_transid,
918 fs_devices->latest_generation);
921 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
923 mutex_unlock(&fs_devices->device_list_mutex);
927 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
929 struct btrfs_fs_devices *fs_devices;
930 struct btrfs_device *device;
931 struct btrfs_device *orig_dev;
934 lockdep_assert_held(&uuid_mutex);
936 fs_devices = alloc_fs_devices(orig->fsid);
937 if (IS_ERR(fs_devices))
940 fs_devices->total_devices = orig->total_devices;
942 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
943 const char *dev_path = NULL;
946 * This is ok to do without RCU read locked because we hold the
947 * uuid mutex so nothing we touch in here is going to disappear.
950 dev_path = orig_dev->name->str;
952 device = btrfs_alloc_device(NULL, &orig_dev->devid,
953 orig_dev->uuid, dev_path);
954 if (IS_ERR(device)) {
955 ret = PTR_ERR(device);
959 if (orig_dev->zone_info) {
960 struct btrfs_zoned_device_info *zone_info;
962 zone_info = btrfs_clone_dev_zone_info(orig_dev);
964 btrfs_free_device(device);
968 device->zone_info = zone_info;
971 list_add(&device->dev_list, &fs_devices->devices);
972 device->fs_devices = fs_devices;
973 fs_devices->num_devices++;
977 free_fs_devices(fs_devices);
981 static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
982 struct btrfs_device **latest_dev)
984 struct btrfs_device *device, *next;
986 /* This is the initialized path, it is safe to release the devices. */
987 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
988 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
989 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
990 &device->dev_state) &&
991 !test_bit(BTRFS_DEV_STATE_MISSING,
992 &device->dev_state) &&
994 device->generation > (*latest_dev)->generation)) {
995 *latest_dev = device;
1001 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1002 * in btrfs_init_dev_replace() so just continue.
1004 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1007 if (device->bdev_handle) {
1008 bdev_release(device->bdev_handle);
1009 device->bdev = NULL;
1010 device->bdev_handle = NULL;
1011 fs_devices->open_devices--;
1013 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1014 list_del_init(&device->dev_alloc_list);
1015 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1016 fs_devices->rw_devices--;
1018 list_del_init(&device->dev_list);
1019 fs_devices->num_devices--;
1020 btrfs_free_device(device);
1026 * After we have read the system tree and know devids belonging to this
1027 * filesystem, remove the device which does not belong there.
1029 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices)
1031 struct btrfs_device *latest_dev = NULL;
1032 struct btrfs_fs_devices *seed_dev;
1034 mutex_lock(&uuid_mutex);
1035 __btrfs_free_extra_devids(fs_devices, &latest_dev);
1037 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1038 __btrfs_free_extra_devids(seed_dev, &latest_dev);
1040 fs_devices->latest_dev = latest_dev;
1042 mutex_unlock(&uuid_mutex);
1045 static void btrfs_close_bdev(struct btrfs_device *device)
1050 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1051 sync_blockdev(device->bdev);
1052 invalidate_bdev(device->bdev);
1055 bdev_release(device->bdev_handle);
1058 static void btrfs_close_one_device(struct btrfs_device *device)
1060 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1062 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1063 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1064 list_del_init(&device->dev_alloc_list);
1065 fs_devices->rw_devices--;
1068 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1069 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
1071 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1072 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1073 fs_devices->missing_devices--;
1076 btrfs_close_bdev(device);
1078 fs_devices->open_devices--;
1079 device->bdev = NULL;
1081 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1082 btrfs_destroy_dev_zone_info(device);
1084 device->fs_info = NULL;
1085 atomic_set(&device->dev_stats_ccnt, 0);
1086 extent_io_tree_release(&device->alloc_state);
1089 * Reset the flush error record. We might have a transient flush error
1090 * in this mount, and if so we aborted the current transaction and set
1091 * the fs to an error state, guaranteeing no super blocks can be further
1092 * committed. However that error might be transient and if we unmount the
1093 * filesystem and mount it again, we should allow the mount to succeed
1094 * (btrfs_check_rw_degradable() should not fail) - if after mounting the
1095 * filesystem again we still get flush errors, then we will again abort
1096 * any transaction and set the error state, guaranteeing no commits of
1097 * unsafe super blocks.
1099 device->last_flush_error = 0;
1101 /* Verify the device is back in a pristine state */
1102 WARN_ON(test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1103 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1104 WARN_ON(!list_empty(&device->dev_alloc_list));
1105 WARN_ON(!list_empty(&device->post_commit_list));
1108 static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
1110 struct btrfs_device *device, *tmp;
1112 lockdep_assert_held(&uuid_mutex);
1114 if (--fs_devices->opened > 0)
1117 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
1118 btrfs_close_one_device(device);
1120 WARN_ON(fs_devices->open_devices);
1121 WARN_ON(fs_devices->rw_devices);
1122 fs_devices->opened = 0;
1123 fs_devices->seeding = false;
1124 fs_devices->fs_info = NULL;
1127 void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1130 struct btrfs_fs_devices *tmp;
1132 mutex_lock(&uuid_mutex);
1133 close_fs_devices(fs_devices);
1134 if (!fs_devices->opened) {
1135 list_splice_init(&fs_devices->seed_list, &list);
1138 * If the struct btrfs_fs_devices is not assembled with any
1139 * other device, it can be re-initialized during the next mount
1140 * without the needing device-scan step. Therefore, it can be
1143 if (fs_devices->num_devices == 1) {
1144 list_del(&fs_devices->fs_list);
1145 free_fs_devices(fs_devices);
1150 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
1151 close_fs_devices(fs_devices);
1152 list_del(&fs_devices->seed_list);
1153 free_fs_devices(fs_devices);
1155 mutex_unlock(&uuid_mutex);
1158 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1159 blk_mode_t flags, void *holder)
1161 struct btrfs_device *device;
1162 struct btrfs_device *latest_dev = NULL;
1163 struct btrfs_device *tmp_device;
1165 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1169 ret = btrfs_open_one_device(fs_devices, device, flags, holder);
1171 (!latest_dev || device->generation > latest_dev->generation)) {
1172 latest_dev = device;
1173 } else if (ret == -ENODATA) {
1174 fs_devices->num_devices--;
1175 list_del(&device->dev_list);
1176 btrfs_free_device(device);
1179 if (fs_devices->open_devices == 0)
1182 fs_devices->opened = 1;
1183 fs_devices->latest_dev = latest_dev;
1184 fs_devices->total_rw_bytes = 0;
1185 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1186 fs_devices->read_policy = BTRFS_READ_POLICY_PID;
1191 static int devid_cmp(void *priv, const struct list_head *a,
1192 const struct list_head *b)
1194 const struct btrfs_device *dev1, *dev2;
1196 dev1 = list_entry(a, struct btrfs_device, dev_list);
1197 dev2 = list_entry(b, struct btrfs_device, dev_list);
1199 if (dev1->devid < dev2->devid)
1201 else if (dev1->devid > dev2->devid)
1206 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1207 blk_mode_t flags, void *holder)
1211 lockdep_assert_held(&uuid_mutex);
1213 * The device_list_mutex cannot be taken here in case opening the
1214 * underlying device takes further locks like open_mutex.
1216 * We also don't need the lock here as this is called during mount and
1217 * exclusion is provided by uuid_mutex
1220 if (fs_devices->opened) {
1221 fs_devices->opened++;
1224 list_sort(NULL, &fs_devices->devices, devid_cmp);
1225 ret = open_fs_devices(fs_devices, flags, holder);
1231 void btrfs_release_disk_super(struct btrfs_super_block *super)
1233 struct page *page = virt_to_page(super);
1238 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1239 u64 bytenr, u64 bytenr_orig)
1241 struct btrfs_super_block *disk_super;
1246 /* make sure our super fits in the device */
1247 if (bytenr + PAGE_SIZE >= bdev_nr_bytes(bdev))
1248 return ERR_PTR(-EINVAL);
1250 /* make sure our super fits in the page */
1251 if (sizeof(*disk_super) > PAGE_SIZE)
1252 return ERR_PTR(-EINVAL);
1254 /* make sure our super doesn't straddle pages on disk */
1255 index = bytenr >> PAGE_SHIFT;
1256 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1257 return ERR_PTR(-EINVAL);
1259 /* pull in the page with our super */
1260 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1263 return ERR_CAST(page);
1265 p = page_address(page);
1267 /* align our pointer to the offset of the super block */
1268 disk_super = p + offset_in_page(bytenr);
1270 if (btrfs_super_bytenr(disk_super) != bytenr_orig ||
1271 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1272 btrfs_release_disk_super(p);
1273 return ERR_PTR(-EINVAL);
1276 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1277 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1282 int btrfs_forget_devices(dev_t devt)
1286 mutex_lock(&uuid_mutex);
1287 ret = btrfs_free_stale_devices(devt, NULL);
1288 mutex_unlock(&uuid_mutex);
1294 * Look for a btrfs signature on a device. This may be called out of the mount path
1295 * and we are not allowed to call set_blocksize during the scan. The superblock
1296 * is read via pagecache.
1298 * With @mount_arg_dev it's a scan during mount time that will always register
1299 * the device or return an error. Multi-device and seeding devices are registered
1302 struct btrfs_device *btrfs_scan_one_device(const char *path, blk_mode_t flags,
1305 struct btrfs_super_block *disk_super;
1306 bool new_device_added = false;
1307 struct btrfs_device *device = NULL;
1308 struct bdev_handle *bdev_handle;
1309 u64 bytenr, bytenr_orig;
1312 lockdep_assert_held(&uuid_mutex);
1315 * we would like to check all the supers, but that would make
1316 * a btrfs mount succeed after a mkfs from a different FS.
1317 * So, we need to add a special mount option to scan for
1318 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1322 * Avoid an exclusive open here, as the systemd-udev may initiate the
1323 * device scan which may race with the user's mount or mkfs command,
1324 * resulting in failure.
1325 * Since the device scan is solely for reading purposes, there is no
1326 * need for an exclusive open. Additionally, the devices are read again
1327 * during the mount process. It is ok to get some inconsistent
1328 * values temporarily, as the device paths of the fsid are the only
1329 * required information for assembling the volume.
1331 bdev_handle = bdev_open_by_path(path, flags, NULL, NULL);
1332 if (IS_ERR(bdev_handle))
1333 return ERR_CAST(bdev_handle);
1335 bytenr_orig = btrfs_sb_offset(0);
1336 ret = btrfs_sb_log_location_bdev(bdev_handle->bdev, 0, READ, &bytenr);
1338 device = ERR_PTR(ret);
1339 goto error_bdev_put;
1342 disk_super = btrfs_read_disk_super(bdev_handle->bdev, bytenr,
1344 if (IS_ERR(disk_super)) {
1345 device = ERR_CAST(disk_super);
1346 goto error_bdev_put;
1349 if (!mount_arg_dev && btrfs_super_num_devices(disk_super) == 1 &&
1350 !(btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING)) {
1353 ret = lookup_bdev(path, &devt);
1355 btrfs_warn(NULL, "lookup bdev failed for path %s: %d",
1358 btrfs_free_stale_devices(devt, NULL);
1360 pr_debug("BTRFS: skip registering single non-seed device %s\n", path);
1362 goto free_disk_super;
1365 device = device_list_add(path, disk_super, &new_device_added);
1366 if (!IS_ERR(device) && new_device_added)
1367 btrfs_free_stale_devices(device->devt, device);
1370 btrfs_release_disk_super(disk_super);
1373 bdev_release(bdev_handle);
1379 * Try to find a chunk that intersects [start, start + len] range and when one
1380 * such is found, record the end of it in *start
1382 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1385 u64 physical_start, physical_end;
1387 lockdep_assert_held(&device->fs_info->chunk_mutex);
1389 if (find_first_extent_bit(&device->alloc_state, *start,
1390 &physical_start, &physical_end,
1391 CHUNK_ALLOCATED, NULL)) {
1393 if (in_range(physical_start, *start, len) ||
1394 in_range(*start, physical_start,
1395 physical_end - physical_start)) {
1396 *start = physical_end + 1;
1403 static u64 dev_extent_search_start(struct btrfs_device *device)
1405 switch (device->fs_devices->chunk_alloc_policy) {
1406 case BTRFS_CHUNK_ALLOC_REGULAR:
1407 return BTRFS_DEVICE_RANGE_RESERVED;
1408 case BTRFS_CHUNK_ALLOC_ZONED:
1410 * We don't care about the starting region like regular
1411 * allocator, because we anyway use/reserve the first two zones
1412 * for superblock logging.
1420 static bool dev_extent_hole_check_zoned(struct btrfs_device *device,
1421 u64 *hole_start, u64 *hole_size,
1424 u64 zone_size = device->zone_info->zone_size;
1427 bool changed = false;
1429 ASSERT(IS_ALIGNED(*hole_start, zone_size));
1431 while (*hole_size > 0) {
1432 pos = btrfs_find_allocatable_zones(device, *hole_start,
1433 *hole_start + *hole_size,
1435 if (pos != *hole_start) {
1436 *hole_size = *hole_start + *hole_size - pos;
1439 if (*hole_size < num_bytes)
1443 ret = btrfs_ensure_empty_zones(device, pos, num_bytes);
1445 /* Range is ensured to be empty */
1449 /* Given hole range was invalid (outside of device) */
1450 if (ret == -ERANGE) {
1451 *hole_start += *hole_size;
1456 *hole_start += zone_size;
1457 *hole_size -= zone_size;
1465 * Check if specified hole is suitable for allocation.
1467 * @device: the device which we have the hole
1468 * @hole_start: starting position of the hole
1469 * @hole_size: the size of the hole
1470 * @num_bytes: the size of the free space that we need
1472 * This function may modify @hole_start and @hole_size to reflect the suitable
1473 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1475 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1476 u64 *hole_size, u64 num_bytes)
1478 bool changed = false;
1479 u64 hole_end = *hole_start + *hole_size;
1483 * Check before we set max_hole_start, otherwise we could end up
1484 * sending back this offset anyway.
1486 if (contains_pending_extent(device, hole_start, *hole_size)) {
1487 if (hole_end >= *hole_start)
1488 *hole_size = hole_end - *hole_start;
1494 switch (device->fs_devices->chunk_alloc_policy) {
1495 case BTRFS_CHUNK_ALLOC_REGULAR:
1496 /* No extra check */
1498 case BTRFS_CHUNK_ALLOC_ZONED:
1499 if (dev_extent_hole_check_zoned(device, hole_start,
1500 hole_size, num_bytes)) {
1503 * The changed hole can contain pending extent.
1504 * Loop again to check that.
1520 * Find free space in the specified device.
1522 * @device: the device which we search the free space in
1523 * @num_bytes: the size of the free space that we need
1524 * @search_start: the position from which to begin the search
1525 * @start: store the start of the free space.
1526 * @len: the size of the free space. that we find, or the size
1527 * of the max free space if we don't find suitable free space
1529 * This does a pretty simple search, the expectation is that it is called very
1530 * infrequently and that a given device has a small number of extents.
1532 * @start is used to store the start of the free space if we find. But if we
1533 * don't find suitable free space, it will be used to store the start position
1534 * of the max free space.
1536 * @len is used to store the size of the free space that we find.
1537 * But if we don't find suitable free space, it is used to store the size of
1538 * the max free space.
1540 * NOTE: This function will search *commit* root of device tree, and does extra
1541 * check to ensure dev extents are not double allocated.
1542 * This makes the function safe to allocate dev extents but may not report
1543 * correct usable device space, as device extent freed in current transaction
1544 * is not reported as available.
1546 static int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1547 u64 *start, u64 *len)
1549 struct btrfs_fs_info *fs_info = device->fs_info;
1550 struct btrfs_root *root = fs_info->dev_root;
1551 struct btrfs_key key;
1552 struct btrfs_dev_extent *dev_extent;
1553 struct btrfs_path *path;
1557 u64 max_hole_size = 0;
1559 u64 search_end = device->total_bytes;
1562 struct extent_buffer *l;
1564 search_start = dev_extent_search_start(device);
1565 max_hole_start = search_start;
1567 WARN_ON(device->zone_info &&
1568 !IS_ALIGNED(num_bytes, device->zone_info->zone_size));
1570 path = btrfs_alloc_path();
1576 if (search_start >= search_end ||
1577 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1582 path->reada = READA_FORWARD;
1583 path->search_commit_root = 1;
1584 path->skip_locking = 1;
1586 key.objectid = device->devid;
1587 key.offset = search_start;
1588 key.type = BTRFS_DEV_EXTENT_KEY;
1590 ret = btrfs_search_backwards(root, &key, path);
1594 while (search_start < search_end) {
1596 slot = path->slots[0];
1597 if (slot >= btrfs_header_nritems(l)) {
1598 ret = btrfs_next_leaf(root, path);
1606 btrfs_item_key_to_cpu(l, &key, slot);
1608 if (key.objectid < device->devid)
1611 if (key.objectid > device->devid)
1614 if (key.type != BTRFS_DEV_EXTENT_KEY)
1617 if (key.offset > search_end)
1620 if (key.offset > search_start) {
1621 hole_size = key.offset - search_start;
1622 dev_extent_hole_check(device, &search_start, &hole_size,
1625 if (hole_size > max_hole_size) {
1626 max_hole_start = search_start;
1627 max_hole_size = hole_size;
1631 * If this free space is greater than which we need,
1632 * it must be the max free space that we have found
1633 * until now, so max_hole_start must point to the start
1634 * of this free space and the length of this free space
1635 * is stored in max_hole_size. Thus, we return
1636 * max_hole_start and max_hole_size and go back to the
1639 if (hole_size >= num_bytes) {
1645 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1646 extent_end = key.offset + btrfs_dev_extent_length(l,
1648 if (extent_end > search_start)
1649 search_start = extent_end;
1656 * At this point, search_start should be the end of
1657 * allocated dev extents, and when shrinking the device,
1658 * search_end may be smaller than search_start.
1660 if (search_end > search_start) {
1661 hole_size = search_end - search_start;
1662 if (dev_extent_hole_check(device, &search_start, &hole_size,
1664 btrfs_release_path(path);
1668 if (hole_size > max_hole_size) {
1669 max_hole_start = search_start;
1670 max_hole_size = hole_size;
1675 if (max_hole_size < num_bytes)
1680 ASSERT(max_hole_start + max_hole_size <= search_end);
1682 btrfs_free_path(path);
1683 *start = max_hole_start;
1685 *len = max_hole_size;
1689 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1690 struct btrfs_device *device,
1691 u64 start, u64 *dev_extent_len)
1693 struct btrfs_fs_info *fs_info = device->fs_info;
1694 struct btrfs_root *root = fs_info->dev_root;
1696 struct btrfs_path *path;
1697 struct btrfs_key key;
1698 struct btrfs_key found_key;
1699 struct extent_buffer *leaf = NULL;
1700 struct btrfs_dev_extent *extent = NULL;
1702 path = btrfs_alloc_path();
1706 key.objectid = device->devid;
1708 key.type = BTRFS_DEV_EXTENT_KEY;
1710 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1712 ret = btrfs_previous_item(root, path, key.objectid,
1713 BTRFS_DEV_EXTENT_KEY);
1716 leaf = path->nodes[0];
1717 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1718 extent = btrfs_item_ptr(leaf, path->slots[0],
1719 struct btrfs_dev_extent);
1720 BUG_ON(found_key.offset > start || found_key.offset +
1721 btrfs_dev_extent_length(leaf, extent) < start);
1723 btrfs_release_path(path);
1725 } else if (ret == 0) {
1726 leaf = path->nodes[0];
1727 extent = btrfs_item_ptr(leaf, path->slots[0],
1728 struct btrfs_dev_extent);
1733 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1735 ret = btrfs_del_item(trans, root, path);
1737 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1739 btrfs_free_path(path);
1743 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1745 struct extent_map_tree *em_tree;
1746 struct extent_map *em;
1750 em_tree = &fs_info->mapping_tree;
1751 read_lock(&em_tree->lock);
1752 n = rb_last(&em_tree->map.rb_root);
1754 em = rb_entry(n, struct extent_map, rb_node);
1755 ret = em->start + em->len;
1757 read_unlock(&em_tree->lock);
1762 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1766 struct btrfs_key key;
1767 struct btrfs_key found_key;
1768 struct btrfs_path *path;
1770 path = btrfs_alloc_path();
1774 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1775 key.type = BTRFS_DEV_ITEM_KEY;
1776 key.offset = (u64)-1;
1778 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1784 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1789 ret = btrfs_previous_item(fs_info->chunk_root, path,
1790 BTRFS_DEV_ITEMS_OBJECTID,
1791 BTRFS_DEV_ITEM_KEY);
1795 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1797 *devid_ret = found_key.offset + 1;
1801 btrfs_free_path(path);
1806 * the device information is stored in the chunk root
1807 * the btrfs_device struct should be fully filled in
1809 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1810 struct btrfs_device *device)
1813 struct btrfs_path *path;
1814 struct btrfs_dev_item *dev_item;
1815 struct extent_buffer *leaf;
1816 struct btrfs_key key;
1819 path = btrfs_alloc_path();
1823 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1824 key.type = BTRFS_DEV_ITEM_KEY;
1825 key.offset = device->devid;
1827 btrfs_reserve_chunk_metadata(trans, true);
1828 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1829 &key, sizeof(*dev_item));
1830 btrfs_trans_release_chunk_metadata(trans);
1834 leaf = path->nodes[0];
1835 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1837 btrfs_set_device_id(leaf, dev_item, device->devid);
1838 btrfs_set_device_generation(leaf, dev_item, 0);
1839 btrfs_set_device_type(leaf, dev_item, device->type);
1840 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1841 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1842 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1843 btrfs_set_device_total_bytes(leaf, dev_item,
1844 btrfs_device_get_disk_total_bytes(device));
1845 btrfs_set_device_bytes_used(leaf, dev_item,
1846 btrfs_device_get_bytes_used(device));
1847 btrfs_set_device_group(leaf, dev_item, 0);
1848 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1849 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1850 btrfs_set_device_start_offset(leaf, dev_item, 0);
1852 ptr = btrfs_device_uuid(dev_item);
1853 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1854 ptr = btrfs_device_fsid(dev_item);
1855 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1856 ptr, BTRFS_FSID_SIZE);
1857 btrfs_mark_buffer_dirty(trans, leaf);
1861 btrfs_free_path(path);
1866 * Function to update ctime/mtime for a given device path.
1867 * Mainly used for ctime/mtime based probe like libblkid.
1869 * We don't care about errors here, this is just to be kind to userspace.
1871 static void update_dev_time(const char *device_path)
1876 ret = kern_path(device_path, LOOKUP_FOLLOW, &path);
1880 inode_update_time(d_inode(path.dentry), S_MTIME | S_CTIME | S_VERSION);
1884 static int btrfs_rm_dev_item(struct btrfs_trans_handle *trans,
1885 struct btrfs_device *device)
1887 struct btrfs_root *root = device->fs_info->chunk_root;
1889 struct btrfs_path *path;
1890 struct btrfs_key key;
1892 path = btrfs_alloc_path();
1896 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1897 key.type = BTRFS_DEV_ITEM_KEY;
1898 key.offset = device->devid;
1900 btrfs_reserve_chunk_metadata(trans, false);
1901 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1902 btrfs_trans_release_chunk_metadata(trans);
1909 ret = btrfs_del_item(trans, root, path);
1911 btrfs_free_path(path);
1916 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1917 * filesystem. It's up to the caller to adjust that number regarding eg. device
1920 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1928 seq = read_seqbegin(&fs_info->profiles_lock);
1930 all_avail = fs_info->avail_data_alloc_bits |
1931 fs_info->avail_system_alloc_bits |
1932 fs_info->avail_metadata_alloc_bits;
1933 } while (read_seqretry(&fs_info->profiles_lock, seq));
1935 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1936 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1939 if (num_devices < btrfs_raid_array[i].devs_min)
1940 return btrfs_raid_array[i].mindev_error;
1946 static struct btrfs_device * btrfs_find_next_active_device(
1947 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1949 struct btrfs_device *next_device;
1951 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1952 if (next_device != device &&
1953 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1954 && next_device->bdev)
1962 * Helper function to check if the given device is part of s_bdev / latest_dev
1963 * and replace it with the provided or the next active device, in the context
1964 * where this function called, there should be always be another device (or
1965 * this_dev) which is active.
1967 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
1968 struct btrfs_device *next_device)
1970 struct btrfs_fs_info *fs_info = device->fs_info;
1973 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1975 ASSERT(next_device);
1977 if (fs_info->sb->s_bdev &&
1978 (fs_info->sb->s_bdev == device->bdev))
1979 fs_info->sb->s_bdev = next_device->bdev;
1981 if (fs_info->fs_devices->latest_dev->bdev == device->bdev)
1982 fs_info->fs_devices->latest_dev = next_device;
1986 * Return btrfs_fs_devices::num_devices excluding the device that's being
1987 * currently replaced.
1989 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1991 u64 num_devices = fs_info->fs_devices->num_devices;
1993 down_read(&fs_info->dev_replace.rwsem);
1994 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1995 ASSERT(num_devices > 1);
1998 up_read(&fs_info->dev_replace.rwsem);
2003 static void btrfs_scratch_superblock(struct btrfs_fs_info *fs_info,
2004 struct block_device *bdev, int copy_num)
2006 struct btrfs_super_block *disk_super;
2007 const size_t len = sizeof(disk_super->magic);
2008 const u64 bytenr = btrfs_sb_offset(copy_num);
2011 disk_super = btrfs_read_disk_super(bdev, bytenr, bytenr);
2012 if (IS_ERR(disk_super))
2015 memset(&disk_super->magic, 0, len);
2016 folio_mark_dirty(virt_to_folio(disk_super));
2017 btrfs_release_disk_super(disk_super);
2019 ret = sync_blockdev_range(bdev, bytenr, bytenr + len - 1);
2021 btrfs_warn(fs_info, "error clearing superblock number %d (%d)",
2025 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2026 struct block_device *bdev,
2027 const char *device_path)
2034 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2035 if (bdev_is_zoned(bdev))
2036 btrfs_reset_sb_log_zones(bdev, copy_num);
2038 btrfs_scratch_superblock(fs_info, bdev, copy_num);
2041 /* Notify udev that device has changed */
2042 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2044 /* Update ctime/mtime for device path for libblkid */
2045 update_dev_time(device_path);
2048 int btrfs_rm_device(struct btrfs_fs_info *fs_info,
2049 struct btrfs_dev_lookup_args *args,
2050 struct bdev_handle **bdev_handle)
2052 struct btrfs_trans_handle *trans;
2053 struct btrfs_device *device;
2054 struct btrfs_fs_devices *cur_devices;
2055 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2059 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2060 btrfs_err(fs_info, "device remove not supported on extent tree v2 yet");
2065 * The device list in fs_devices is accessed without locks (neither
2066 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2067 * filesystem and another device rm cannot run.
2069 num_devices = btrfs_num_devices(fs_info);
2071 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2075 device = btrfs_find_device(fs_info->fs_devices, args);
2078 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2084 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2085 btrfs_warn_in_rcu(fs_info,
2086 "cannot remove device %s (devid %llu) due to active swapfile",
2087 btrfs_dev_name(device), device->devid);
2091 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
2092 return BTRFS_ERROR_DEV_TGT_REPLACE;
2094 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2095 fs_info->fs_devices->rw_devices == 1)
2096 return BTRFS_ERROR_DEV_ONLY_WRITABLE;
2098 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2099 mutex_lock(&fs_info->chunk_mutex);
2100 list_del_init(&device->dev_alloc_list);
2101 device->fs_devices->rw_devices--;
2102 mutex_unlock(&fs_info->chunk_mutex);
2105 ret = btrfs_shrink_device(device, 0);
2109 trans = btrfs_start_transaction(fs_info->chunk_root, 0);
2110 if (IS_ERR(trans)) {
2111 ret = PTR_ERR(trans);
2115 ret = btrfs_rm_dev_item(trans, device);
2117 /* Any error in dev item removal is critical */
2119 "failed to remove device item for devid %llu: %d",
2120 device->devid, ret);
2121 btrfs_abort_transaction(trans, ret);
2122 btrfs_end_transaction(trans);
2126 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2127 btrfs_scrub_cancel_dev(device);
2130 * the device list mutex makes sure that we don't change
2131 * the device list while someone else is writing out all
2132 * the device supers. Whoever is writing all supers, should
2133 * lock the device list mutex before getting the number of
2134 * devices in the super block (super_copy). Conversely,
2135 * whoever updates the number of devices in the super block
2136 * (super_copy) should hold the device list mutex.
2140 * In normal cases the cur_devices == fs_devices. But in case
2141 * of deleting a seed device, the cur_devices should point to
2142 * its own fs_devices listed under the fs_devices->seed_list.
2144 cur_devices = device->fs_devices;
2145 mutex_lock(&fs_devices->device_list_mutex);
2146 list_del_rcu(&device->dev_list);
2148 cur_devices->num_devices--;
2149 cur_devices->total_devices--;
2150 /* Update total_devices of the parent fs_devices if it's seed */
2151 if (cur_devices != fs_devices)
2152 fs_devices->total_devices--;
2154 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2155 cur_devices->missing_devices--;
2157 btrfs_assign_next_active_device(device, NULL);
2159 if (device->bdev_handle) {
2160 cur_devices->open_devices--;
2161 /* remove sysfs entry */
2162 btrfs_sysfs_remove_device(device);
2165 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2166 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2167 mutex_unlock(&fs_devices->device_list_mutex);
2170 * At this point, the device is zero sized and detached from the
2171 * devices list. All that's left is to zero out the old supers and
2174 * We cannot call btrfs_close_bdev() here because we're holding the sb
2175 * write lock, and bdev_release() will pull in the ->open_mutex on
2176 * the block device and it's dependencies. Instead just flush the
2177 * device and let the caller do the final bdev_release.
2179 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2180 btrfs_scratch_superblocks(fs_info, device->bdev,
2183 sync_blockdev(device->bdev);
2184 invalidate_bdev(device->bdev);
2188 *bdev_handle = device->bdev_handle;
2190 btrfs_free_device(device);
2193 * This can happen if cur_devices is the private seed devices list. We
2194 * cannot call close_fs_devices() here because it expects the uuid_mutex
2195 * to be held, but in fact we don't need that for the private
2196 * seed_devices, we can simply decrement cur_devices->opened and then
2197 * remove it from our list and free the fs_devices.
2199 if (cur_devices->num_devices == 0) {
2200 list_del_init(&cur_devices->seed_list);
2201 ASSERT(cur_devices->opened == 1);
2202 cur_devices->opened--;
2203 free_fs_devices(cur_devices);
2206 ret = btrfs_commit_transaction(trans);
2211 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2212 mutex_lock(&fs_info->chunk_mutex);
2213 list_add(&device->dev_alloc_list,
2214 &fs_devices->alloc_list);
2215 device->fs_devices->rw_devices++;
2216 mutex_unlock(&fs_info->chunk_mutex);
2221 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2223 struct btrfs_fs_devices *fs_devices;
2225 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2228 * in case of fs with no seed, srcdev->fs_devices will point
2229 * to fs_devices of fs_info. However when the dev being replaced is
2230 * a seed dev it will point to the seed's local fs_devices. In short
2231 * srcdev will have its correct fs_devices in both the cases.
2233 fs_devices = srcdev->fs_devices;
2235 list_del_rcu(&srcdev->dev_list);
2236 list_del(&srcdev->dev_alloc_list);
2237 fs_devices->num_devices--;
2238 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2239 fs_devices->missing_devices--;
2241 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2242 fs_devices->rw_devices--;
2245 fs_devices->open_devices--;
2248 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2250 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2252 mutex_lock(&uuid_mutex);
2254 btrfs_close_bdev(srcdev);
2256 btrfs_free_device(srcdev);
2258 /* if this is no devs we rather delete the fs_devices */
2259 if (!fs_devices->num_devices) {
2261 * On a mounted FS, num_devices can't be zero unless it's a
2262 * seed. In case of a seed device being replaced, the replace
2263 * target added to the sprout FS, so there will be no more
2264 * device left under the seed FS.
2266 ASSERT(fs_devices->seeding);
2268 list_del_init(&fs_devices->seed_list);
2269 close_fs_devices(fs_devices);
2270 free_fs_devices(fs_devices);
2272 mutex_unlock(&uuid_mutex);
2275 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2277 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2279 mutex_lock(&fs_devices->device_list_mutex);
2281 btrfs_sysfs_remove_device(tgtdev);
2284 fs_devices->open_devices--;
2286 fs_devices->num_devices--;
2288 btrfs_assign_next_active_device(tgtdev, NULL);
2290 list_del_rcu(&tgtdev->dev_list);
2292 mutex_unlock(&fs_devices->device_list_mutex);
2294 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2297 btrfs_close_bdev(tgtdev);
2299 btrfs_free_device(tgtdev);
2303 * Populate args from device at path.
2305 * @fs_info: the filesystem
2306 * @args: the args to populate
2307 * @path: the path to the device
2309 * This will read the super block of the device at @path and populate @args with
2310 * the devid, fsid, and uuid. This is meant to be used for ioctls that need to
2311 * lookup a device to operate on, but need to do it before we take any locks.
2312 * This properly handles the special case of "missing" that a user may pass in,
2313 * and does some basic sanity checks. The caller must make sure that @path is
2314 * properly NUL terminated before calling in, and must call
2315 * btrfs_put_dev_args_from_path() in order to free up the temporary fsid and
2318 * Return: 0 for success, -errno for failure
2320 int btrfs_get_dev_args_from_path(struct btrfs_fs_info *fs_info,
2321 struct btrfs_dev_lookup_args *args,
2324 struct btrfs_super_block *disk_super;
2325 struct bdev_handle *bdev_handle;
2328 if (!path || !path[0])
2330 if (!strcmp(path, "missing")) {
2331 args->missing = true;
2335 args->uuid = kzalloc(BTRFS_UUID_SIZE, GFP_KERNEL);
2336 args->fsid = kzalloc(BTRFS_FSID_SIZE, GFP_KERNEL);
2337 if (!args->uuid || !args->fsid) {
2338 btrfs_put_dev_args_from_path(args);
2342 ret = btrfs_get_bdev_and_sb(path, BLK_OPEN_READ, NULL, 0,
2343 &bdev_handle, &disk_super);
2345 btrfs_put_dev_args_from_path(args);
2349 args->devid = btrfs_stack_device_id(&disk_super->dev_item);
2350 memcpy(args->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE);
2351 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2352 memcpy(args->fsid, disk_super->metadata_uuid, BTRFS_FSID_SIZE);
2354 memcpy(args->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
2355 btrfs_release_disk_super(disk_super);
2356 bdev_release(bdev_handle);
2361 * Only use this jointly with btrfs_get_dev_args_from_path() because we will
2362 * allocate our ->uuid and ->fsid pointers, everybody else uses local variables
2363 * that don't need to be freed.
2365 void btrfs_put_dev_args_from_path(struct btrfs_dev_lookup_args *args)
2373 struct btrfs_device *btrfs_find_device_by_devspec(
2374 struct btrfs_fs_info *fs_info, u64 devid,
2375 const char *device_path)
2377 BTRFS_DEV_LOOKUP_ARGS(args);
2378 struct btrfs_device *device;
2383 device = btrfs_find_device(fs_info->fs_devices, &args);
2385 return ERR_PTR(-ENOENT);
2389 ret = btrfs_get_dev_args_from_path(fs_info, &args, device_path);
2391 return ERR_PTR(ret);
2392 device = btrfs_find_device(fs_info->fs_devices, &args);
2393 btrfs_put_dev_args_from_path(&args);
2395 return ERR_PTR(-ENOENT);
2399 static struct btrfs_fs_devices *btrfs_init_sprout(struct btrfs_fs_info *fs_info)
2401 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2402 struct btrfs_fs_devices *old_devices;
2403 struct btrfs_fs_devices *seed_devices;
2405 lockdep_assert_held(&uuid_mutex);
2406 if (!fs_devices->seeding)
2407 return ERR_PTR(-EINVAL);
2410 * Private copy of the seed devices, anchored at
2411 * fs_info->fs_devices->seed_list
2413 seed_devices = alloc_fs_devices(NULL);
2414 if (IS_ERR(seed_devices))
2415 return seed_devices;
2418 * It's necessary to retain a copy of the original seed fs_devices in
2419 * fs_uuids so that filesystems which have been seeded can successfully
2420 * reference the seed device from open_seed_devices. This also supports
2423 old_devices = clone_fs_devices(fs_devices);
2424 if (IS_ERR(old_devices)) {
2425 kfree(seed_devices);
2429 list_add(&old_devices->fs_list, &fs_uuids);
2431 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2432 seed_devices->opened = 1;
2433 INIT_LIST_HEAD(&seed_devices->devices);
2434 INIT_LIST_HEAD(&seed_devices->alloc_list);
2435 mutex_init(&seed_devices->device_list_mutex);
2437 return seed_devices;
2441 * Splice seed devices into the sprout fs_devices.
2442 * Generate a new fsid for the sprouted read-write filesystem.
2444 static void btrfs_setup_sprout(struct btrfs_fs_info *fs_info,
2445 struct btrfs_fs_devices *seed_devices)
2447 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2448 struct btrfs_super_block *disk_super = fs_info->super_copy;
2449 struct btrfs_device *device;
2453 * We are updating the fsid, the thread leading to device_list_add()
2454 * could race, so uuid_mutex is needed.
2456 lockdep_assert_held(&uuid_mutex);
2459 * The threads listed below may traverse dev_list but can do that without
2460 * device_list_mutex:
2461 * - All device ops and balance - as we are in btrfs_exclop_start.
2462 * - Various dev_list readers - are using RCU.
2463 * - btrfs_ioctl_fitrim() - is using RCU.
2465 * For-read threads as below are using device_list_mutex:
2466 * - Readonly scrub btrfs_scrub_dev()
2467 * - Readonly scrub btrfs_scrub_progress()
2468 * - btrfs_get_dev_stats()
2470 lockdep_assert_held(&fs_devices->device_list_mutex);
2472 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2474 list_for_each_entry(device, &seed_devices->devices, dev_list)
2475 device->fs_devices = seed_devices;
2477 fs_devices->seeding = false;
2478 fs_devices->num_devices = 0;
2479 fs_devices->open_devices = 0;
2480 fs_devices->missing_devices = 0;
2481 fs_devices->rotating = false;
2482 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2484 generate_random_uuid(fs_devices->fsid);
2485 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2486 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2488 super_flags = btrfs_super_flags(disk_super) &
2489 ~BTRFS_SUPER_FLAG_SEEDING;
2490 btrfs_set_super_flags(disk_super, super_flags);
2494 * Store the expected generation for seed devices in device items.
2496 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2498 BTRFS_DEV_LOOKUP_ARGS(args);
2499 struct btrfs_fs_info *fs_info = trans->fs_info;
2500 struct btrfs_root *root = fs_info->chunk_root;
2501 struct btrfs_path *path;
2502 struct extent_buffer *leaf;
2503 struct btrfs_dev_item *dev_item;
2504 struct btrfs_device *device;
2505 struct btrfs_key key;
2506 u8 fs_uuid[BTRFS_FSID_SIZE];
2507 u8 dev_uuid[BTRFS_UUID_SIZE];
2510 path = btrfs_alloc_path();
2514 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2516 key.type = BTRFS_DEV_ITEM_KEY;
2519 btrfs_reserve_chunk_metadata(trans, false);
2520 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2521 btrfs_trans_release_chunk_metadata(trans);
2525 leaf = path->nodes[0];
2527 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2528 ret = btrfs_next_leaf(root, path);
2533 leaf = path->nodes[0];
2534 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2535 btrfs_release_path(path);
2539 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2540 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2541 key.type != BTRFS_DEV_ITEM_KEY)
2544 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2545 struct btrfs_dev_item);
2546 args.devid = btrfs_device_id(leaf, dev_item);
2547 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2549 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2551 args.uuid = dev_uuid;
2552 args.fsid = fs_uuid;
2553 device = btrfs_find_device(fs_info->fs_devices, &args);
2554 BUG_ON(!device); /* Logic error */
2556 if (device->fs_devices->seeding) {
2557 btrfs_set_device_generation(leaf, dev_item,
2558 device->generation);
2559 btrfs_mark_buffer_dirty(trans, leaf);
2567 btrfs_free_path(path);
2571 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2573 struct btrfs_root *root = fs_info->dev_root;
2574 struct btrfs_trans_handle *trans;
2575 struct btrfs_device *device;
2576 struct bdev_handle *bdev_handle;
2577 struct super_block *sb = fs_info->sb;
2578 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2579 struct btrfs_fs_devices *seed_devices = NULL;
2580 u64 orig_super_total_bytes;
2581 u64 orig_super_num_devices;
2583 bool seeding_dev = false;
2584 bool locked = false;
2586 if (sb_rdonly(sb) && !fs_devices->seeding)
2589 bdev_handle = bdev_open_by_path(device_path, BLK_OPEN_WRITE,
2590 fs_info->bdev_holder, NULL);
2591 if (IS_ERR(bdev_handle))
2592 return PTR_ERR(bdev_handle);
2594 if (!btrfs_check_device_zone_type(fs_info, bdev_handle->bdev)) {
2599 if (fs_devices->seeding) {
2601 down_write(&sb->s_umount);
2602 mutex_lock(&uuid_mutex);
2606 sync_blockdev(bdev_handle->bdev);
2609 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2610 if (device->bdev == bdev_handle->bdev) {
2618 device = btrfs_alloc_device(fs_info, NULL, NULL, device_path);
2619 if (IS_ERR(device)) {
2620 /* we can safely leave the fs_devices entry around */
2621 ret = PTR_ERR(device);
2625 device->fs_info = fs_info;
2626 device->bdev_handle = bdev_handle;
2627 device->bdev = bdev_handle->bdev;
2628 ret = lookup_bdev(device_path, &device->devt);
2630 goto error_free_device;
2632 ret = btrfs_get_dev_zone_info(device, false);
2634 goto error_free_device;
2636 trans = btrfs_start_transaction(root, 0);
2637 if (IS_ERR(trans)) {
2638 ret = PTR_ERR(trans);
2639 goto error_free_zone;
2642 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2643 device->generation = trans->transid;
2644 device->io_width = fs_info->sectorsize;
2645 device->io_align = fs_info->sectorsize;
2646 device->sector_size = fs_info->sectorsize;
2647 device->total_bytes =
2648 round_down(bdev_nr_bytes(device->bdev), fs_info->sectorsize);
2649 device->disk_total_bytes = device->total_bytes;
2650 device->commit_total_bytes = device->total_bytes;
2651 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2652 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2653 device->dev_stats_valid = 1;
2654 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2657 btrfs_clear_sb_rdonly(sb);
2659 /* GFP_KERNEL allocation must not be under device_list_mutex */
2660 seed_devices = btrfs_init_sprout(fs_info);
2661 if (IS_ERR(seed_devices)) {
2662 ret = PTR_ERR(seed_devices);
2663 btrfs_abort_transaction(trans, ret);
2668 mutex_lock(&fs_devices->device_list_mutex);
2670 btrfs_setup_sprout(fs_info, seed_devices);
2671 btrfs_assign_next_active_device(fs_info->fs_devices->latest_dev,
2675 device->fs_devices = fs_devices;
2677 mutex_lock(&fs_info->chunk_mutex);
2678 list_add_rcu(&device->dev_list, &fs_devices->devices);
2679 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2680 fs_devices->num_devices++;
2681 fs_devices->open_devices++;
2682 fs_devices->rw_devices++;
2683 fs_devices->total_devices++;
2684 fs_devices->total_rw_bytes += device->total_bytes;
2686 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2688 if (!bdev_nonrot(device->bdev))
2689 fs_devices->rotating = true;
2691 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2692 btrfs_set_super_total_bytes(fs_info->super_copy,
2693 round_down(orig_super_total_bytes + device->total_bytes,
2694 fs_info->sectorsize));
2696 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2697 btrfs_set_super_num_devices(fs_info->super_copy,
2698 orig_super_num_devices + 1);
2701 * we've got more storage, clear any full flags on the space
2704 btrfs_clear_space_info_full(fs_info);
2706 mutex_unlock(&fs_info->chunk_mutex);
2708 /* Add sysfs device entry */
2709 btrfs_sysfs_add_device(device);
2711 mutex_unlock(&fs_devices->device_list_mutex);
2714 mutex_lock(&fs_info->chunk_mutex);
2715 ret = init_first_rw_device(trans);
2716 mutex_unlock(&fs_info->chunk_mutex);
2718 btrfs_abort_transaction(trans, ret);
2723 ret = btrfs_add_dev_item(trans, device);
2725 btrfs_abort_transaction(trans, ret);
2730 ret = btrfs_finish_sprout(trans);
2732 btrfs_abort_transaction(trans, ret);
2737 * fs_devices now represents the newly sprouted filesystem and
2738 * its fsid has been changed by btrfs_sprout_splice().
2740 btrfs_sysfs_update_sprout_fsid(fs_devices);
2743 ret = btrfs_commit_transaction(trans);
2746 mutex_unlock(&uuid_mutex);
2747 up_write(&sb->s_umount);
2750 if (ret) /* transaction commit */
2753 ret = btrfs_relocate_sys_chunks(fs_info);
2755 btrfs_handle_fs_error(fs_info, ret,
2756 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2757 trans = btrfs_attach_transaction(root);
2758 if (IS_ERR(trans)) {
2759 if (PTR_ERR(trans) == -ENOENT)
2761 ret = PTR_ERR(trans);
2765 ret = btrfs_commit_transaction(trans);
2769 * Now that we have written a new super block to this device, check all
2770 * other fs_devices list if device_path alienates any other scanned
2772 * We can ignore the return value as it typically returns -EINVAL and
2773 * only succeeds if the device was an alien.
2775 btrfs_forget_devices(device->devt);
2777 /* Update ctime/mtime for blkid or udev */
2778 update_dev_time(device_path);
2783 btrfs_sysfs_remove_device(device);
2784 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2785 mutex_lock(&fs_info->chunk_mutex);
2786 list_del_rcu(&device->dev_list);
2787 list_del(&device->dev_alloc_list);
2788 fs_info->fs_devices->num_devices--;
2789 fs_info->fs_devices->open_devices--;
2790 fs_info->fs_devices->rw_devices--;
2791 fs_info->fs_devices->total_devices--;
2792 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2793 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2794 btrfs_set_super_total_bytes(fs_info->super_copy,
2795 orig_super_total_bytes);
2796 btrfs_set_super_num_devices(fs_info->super_copy,
2797 orig_super_num_devices);
2798 mutex_unlock(&fs_info->chunk_mutex);
2799 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2802 btrfs_set_sb_rdonly(sb);
2804 btrfs_end_transaction(trans);
2806 btrfs_destroy_dev_zone_info(device);
2808 btrfs_free_device(device);
2810 bdev_release(bdev_handle);
2812 mutex_unlock(&uuid_mutex);
2813 up_write(&sb->s_umount);
2818 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2819 struct btrfs_device *device)
2822 struct btrfs_path *path;
2823 struct btrfs_root *root = device->fs_info->chunk_root;
2824 struct btrfs_dev_item *dev_item;
2825 struct extent_buffer *leaf;
2826 struct btrfs_key key;
2828 path = btrfs_alloc_path();
2832 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2833 key.type = BTRFS_DEV_ITEM_KEY;
2834 key.offset = device->devid;
2836 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2845 leaf = path->nodes[0];
2846 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2848 btrfs_set_device_id(leaf, dev_item, device->devid);
2849 btrfs_set_device_type(leaf, dev_item, device->type);
2850 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2851 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2852 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2853 btrfs_set_device_total_bytes(leaf, dev_item,
2854 btrfs_device_get_disk_total_bytes(device));
2855 btrfs_set_device_bytes_used(leaf, dev_item,
2856 btrfs_device_get_bytes_used(device));
2857 btrfs_mark_buffer_dirty(trans, leaf);
2860 btrfs_free_path(path);
2864 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2865 struct btrfs_device *device, u64 new_size)
2867 struct btrfs_fs_info *fs_info = device->fs_info;
2868 struct btrfs_super_block *super_copy = fs_info->super_copy;
2873 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2876 new_size = round_down(new_size, fs_info->sectorsize);
2878 mutex_lock(&fs_info->chunk_mutex);
2879 old_total = btrfs_super_total_bytes(super_copy);
2880 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2882 if (new_size <= device->total_bytes ||
2883 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2884 mutex_unlock(&fs_info->chunk_mutex);
2888 btrfs_set_super_total_bytes(super_copy,
2889 round_down(old_total + diff, fs_info->sectorsize));
2890 device->fs_devices->total_rw_bytes += diff;
2891 atomic64_add(diff, &fs_info->free_chunk_space);
2893 btrfs_device_set_total_bytes(device, new_size);
2894 btrfs_device_set_disk_total_bytes(device, new_size);
2895 btrfs_clear_space_info_full(device->fs_info);
2896 if (list_empty(&device->post_commit_list))
2897 list_add_tail(&device->post_commit_list,
2898 &trans->transaction->dev_update_list);
2899 mutex_unlock(&fs_info->chunk_mutex);
2901 btrfs_reserve_chunk_metadata(trans, false);
2902 ret = btrfs_update_device(trans, device);
2903 btrfs_trans_release_chunk_metadata(trans);
2908 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2910 struct btrfs_fs_info *fs_info = trans->fs_info;
2911 struct btrfs_root *root = fs_info->chunk_root;
2913 struct btrfs_path *path;
2914 struct btrfs_key key;
2916 path = btrfs_alloc_path();
2920 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2921 key.offset = chunk_offset;
2922 key.type = BTRFS_CHUNK_ITEM_KEY;
2924 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2927 else if (ret > 0) { /* Logic error or corruption */
2928 btrfs_handle_fs_error(fs_info, -ENOENT,
2929 "Failed lookup while freeing chunk.");
2934 ret = btrfs_del_item(trans, root, path);
2936 btrfs_handle_fs_error(fs_info, ret,
2937 "Failed to delete chunk item.");
2939 btrfs_free_path(path);
2943 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2945 struct btrfs_super_block *super_copy = fs_info->super_copy;
2946 struct btrfs_disk_key *disk_key;
2947 struct btrfs_chunk *chunk;
2954 struct btrfs_key key;
2956 lockdep_assert_held(&fs_info->chunk_mutex);
2957 array_size = btrfs_super_sys_array_size(super_copy);
2959 ptr = super_copy->sys_chunk_array;
2962 while (cur < array_size) {
2963 disk_key = (struct btrfs_disk_key *)ptr;
2964 btrfs_disk_key_to_cpu(&key, disk_key);
2966 len = sizeof(*disk_key);
2968 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2969 chunk = (struct btrfs_chunk *)(ptr + len);
2970 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2971 len += btrfs_chunk_item_size(num_stripes);
2976 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2977 key.offset == chunk_offset) {
2978 memmove(ptr, ptr + len, array_size - (cur + len));
2980 btrfs_set_super_sys_array_size(super_copy, array_size);
2990 * Find the mapping containing the given logical extent.
2992 * @logical: Logical block offset in bytes.
2993 * @length: Length of extent in bytes.
2995 * Return: Chunk mapping or ERR_PTR.
2997 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2998 u64 logical, u64 length)
3000 struct extent_map_tree *em_tree;
3001 struct extent_map *em;
3003 em_tree = &fs_info->mapping_tree;
3004 read_lock(&em_tree->lock);
3005 em = lookup_extent_mapping(em_tree, logical, length);
3006 read_unlock(&em_tree->lock);
3010 "unable to find chunk map for logical %llu length %llu",
3012 return ERR_PTR(-EINVAL);
3015 if (em->start > logical || em->start + em->len <= logical) {
3017 "found a bad chunk map, wanted %llu-%llu, found %llu-%llu",
3018 logical, logical + length, em->start, em->start + em->len);
3019 free_extent_map(em);
3020 return ERR_PTR(-EINVAL);
3023 /* callers are responsible for dropping em's ref. */
3027 static int remove_chunk_item(struct btrfs_trans_handle *trans,
3028 struct map_lookup *map, u64 chunk_offset)
3033 * Removing chunk items and updating the device items in the chunks btree
3034 * requires holding the chunk_mutex.
3035 * See the comment at btrfs_chunk_alloc() for the details.
3037 lockdep_assert_held(&trans->fs_info->chunk_mutex);
3039 for (i = 0; i < map->num_stripes; i++) {
3042 ret = btrfs_update_device(trans, map->stripes[i].dev);
3047 return btrfs_free_chunk(trans, chunk_offset);
3050 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3052 struct btrfs_fs_info *fs_info = trans->fs_info;
3053 struct extent_map *em;
3054 struct map_lookup *map;
3055 u64 dev_extent_len = 0;
3057 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3059 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3062 * This is a logic error, but we don't want to just rely on the
3063 * user having built with ASSERT enabled, so if ASSERT doesn't
3064 * do anything we still error out.
3069 map = em->map_lookup;
3072 * First delete the device extent items from the devices btree.
3073 * We take the device_list_mutex to avoid racing with the finishing phase
3074 * of a device replace operation. See the comment below before acquiring
3075 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3076 * because that can result in a deadlock when deleting the device extent
3077 * items from the devices btree - COWing an extent buffer from the btree
3078 * may result in allocating a new metadata chunk, which would attempt to
3079 * lock again fs_info->chunk_mutex.
3081 mutex_lock(&fs_devices->device_list_mutex);
3082 for (i = 0; i < map->num_stripes; i++) {
3083 struct btrfs_device *device = map->stripes[i].dev;
3084 ret = btrfs_free_dev_extent(trans, device,
3085 map->stripes[i].physical,
3088 mutex_unlock(&fs_devices->device_list_mutex);
3089 btrfs_abort_transaction(trans, ret);
3093 if (device->bytes_used > 0) {
3094 mutex_lock(&fs_info->chunk_mutex);
3095 btrfs_device_set_bytes_used(device,
3096 device->bytes_used - dev_extent_len);
3097 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3098 btrfs_clear_space_info_full(fs_info);
3099 mutex_unlock(&fs_info->chunk_mutex);
3102 mutex_unlock(&fs_devices->device_list_mutex);
3105 * We acquire fs_info->chunk_mutex for 2 reasons:
3107 * 1) Just like with the first phase of the chunk allocation, we must
3108 * reserve system space, do all chunk btree updates and deletions, and
3109 * update the system chunk array in the superblock while holding this
3110 * mutex. This is for similar reasons as explained on the comment at
3111 * the top of btrfs_chunk_alloc();
3113 * 2) Prevent races with the final phase of a device replace operation
3114 * that replaces the device object associated with the map's stripes,
3115 * because the device object's id can change at any time during that
3116 * final phase of the device replace operation
3117 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3118 * replaced device and then see it with an ID of
3119 * BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3120 * the device item, which does not exists on the chunk btree.
3121 * The finishing phase of device replace acquires both the
3122 * device_list_mutex and the chunk_mutex, in that order, so we are
3123 * safe by just acquiring the chunk_mutex.
3125 trans->removing_chunk = true;
3126 mutex_lock(&fs_info->chunk_mutex);
3128 check_system_chunk(trans, map->type);
3130 ret = remove_chunk_item(trans, map, chunk_offset);
3132 * Normally we should not get -ENOSPC since we reserved space before
3133 * through the call to check_system_chunk().
3135 * Despite our system space_info having enough free space, we may not
3136 * be able to allocate extents from its block groups, because all have
3137 * an incompatible profile, which will force us to allocate a new system
3138 * block group with the right profile, or right after we called
3139 * check_system_space() above, a scrub turned the only system block group
3140 * with enough free space into RO mode.
3141 * This is explained with more detail at do_chunk_alloc().
3143 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3145 if (ret == -ENOSPC) {
3146 const u64 sys_flags = btrfs_system_alloc_profile(fs_info);
3147 struct btrfs_block_group *sys_bg;
3149 sys_bg = btrfs_create_chunk(trans, sys_flags);
3150 if (IS_ERR(sys_bg)) {
3151 ret = PTR_ERR(sys_bg);
3152 btrfs_abort_transaction(trans, ret);
3156 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3158 btrfs_abort_transaction(trans, ret);
3162 ret = remove_chunk_item(trans, map, chunk_offset);
3164 btrfs_abort_transaction(trans, ret);
3168 btrfs_abort_transaction(trans, ret);
3172 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3174 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3175 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3177 btrfs_abort_transaction(trans, ret);
3182 mutex_unlock(&fs_info->chunk_mutex);
3183 trans->removing_chunk = false;
3186 * We are done with chunk btree updates and deletions, so release the
3187 * system space we previously reserved (with check_system_chunk()).
3189 btrfs_trans_release_chunk_metadata(trans);
3191 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3193 btrfs_abort_transaction(trans, ret);
3198 if (trans->removing_chunk) {
3199 mutex_unlock(&fs_info->chunk_mutex);
3200 trans->removing_chunk = false;
3203 free_extent_map(em);
3207 int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3209 struct btrfs_root *root = fs_info->chunk_root;
3210 struct btrfs_trans_handle *trans;
3211 struct btrfs_block_group *block_group;
3215 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3217 "relocate: not supported on extent tree v2 yet");
3222 * Prevent races with automatic removal of unused block groups.
3223 * After we relocate and before we remove the chunk with offset
3224 * chunk_offset, automatic removal of the block group can kick in,
3225 * resulting in a failure when calling btrfs_remove_chunk() below.
3227 * Make sure to acquire this mutex before doing a tree search (dev
3228 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3229 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3230 * we release the path used to search the chunk/dev tree and before
3231 * the current task acquires this mutex and calls us.
3233 lockdep_assert_held(&fs_info->reclaim_bgs_lock);
3235 /* step one, relocate all the extents inside this chunk */
3236 btrfs_scrub_pause(fs_info);
3237 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3238 btrfs_scrub_continue(fs_info);
3241 * If we had a transaction abort, stop all running scrubs.
3242 * See transaction.c:cleanup_transaction() why we do it here.
3244 if (BTRFS_FS_ERROR(fs_info))
3245 btrfs_scrub_cancel(fs_info);
3249 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3252 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3253 length = block_group->length;
3254 btrfs_put_block_group(block_group);
3257 * On a zoned file system, discard the whole block group, this will
3258 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3259 * resetting the zone fails, don't treat it as a fatal problem from the
3260 * filesystem's point of view.
3262 if (btrfs_is_zoned(fs_info)) {
3263 ret = btrfs_discard_extent(fs_info, chunk_offset, length, NULL);
3266 "failed to reset zone %llu after relocation",
3270 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3272 if (IS_ERR(trans)) {
3273 ret = PTR_ERR(trans);
3274 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3279 * step two, delete the device extents and the
3280 * chunk tree entries
3282 ret = btrfs_remove_chunk(trans, chunk_offset);
3283 btrfs_end_transaction(trans);
3287 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3289 struct btrfs_root *chunk_root = fs_info->chunk_root;
3290 struct btrfs_path *path;
3291 struct extent_buffer *leaf;
3292 struct btrfs_chunk *chunk;
3293 struct btrfs_key key;
3294 struct btrfs_key found_key;
3296 bool retried = false;
3300 path = btrfs_alloc_path();
3305 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3306 key.offset = (u64)-1;
3307 key.type = BTRFS_CHUNK_ITEM_KEY;
3310 mutex_lock(&fs_info->reclaim_bgs_lock);
3311 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3313 mutex_unlock(&fs_info->reclaim_bgs_lock);
3316 BUG_ON(ret == 0); /* Corruption */
3318 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3321 mutex_unlock(&fs_info->reclaim_bgs_lock);
3327 leaf = path->nodes[0];
3328 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3330 chunk = btrfs_item_ptr(leaf, path->slots[0],
3331 struct btrfs_chunk);
3332 chunk_type = btrfs_chunk_type(leaf, chunk);
3333 btrfs_release_path(path);
3335 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3336 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3342 mutex_unlock(&fs_info->reclaim_bgs_lock);
3344 if (found_key.offset == 0)
3346 key.offset = found_key.offset - 1;
3349 if (failed && !retried) {
3353 } else if (WARN_ON(failed && retried)) {
3357 btrfs_free_path(path);
3362 * return 1 : allocate a data chunk successfully,
3363 * return <0: errors during allocating a data chunk,
3364 * return 0 : no need to allocate a data chunk.
3366 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3369 struct btrfs_block_group *cache;
3373 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3375 chunk_type = cache->flags;
3376 btrfs_put_block_group(cache);
3378 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3381 spin_lock(&fs_info->data_sinfo->lock);
3382 bytes_used = fs_info->data_sinfo->bytes_used;
3383 spin_unlock(&fs_info->data_sinfo->lock);
3386 struct btrfs_trans_handle *trans;
3389 trans = btrfs_join_transaction(fs_info->tree_root);
3391 return PTR_ERR(trans);
3393 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3394 btrfs_end_transaction(trans);
3403 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3404 struct btrfs_balance_control *bctl)
3406 struct btrfs_root *root = fs_info->tree_root;
3407 struct btrfs_trans_handle *trans;
3408 struct btrfs_balance_item *item;
3409 struct btrfs_disk_balance_args disk_bargs;
3410 struct btrfs_path *path;
3411 struct extent_buffer *leaf;
3412 struct btrfs_key key;
3415 path = btrfs_alloc_path();
3419 trans = btrfs_start_transaction(root, 0);
3420 if (IS_ERR(trans)) {
3421 btrfs_free_path(path);
3422 return PTR_ERR(trans);
3425 key.objectid = BTRFS_BALANCE_OBJECTID;
3426 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3429 ret = btrfs_insert_empty_item(trans, root, path, &key,
3434 leaf = path->nodes[0];
3435 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3437 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3439 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3440 btrfs_set_balance_data(leaf, item, &disk_bargs);
3441 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3442 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3443 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3444 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3446 btrfs_set_balance_flags(leaf, item, bctl->flags);
3448 btrfs_mark_buffer_dirty(trans, leaf);
3450 btrfs_free_path(path);
3451 err = btrfs_commit_transaction(trans);
3457 static int del_balance_item(struct btrfs_fs_info *fs_info)
3459 struct btrfs_root *root = fs_info->tree_root;
3460 struct btrfs_trans_handle *trans;
3461 struct btrfs_path *path;
3462 struct btrfs_key key;
3465 path = btrfs_alloc_path();
3469 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3470 if (IS_ERR(trans)) {
3471 btrfs_free_path(path);
3472 return PTR_ERR(trans);
3475 key.objectid = BTRFS_BALANCE_OBJECTID;
3476 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3479 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3487 ret = btrfs_del_item(trans, root, path);
3489 btrfs_free_path(path);
3490 err = btrfs_commit_transaction(trans);
3497 * This is a heuristic used to reduce the number of chunks balanced on
3498 * resume after balance was interrupted.
3500 static void update_balance_args(struct btrfs_balance_control *bctl)
3503 * Turn on soft mode for chunk types that were being converted.
3505 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3506 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3507 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3508 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3509 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3510 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3513 * Turn on usage filter if is not already used. The idea is
3514 * that chunks that we have already balanced should be
3515 * reasonably full. Don't do it for chunks that are being
3516 * converted - that will keep us from relocating unconverted
3517 * (albeit full) chunks.
3519 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3520 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3521 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3522 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3523 bctl->data.usage = 90;
3525 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3526 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3527 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3528 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3529 bctl->sys.usage = 90;
3531 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3532 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3533 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3534 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3535 bctl->meta.usage = 90;
3540 * Clear the balance status in fs_info and delete the balance item from disk.
3542 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3544 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3547 BUG_ON(!fs_info->balance_ctl);
3549 spin_lock(&fs_info->balance_lock);
3550 fs_info->balance_ctl = NULL;
3551 spin_unlock(&fs_info->balance_lock);
3554 ret = del_balance_item(fs_info);
3556 btrfs_handle_fs_error(fs_info, ret, NULL);
3560 * Balance filters. Return 1 if chunk should be filtered out
3561 * (should not be balanced).
3563 static int chunk_profiles_filter(u64 chunk_type,
3564 struct btrfs_balance_args *bargs)
3566 chunk_type = chunk_to_extended(chunk_type) &
3567 BTRFS_EXTENDED_PROFILE_MASK;
3569 if (bargs->profiles & chunk_type)
3575 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3576 struct btrfs_balance_args *bargs)
3578 struct btrfs_block_group *cache;
3580 u64 user_thresh_min;
3581 u64 user_thresh_max;
3584 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3585 chunk_used = cache->used;
3587 if (bargs->usage_min == 0)
3588 user_thresh_min = 0;
3590 user_thresh_min = mult_perc(cache->length, bargs->usage_min);
3592 if (bargs->usage_max == 0)
3593 user_thresh_max = 1;
3594 else if (bargs->usage_max > 100)
3595 user_thresh_max = cache->length;
3597 user_thresh_max = mult_perc(cache->length, bargs->usage_max);
3599 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3602 btrfs_put_block_group(cache);
3606 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3607 u64 chunk_offset, struct btrfs_balance_args *bargs)
3609 struct btrfs_block_group *cache;
3610 u64 chunk_used, user_thresh;
3613 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3614 chunk_used = cache->used;
3616 if (bargs->usage_min == 0)
3618 else if (bargs->usage > 100)
3619 user_thresh = cache->length;
3621 user_thresh = mult_perc(cache->length, bargs->usage);
3623 if (chunk_used < user_thresh)
3626 btrfs_put_block_group(cache);
3630 static int chunk_devid_filter(struct extent_buffer *leaf,
3631 struct btrfs_chunk *chunk,
3632 struct btrfs_balance_args *bargs)
3634 struct btrfs_stripe *stripe;
3635 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3638 for (i = 0; i < num_stripes; i++) {
3639 stripe = btrfs_stripe_nr(chunk, i);
3640 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3647 static u64 calc_data_stripes(u64 type, int num_stripes)
3649 const int index = btrfs_bg_flags_to_raid_index(type);
3650 const int ncopies = btrfs_raid_array[index].ncopies;
3651 const int nparity = btrfs_raid_array[index].nparity;
3653 return (num_stripes - nparity) / ncopies;
3656 /* [pstart, pend) */
3657 static int chunk_drange_filter(struct extent_buffer *leaf,
3658 struct btrfs_chunk *chunk,
3659 struct btrfs_balance_args *bargs)
3661 struct btrfs_stripe *stripe;
3662 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3669 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3672 type = btrfs_chunk_type(leaf, chunk);
3673 factor = calc_data_stripes(type, num_stripes);
3675 for (i = 0; i < num_stripes; i++) {
3676 stripe = btrfs_stripe_nr(chunk, i);
3677 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3680 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3681 stripe_length = btrfs_chunk_length(leaf, chunk);
3682 stripe_length = div_u64(stripe_length, factor);
3684 if (stripe_offset < bargs->pend &&
3685 stripe_offset + stripe_length > bargs->pstart)
3692 /* [vstart, vend) */
3693 static int chunk_vrange_filter(struct extent_buffer *leaf,
3694 struct btrfs_chunk *chunk,
3696 struct btrfs_balance_args *bargs)
3698 if (chunk_offset < bargs->vend &&
3699 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3700 /* at least part of the chunk is inside this vrange */
3706 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3707 struct btrfs_chunk *chunk,
3708 struct btrfs_balance_args *bargs)
3710 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3712 if (bargs->stripes_min <= num_stripes
3713 && num_stripes <= bargs->stripes_max)
3719 static int chunk_soft_convert_filter(u64 chunk_type,
3720 struct btrfs_balance_args *bargs)
3722 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3725 chunk_type = chunk_to_extended(chunk_type) &
3726 BTRFS_EXTENDED_PROFILE_MASK;
3728 if (bargs->target == chunk_type)
3734 static int should_balance_chunk(struct extent_buffer *leaf,
3735 struct btrfs_chunk *chunk, u64 chunk_offset)
3737 struct btrfs_fs_info *fs_info = leaf->fs_info;
3738 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3739 struct btrfs_balance_args *bargs = NULL;
3740 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3743 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3744 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3748 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3749 bargs = &bctl->data;
3750 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3752 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3753 bargs = &bctl->meta;
3755 /* profiles filter */
3756 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3757 chunk_profiles_filter(chunk_type, bargs)) {
3762 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3763 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3765 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3766 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3771 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3772 chunk_devid_filter(leaf, chunk, bargs)) {
3776 /* drange filter, makes sense only with devid filter */
3777 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3778 chunk_drange_filter(leaf, chunk, bargs)) {
3783 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3784 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3788 /* stripes filter */
3789 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3790 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3794 /* soft profile changing mode */
3795 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3796 chunk_soft_convert_filter(chunk_type, bargs)) {
3801 * limited by count, must be the last filter
3803 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3804 if (bargs->limit == 0)
3808 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3810 * Same logic as the 'limit' filter; the minimum cannot be
3811 * determined here because we do not have the global information
3812 * about the count of all chunks that satisfy the filters.
3814 if (bargs->limit_max == 0)
3823 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3825 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3826 struct btrfs_root *chunk_root = fs_info->chunk_root;
3828 struct btrfs_chunk *chunk;
3829 struct btrfs_path *path = NULL;
3830 struct btrfs_key key;
3831 struct btrfs_key found_key;
3832 struct extent_buffer *leaf;
3835 int enospc_errors = 0;
3836 bool counting = true;
3837 /* The single value limit and min/max limits use the same bytes in the */
3838 u64 limit_data = bctl->data.limit;
3839 u64 limit_meta = bctl->meta.limit;
3840 u64 limit_sys = bctl->sys.limit;
3844 int chunk_reserved = 0;
3846 path = btrfs_alloc_path();
3852 /* zero out stat counters */
3853 spin_lock(&fs_info->balance_lock);
3854 memset(&bctl->stat, 0, sizeof(bctl->stat));
3855 spin_unlock(&fs_info->balance_lock);
3859 * The single value limit and min/max limits use the same bytes
3862 bctl->data.limit = limit_data;
3863 bctl->meta.limit = limit_meta;
3864 bctl->sys.limit = limit_sys;
3866 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3867 key.offset = (u64)-1;
3868 key.type = BTRFS_CHUNK_ITEM_KEY;
3871 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3872 atomic_read(&fs_info->balance_cancel_req)) {
3877 mutex_lock(&fs_info->reclaim_bgs_lock);
3878 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3880 mutex_unlock(&fs_info->reclaim_bgs_lock);
3885 * this shouldn't happen, it means the last relocate
3889 BUG(); /* FIXME break ? */
3891 ret = btrfs_previous_item(chunk_root, path, 0,
3892 BTRFS_CHUNK_ITEM_KEY);
3894 mutex_unlock(&fs_info->reclaim_bgs_lock);
3899 leaf = path->nodes[0];
3900 slot = path->slots[0];
3901 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3903 if (found_key.objectid != key.objectid) {
3904 mutex_unlock(&fs_info->reclaim_bgs_lock);
3908 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3909 chunk_type = btrfs_chunk_type(leaf, chunk);
3912 spin_lock(&fs_info->balance_lock);
3913 bctl->stat.considered++;
3914 spin_unlock(&fs_info->balance_lock);
3917 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3919 btrfs_release_path(path);
3921 mutex_unlock(&fs_info->reclaim_bgs_lock);
3926 mutex_unlock(&fs_info->reclaim_bgs_lock);
3927 spin_lock(&fs_info->balance_lock);
3928 bctl->stat.expected++;
3929 spin_unlock(&fs_info->balance_lock);
3931 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3933 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3935 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3942 * Apply limit_min filter, no need to check if the LIMITS
3943 * filter is used, limit_min is 0 by default
3945 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3946 count_data < bctl->data.limit_min)
3947 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3948 count_meta < bctl->meta.limit_min)
3949 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3950 count_sys < bctl->sys.limit_min)) {
3951 mutex_unlock(&fs_info->reclaim_bgs_lock);
3955 if (!chunk_reserved) {
3957 * We may be relocating the only data chunk we have,
3958 * which could potentially end up with losing data's
3959 * raid profile, so lets allocate an empty one in
3962 ret = btrfs_may_alloc_data_chunk(fs_info,
3965 mutex_unlock(&fs_info->reclaim_bgs_lock);
3967 } else if (ret == 1) {
3972 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3973 mutex_unlock(&fs_info->reclaim_bgs_lock);
3974 if (ret == -ENOSPC) {
3976 } else if (ret == -ETXTBSY) {
3978 "skipping relocation of block group %llu due to active swapfile",
3984 spin_lock(&fs_info->balance_lock);
3985 bctl->stat.completed++;
3986 spin_unlock(&fs_info->balance_lock);
3989 if (found_key.offset == 0)
3991 key.offset = found_key.offset - 1;
3995 btrfs_release_path(path);
4000 btrfs_free_path(path);
4001 if (enospc_errors) {
4002 btrfs_info(fs_info, "%d enospc errors during balance",
4012 * See if a given profile is valid and reduced.
4014 * @flags: profile to validate
4015 * @extended: if true @flags is treated as an extended profile
4017 static int alloc_profile_is_valid(u64 flags, int extended)
4019 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
4020 BTRFS_BLOCK_GROUP_PROFILE_MASK);
4022 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
4024 /* 1) check that all other bits are zeroed */
4028 /* 2) see if profile is reduced */
4030 return !extended; /* "0" is valid for usual profiles */
4032 return has_single_bit_set(flags);
4036 * Validate target profile against allowed profiles and return true if it's OK.
4037 * Otherwise print the error message and return false.
4039 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
4040 const struct btrfs_balance_args *bargs,
4041 u64 allowed, const char *type)
4043 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4046 /* Profile is valid and does not have bits outside of the allowed set */
4047 if (alloc_profile_is_valid(bargs->target, 1) &&
4048 (bargs->target & ~allowed) == 0)
4051 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
4052 type, btrfs_bg_type_to_raid_name(bargs->target));
4057 * Fill @buf with textual description of balance filter flags @bargs, up to
4058 * @size_buf including the terminating null. The output may be trimmed if it
4059 * does not fit into the provided buffer.
4061 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4065 u32 size_bp = size_buf;
4067 u64 flags = bargs->flags;
4068 char tmp_buf[128] = {'\0'};
4073 #define CHECK_APPEND_NOARG(a) \
4075 ret = snprintf(bp, size_bp, (a)); \
4076 if (ret < 0 || ret >= size_bp) \
4077 goto out_overflow; \
4082 #define CHECK_APPEND_1ARG(a, v1) \
4084 ret = snprintf(bp, size_bp, (a), (v1)); \
4085 if (ret < 0 || ret >= size_bp) \
4086 goto out_overflow; \
4091 #define CHECK_APPEND_2ARG(a, v1, v2) \
4093 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
4094 if (ret < 0 || ret >= size_bp) \
4095 goto out_overflow; \
4100 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4101 CHECK_APPEND_1ARG("convert=%s,",
4102 btrfs_bg_type_to_raid_name(bargs->target));
4104 if (flags & BTRFS_BALANCE_ARGS_SOFT)
4105 CHECK_APPEND_NOARG("soft,");
4107 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4108 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4110 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4113 if (flags & BTRFS_BALANCE_ARGS_USAGE)
4114 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4116 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4117 CHECK_APPEND_2ARG("usage=%u..%u,",
4118 bargs->usage_min, bargs->usage_max);
4120 if (flags & BTRFS_BALANCE_ARGS_DEVID)
4121 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4123 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4124 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4125 bargs->pstart, bargs->pend);
4127 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4128 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4129 bargs->vstart, bargs->vend);
4131 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4132 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4134 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4135 CHECK_APPEND_2ARG("limit=%u..%u,",
4136 bargs->limit_min, bargs->limit_max);
4138 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4139 CHECK_APPEND_2ARG("stripes=%u..%u,",
4140 bargs->stripes_min, bargs->stripes_max);
4142 #undef CHECK_APPEND_2ARG
4143 #undef CHECK_APPEND_1ARG
4144 #undef CHECK_APPEND_NOARG
4148 if (size_bp < size_buf)
4149 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4154 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4156 u32 size_buf = 1024;
4157 char tmp_buf[192] = {'\0'};
4160 u32 size_bp = size_buf;
4162 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4164 buf = kzalloc(size_buf, GFP_KERNEL);
4170 #define CHECK_APPEND_1ARG(a, v1) \
4172 ret = snprintf(bp, size_bp, (a), (v1)); \
4173 if (ret < 0 || ret >= size_bp) \
4174 goto out_overflow; \
4179 if (bctl->flags & BTRFS_BALANCE_FORCE)
4180 CHECK_APPEND_1ARG("%s", "-f ");
4182 if (bctl->flags & BTRFS_BALANCE_DATA) {
4183 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4184 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4187 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4188 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4189 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4192 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4193 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4194 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4197 #undef CHECK_APPEND_1ARG
4201 if (size_bp < size_buf)
4202 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4203 btrfs_info(fs_info, "balance: %s %s",
4204 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4205 "resume" : "start", buf);
4211 * Should be called with balance mutexe held
4213 int btrfs_balance(struct btrfs_fs_info *fs_info,
4214 struct btrfs_balance_control *bctl,
4215 struct btrfs_ioctl_balance_args *bargs)
4217 u64 meta_target, data_target;
4223 bool reducing_redundancy;
4224 bool paused = false;
4227 if (btrfs_fs_closing(fs_info) ||
4228 atomic_read(&fs_info->balance_pause_req) ||
4229 btrfs_should_cancel_balance(fs_info)) {
4234 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4235 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4239 * In case of mixed groups both data and meta should be picked,
4240 * and identical options should be given for both of them.
4242 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4243 if (mixed && (bctl->flags & allowed)) {
4244 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4245 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4246 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4248 "balance: mixed groups data and metadata options must be the same");
4255 * rw_devices will not change at the moment, device add/delete/replace
4258 num_devices = fs_info->fs_devices->rw_devices;
4261 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4262 * special bit for it, to make it easier to distinguish. Thus we need
4263 * to set it manually, or balance would refuse the profile.
4265 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4266 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4267 if (num_devices >= btrfs_raid_array[i].devs_min)
4268 allowed |= btrfs_raid_array[i].bg_flag;
4270 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4271 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4272 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
4278 * Allow to reduce metadata or system integrity only if force set for
4279 * profiles with redundancy (copies, parity)
4282 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4283 if (btrfs_raid_array[i].ncopies >= 2 ||
4284 btrfs_raid_array[i].tolerated_failures >= 1)
4285 allowed |= btrfs_raid_array[i].bg_flag;
4288 seq = read_seqbegin(&fs_info->profiles_lock);
4290 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4291 (fs_info->avail_system_alloc_bits & allowed) &&
4292 !(bctl->sys.target & allowed)) ||
4293 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4294 (fs_info->avail_metadata_alloc_bits & allowed) &&
4295 !(bctl->meta.target & allowed)))
4296 reducing_redundancy = true;
4298 reducing_redundancy = false;
4300 /* if we're not converting, the target field is uninitialized */
4301 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4302 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4303 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4304 bctl->data.target : fs_info->avail_data_alloc_bits;
4305 } while (read_seqretry(&fs_info->profiles_lock, seq));
4307 if (reducing_redundancy) {
4308 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4310 "balance: force reducing metadata redundancy");
4313 "balance: reduces metadata redundancy, use --force if you want this");
4319 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4320 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4322 "balance: metadata profile %s has lower redundancy than data profile %s",
4323 btrfs_bg_type_to_raid_name(meta_target),
4324 btrfs_bg_type_to_raid_name(data_target));
4327 ret = insert_balance_item(fs_info, bctl);
4328 if (ret && ret != -EEXIST)
4331 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4332 BUG_ON(ret == -EEXIST);
4333 BUG_ON(fs_info->balance_ctl);
4334 spin_lock(&fs_info->balance_lock);
4335 fs_info->balance_ctl = bctl;
4336 spin_unlock(&fs_info->balance_lock);
4338 BUG_ON(ret != -EEXIST);
4339 spin_lock(&fs_info->balance_lock);
4340 update_balance_args(bctl);
4341 spin_unlock(&fs_info->balance_lock);
4344 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4345 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4346 describe_balance_start_or_resume(fs_info);
4347 mutex_unlock(&fs_info->balance_mutex);
4349 ret = __btrfs_balance(fs_info);
4351 mutex_lock(&fs_info->balance_mutex);
4352 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req)) {
4353 btrfs_info(fs_info, "balance: paused");
4354 btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
4358 * Balance can be canceled by:
4360 * - Regular cancel request
4361 * Then ret == -ECANCELED and balance_cancel_req > 0
4363 * - Fatal signal to "btrfs" process
4364 * Either the signal caught by wait_reserve_ticket() and callers
4365 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4367 * Either way, in this case balance_cancel_req = 0, and
4368 * ret == -EINTR or ret == -ECANCELED.
4370 * So here we only check the return value to catch canceled balance.
4372 else if (ret == -ECANCELED || ret == -EINTR)
4373 btrfs_info(fs_info, "balance: canceled");
4375 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4377 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4380 memset(bargs, 0, sizeof(*bargs));
4381 btrfs_update_ioctl_balance_args(fs_info, bargs);
4384 /* We didn't pause, we can clean everything up. */
4386 reset_balance_state(fs_info);
4387 btrfs_exclop_finish(fs_info);
4390 wake_up(&fs_info->balance_wait_q);
4394 if (bctl->flags & BTRFS_BALANCE_RESUME)
4395 reset_balance_state(fs_info);
4398 btrfs_exclop_finish(fs_info);
4403 static int balance_kthread(void *data)
4405 struct btrfs_fs_info *fs_info = data;
4408 sb_start_write(fs_info->sb);
4409 mutex_lock(&fs_info->balance_mutex);
4410 if (fs_info->balance_ctl)
4411 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4412 mutex_unlock(&fs_info->balance_mutex);
4413 sb_end_write(fs_info->sb);
4418 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4420 struct task_struct *tsk;
4422 mutex_lock(&fs_info->balance_mutex);
4423 if (!fs_info->balance_ctl) {
4424 mutex_unlock(&fs_info->balance_mutex);
4427 mutex_unlock(&fs_info->balance_mutex);
4429 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4430 btrfs_info(fs_info, "balance: resume skipped");
4434 spin_lock(&fs_info->super_lock);
4435 ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED);
4436 fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
4437 spin_unlock(&fs_info->super_lock);
4439 * A ro->rw remount sequence should continue with the paused balance
4440 * regardless of who pauses it, system or the user as of now, so set
4443 spin_lock(&fs_info->balance_lock);
4444 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4445 spin_unlock(&fs_info->balance_lock);
4447 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4448 return PTR_ERR_OR_ZERO(tsk);
4451 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4453 struct btrfs_balance_control *bctl;
4454 struct btrfs_balance_item *item;
4455 struct btrfs_disk_balance_args disk_bargs;
4456 struct btrfs_path *path;
4457 struct extent_buffer *leaf;
4458 struct btrfs_key key;
4461 path = btrfs_alloc_path();
4465 key.objectid = BTRFS_BALANCE_OBJECTID;
4466 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4469 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4472 if (ret > 0) { /* ret = -ENOENT; */
4477 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4483 leaf = path->nodes[0];
4484 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4486 bctl->flags = btrfs_balance_flags(leaf, item);
4487 bctl->flags |= BTRFS_BALANCE_RESUME;
4489 btrfs_balance_data(leaf, item, &disk_bargs);
4490 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4491 btrfs_balance_meta(leaf, item, &disk_bargs);
4492 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4493 btrfs_balance_sys(leaf, item, &disk_bargs);
4494 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4497 * This should never happen, as the paused balance state is recovered
4498 * during mount without any chance of other exclusive ops to collide.
4500 * This gives the exclusive op status to balance and keeps in paused
4501 * state until user intervention (cancel or umount). If the ownership
4502 * cannot be assigned, show a message but do not fail. The balance
4503 * is in a paused state and must have fs_info::balance_ctl properly
4506 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED))
4508 "balance: cannot set exclusive op status, resume manually");
4510 btrfs_release_path(path);
4512 mutex_lock(&fs_info->balance_mutex);
4513 BUG_ON(fs_info->balance_ctl);
4514 spin_lock(&fs_info->balance_lock);
4515 fs_info->balance_ctl = bctl;
4516 spin_unlock(&fs_info->balance_lock);
4517 mutex_unlock(&fs_info->balance_mutex);
4519 btrfs_free_path(path);
4523 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4527 mutex_lock(&fs_info->balance_mutex);
4528 if (!fs_info->balance_ctl) {
4529 mutex_unlock(&fs_info->balance_mutex);
4533 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4534 atomic_inc(&fs_info->balance_pause_req);
4535 mutex_unlock(&fs_info->balance_mutex);
4537 wait_event(fs_info->balance_wait_q,
4538 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4540 mutex_lock(&fs_info->balance_mutex);
4541 /* we are good with balance_ctl ripped off from under us */
4542 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4543 atomic_dec(&fs_info->balance_pause_req);
4548 mutex_unlock(&fs_info->balance_mutex);
4552 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4554 mutex_lock(&fs_info->balance_mutex);
4555 if (!fs_info->balance_ctl) {
4556 mutex_unlock(&fs_info->balance_mutex);
4561 * A paused balance with the item stored on disk can be resumed at
4562 * mount time if the mount is read-write. Otherwise it's still paused
4563 * and we must not allow cancelling as it deletes the item.
4565 if (sb_rdonly(fs_info->sb)) {
4566 mutex_unlock(&fs_info->balance_mutex);
4570 atomic_inc(&fs_info->balance_cancel_req);
4572 * if we are running just wait and return, balance item is
4573 * deleted in btrfs_balance in this case
4575 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4576 mutex_unlock(&fs_info->balance_mutex);
4577 wait_event(fs_info->balance_wait_q,
4578 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4579 mutex_lock(&fs_info->balance_mutex);
4581 mutex_unlock(&fs_info->balance_mutex);
4583 * Lock released to allow other waiters to continue, we'll
4584 * reexamine the status again.
4586 mutex_lock(&fs_info->balance_mutex);
4588 if (fs_info->balance_ctl) {
4589 reset_balance_state(fs_info);
4590 btrfs_exclop_finish(fs_info);
4591 btrfs_info(fs_info, "balance: canceled");
4595 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4596 atomic_dec(&fs_info->balance_cancel_req);
4597 mutex_unlock(&fs_info->balance_mutex);
4601 int btrfs_uuid_scan_kthread(void *data)
4603 struct btrfs_fs_info *fs_info = data;
4604 struct btrfs_root *root = fs_info->tree_root;
4605 struct btrfs_key key;
4606 struct btrfs_path *path = NULL;
4608 struct extent_buffer *eb;
4610 struct btrfs_root_item root_item;
4612 struct btrfs_trans_handle *trans = NULL;
4613 bool closing = false;
4615 path = btrfs_alloc_path();
4622 key.type = BTRFS_ROOT_ITEM_KEY;
4626 if (btrfs_fs_closing(fs_info)) {
4630 ret = btrfs_search_forward(root, &key, path,
4631 BTRFS_OLDEST_GENERATION);
4638 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4639 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4640 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4641 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4644 eb = path->nodes[0];
4645 slot = path->slots[0];
4646 item_size = btrfs_item_size(eb, slot);
4647 if (item_size < sizeof(root_item))
4650 read_extent_buffer(eb, &root_item,
4651 btrfs_item_ptr_offset(eb, slot),
4652 (int)sizeof(root_item));
4653 if (btrfs_root_refs(&root_item) == 0)
4656 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4657 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4661 btrfs_release_path(path);
4663 * 1 - subvol uuid item
4664 * 1 - received_subvol uuid item
4666 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4667 if (IS_ERR(trans)) {
4668 ret = PTR_ERR(trans);
4676 btrfs_release_path(path);
4677 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4678 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4679 BTRFS_UUID_KEY_SUBVOL,
4682 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4688 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4689 ret = btrfs_uuid_tree_add(trans,
4690 root_item.received_uuid,
4691 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4694 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4701 btrfs_release_path(path);
4703 ret = btrfs_end_transaction(trans);
4709 if (key.offset < (u64)-1) {
4711 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4713 key.type = BTRFS_ROOT_ITEM_KEY;
4714 } else if (key.objectid < (u64)-1) {
4716 key.type = BTRFS_ROOT_ITEM_KEY;
4725 btrfs_free_path(path);
4726 if (trans && !IS_ERR(trans))
4727 btrfs_end_transaction(trans);
4729 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4731 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4732 up(&fs_info->uuid_tree_rescan_sem);
4736 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4738 struct btrfs_trans_handle *trans;
4739 struct btrfs_root *tree_root = fs_info->tree_root;
4740 struct btrfs_root *uuid_root;
4741 struct task_struct *task;
4748 trans = btrfs_start_transaction(tree_root, 2);
4750 return PTR_ERR(trans);
4752 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4753 if (IS_ERR(uuid_root)) {
4754 ret = PTR_ERR(uuid_root);
4755 btrfs_abort_transaction(trans, ret);
4756 btrfs_end_transaction(trans);
4760 fs_info->uuid_root = uuid_root;
4762 ret = btrfs_commit_transaction(trans);
4766 down(&fs_info->uuid_tree_rescan_sem);
4767 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4769 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4770 btrfs_warn(fs_info, "failed to start uuid_scan task");
4771 up(&fs_info->uuid_tree_rescan_sem);
4772 return PTR_ERR(task);
4779 * shrinking a device means finding all of the device extents past
4780 * the new size, and then following the back refs to the chunks.
4781 * The chunk relocation code actually frees the device extent
4783 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4785 struct btrfs_fs_info *fs_info = device->fs_info;
4786 struct btrfs_root *root = fs_info->dev_root;
4787 struct btrfs_trans_handle *trans;
4788 struct btrfs_dev_extent *dev_extent = NULL;
4789 struct btrfs_path *path;
4795 bool retried = false;
4796 struct extent_buffer *l;
4797 struct btrfs_key key;
4798 struct btrfs_super_block *super_copy = fs_info->super_copy;
4799 u64 old_total = btrfs_super_total_bytes(super_copy);
4800 u64 old_size = btrfs_device_get_total_bytes(device);
4805 new_size = round_down(new_size, fs_info->sectorsize);
4807 diff = round_down(old_size - new_size, fs_info->sectorsize);
4809 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4812 path = btrfs_alloc_path();
4816 path->reada = READA_BACK;
4818 trans = btrfs_start_transaction(root, 0);
4819 if (IS_ERR(trans)) {
4820 btrfs_free_path(path);
4821 return PTR_ERR(trans);
4824 mutex_lock(&fs_info->chunk_mutex);
4826 btrfs_device_set_total_bytes(device, new_size);
4827 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4828 device->fs_devices->total_rw_bytes -= diff;
4831 * The new free_chunk_space is new_size - used, so we have to
4832 * subtract the delta of the old free_chunk_space which included
4833 * old_size - used. If used > new_size then just subtract this
4834 * entire device's free space.
4836 if (device->bytes_used < new_size)
4837 free_diff = (old_size - device->bytes_used) -
4838 (new_size - device->bytes_used);
4840 free_diff = old_size - device->bytes_used;
4841 atomic64_sub(free_diff, &fs_info->free_chunk_space);
4845 * Once the device's size has been set to the new size, ensure all
4846 * in-memory chunks are synced to disk so that the loop below sees them
4847 * and relocates them accordingly.
4849 if (contains_pending_extent(device, &start, diff)) {
4850 mutex_unlock(&fs_info->chunk_mutex);
4851 ret = btrfs_commit_transaction(trans);
4855 mutex_unlock(&fs_info->chunk_mutex);
4856 btrfs_end_transaction(trans);
4860 key.objectid = device->devid;
4861 key.offset = (u64)-1;
4862 key.type = BTRFS_DEV_EXTENT_KEY;
4865 mutex_lock(&fs_info->reclaim_bgs_lock);
4866 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4868 mutex_unlock(&fs_info->reclaim_bgs_lock);
4872 ret = btrfs_previous_item(root, path, 0, key.type);
4874 mutex_unlock(&fs_info->reclaim_bgs_lock);
4878 btrfs_release_path(path);
4883 slot = path->slots[0];
4884 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4886 if (key.objectid != device->devid) {
4887 mutex_unlock(&fs_info->reclaim_bgs_lock);
4888 btrfs_release_path(path);
4892 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4893 length = btrfs_dev_extent_length(l, dev_extent);
4895 if (key.offset + length <= new_size) {
4896 mutex_unlock(&fs_info->reclaim_bgs_lock);
4897 btrfs_release_path(path);
4901 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4902 btrfs_release_path(path);
4905 * We may be relocating the only data chunk we have,
4906 * which could potentially end up with losing data's
4907 * raid profile, so lets allocate an empty one in
4910 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4912 mutex_unlock(&fs_info->reclaim_bgs_lock);
4916 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4917 mutex_unlock(&fs_info->reclaim_bgs_lock);
4918 if (ret == -ENOSPC) {
4921 if (ret == -ETXTBSY) {
4923 "could not shrink block group %llu due to active swapfile",
4928 } while (key.offset-- > 0);
4930 if (failed && !retried) {
4934 } else if (failed && retried) {
4939 /* Shrinking succeeded, else we would be at "done". */
4940 trans = btrfs_start_transaction(root, 0);
4941 if (IS_ERR(trans)) {
4942 ret = PTR_ERR(trans);
4946 mutex_lock(&fs_info->chunk_mutex);
4947 /* Clear all state bits beyond the shrunk device size */
4948 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4951 btrfs_device_set_disk_total_bytes(device, new_size);
4952 if (list_empty(&device->post_commit_list))
4953 list_add_tail(&device->post_commit_list,
4954 &trans->transaction->dev_update_list);
4956 WARN_ON(diff > old_total);
4957 btrfs_set_super_total_bytes(super_copy,
4958 round_down(old_total - diff, fs_info->sectorsize));
4959 mutex_unlock(&fs_info->chunk_mutex);
4961 btrfs_reserve_chunk_metadata(trans, false);
4962 /* Now btrfs_update_device() will change the on-disk size. */
4963 ret = btrfs_update_device(trans, device);
4964 btrfs_trans_release_chunk_metadata(trans);
4966 btrfs_abort_transaction(trans, ret);
4967 btrfs_end_transaction(trans);
4969 ret = btrfs_commit_transaction(trans);
4972 btrfs_free_path(path);
4974 mutex_lock(&fs_info->chunk_mutex);
4975 btrfs_device_set_total_bytes(device, old_size);
4976 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4977 device->fs_devices->total_rw_bytes += diff;
4978 atomic64_add(free_diff, &fs_info->free_chunk_space);
4980 mutex_unlock(&fs_info->chunk_mutex);
4985 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4986 struct btrfs_key *key,
4987 struct btrfs_chunk *chunk, int item_size)
4989 struct btrfs_super_block *super_copy = fs_info->super_copy;
4990 struct btrfs_disk_key disk_key;
4994 lockdep_assert_held(&fs_info->chunk_mutex);
4996 array_size = btrfs_super_sys_array_size(super_copy);
4997 if (array_size + item_size + sizeof(disk_key)
4998 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
5001 ptr = super_copy->sys_chunk_array + array_size;
5002 btrfs_cpu_key_to_disk(&disk_key, key);
5003 memcpy(ptr, &disk_key, sizeof(disk_key));
5004 ptr += sizeof(disk_key);
5005 memcpy(ptr, chunk, item_size);
5006 item_size += sizeof(disk_key);
5007 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
5013 * sort the devices in descending order by max_avail, total_avail
5015 static int btrfs_cmp_device_info(const void *a, const void *b)
5017 const struct btrfs_device_info *di_a = a;
5018 const struct btrfs_device_info *di_b = b;
5020 if (di_a->max_avail > di_b->max_avail)
5022 if (di_a->max_avail < di_b->max_avail)
5024 if (di_a->total_avail > di_b->total_avail)
5026 if (di_a->total_avail < di_b->total_avail)
5031 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
5033 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5036 btrfs_set_fs_incompat(info, RAID56);
5039 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
5041 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
5044 btrfs_set_fs_incompat(info, RAID1C34);
5048 * Structure used internally for btrfs_create_chunk() function.
5049 * Wraps needed parameters.
5051 struct alloc_chunk_ctl {
5054 /* Total number of stripes to allocate */
5056 /* sub_stripes info for map */
5058 /* Stripes per device */
5060 /* Maximum number of devices to use */
5062 /* Minimum number of devices to use */
5064 /* ndevs has to be a multiple of this */
5066 /* Number of copies */
5068 /* Number of stripes worth of bytes to store parity information */
5070 u64 max_stripe_size;
5078 static void init_alloc_chunk_ctl_policy_regular(
5079 struct btrfs_fs_devices *fs_devices,
5080 struct alloc_chunk_ctl *ctl)
5082 struct btrfs_space_info *space_info;
5084 space_info = btrfs_find_space_info(fs_devices->fs_info, ctl->type);
5087 ctl->max_chunk_size = READ_ONCE(space_info->chunk_size);
5088 ctl->max_stripe_size = min_t(u64, ctl->max_chunk_size, SZ_1G);
5090 if (ctl->type & BTRFS_BLOCK_GROUP_SYSTEM)
5091 ctl->devs_max = min_t(int, ctl->devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
5093 /* We don't want a chunk larger than 10% of writable space */
5094 ctl->max_chunk_size = min(mult_perc(fs_devices->total_rw_bytes, 10),
5095 ctl->max_chunk_size);
5096 ctl->dev_extent_min = btrfs_stripe_nr_to_offset(ctl->dev_stripes);
5099 static void init_alloc_chunk_ctl_policy_zoned(
5100 struct btrfs_fs_devices *fs_devices,
5101 struct alloc_chunk_ctl *ctl)
5103 u64 zone_size = fs_devices->fs_info->zone_size;
5105 int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5106 int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5107 u64 min_chunk_size = min_data_stripes * zone_size;
5108 u64 type = ctl->type;
5110 ctl->max_stripe_size = zone_size;
5111 if (type & BTRFS_BLOCK_GROUP_DATA) {
5112 ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5114 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5115 ctl->max_chunk_size = ctl->max_stripe_size;
5116 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5117 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5118 ctl->devs_max = min_t(int, ctl->devs_max,
5119 BTRFS_MAX_DEVS_SYS_CHUNK);
5124 /* We don't want a chunk larger than 10% of writable space */
5125 limit = max(round_down(mult_perc(fs_devices->total_rw_bytes, 10),
5128 ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5129 ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5132 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5133 struct alloc_chunk_ctl *ctl)
5135 int index = btrfs_bg_flags_to_raid_index(ctl->type);
5137 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5138 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5139 ctl->devs_max = btrfs_raid_array[index].devs_max;
5141 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5142 ctl->devs_min = btrfs_raid_array[index].devs_min;
5143 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5144 ctl->ncopies = btrfs_raid_array[index].ncopies;
5145 ctl->nparity = btrfs_raid_array[index].nparity;
5148 switch (fs_devices->chunk_alloc_policy) {
5149 case BTRFS_CHUNK_ALLOC_REGULAR:
5150 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5152 case BTRFS_CHUNK_ALLOC_ZONED:
5153 init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5160 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5161 struct alloc_chunk_ctl *ctl,
5162 struct btrfs_device_info *devices_info)
5164 struct btrfs_fs_info *info = fs_devices->fs_info;
5165 struct btrfs_device *device;
5167 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5174 * in the first pass through the devices list, we gather information
5175 * about the available holes on each device.
5177 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5178 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5180 "BTRFS: read-only device in alloc_list\n");
5184 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5185 &device->dev_state) ||
5186 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5189 if (device->total_bytes > device->bytes_used)
5190 total_avail = device->total_bytes - device->bytes_used;
5194 /* If there is no space on this device, skip it. */
5195 if (total_avail < ctl->dev_extent_min)
5198 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5200 if (ret && ret != -ENOSPC)
5204 max_avail = dev_extent_want;
5206 if (max_avail < ctl->dev_extent_min) {
5207 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5209 "%s: devid %llu has no free space, have=%llu want=%llu",
5210 __func__, device->devid, max_avail,
5211 ctl->dev_extent_min);
5215 if (ndevs == fs_devices->rw_devices) {
5216 WARN(1, "%s: found more than %llu devices\n",
5217 __func__, fs_devices->rw_devices);
5220 devices_info[ndevs].dev_offset = dev_offset;
5221 devices_info[ndevs].max_avail = max_avail;
5222 devices_info[ndevs].total_avail = total_avail;
5223 devices_info[ndevs].dev = device;
5229 * now sort the devices by hole size / available space
5231 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5232 btrfs_cmp_device_info, NULL);
5237 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5238 struct btrfs_device_info *devices_info)
5240 /* Number of stripes that count for block group size */
5244 * The primary goal is to maximize the number of stripes, so use as
5245 * many devices as possible, even if the stripes are not maximum sized.
5247 * The DUP profile stores more than one stripe per device, the
5248 * max_avail is the total size so we have to adjust.
5250 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5252 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5254 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5255 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5258 * Use the number of data stripes to figure out how big this chunk is
5259 * really going to be in terms of logical address space, and compare
5260 * that answer with the max chunk size. If it's higher, we try to
5261 * reduce stripe_size.
5263 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5265 * Reduce stripe_size, round it up to a 16MB boundary again and
5266 * then use it, unless it ends up being even bigger than the
5267 * previous value we had already.
5269 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5270 data_stripes), SZ_16M),
5274 /* Stripe size should not go beyond 1G. */
5275 ctl->stripe_size = min_t(u64, ctl->stripe_size, SZ_1G);
5277 /* Align to BTRFS_STRIPE_LEN */
5278 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5279 ctl->chunk_size = ctl->stripe_size * data_stripes;
5284 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5285 struct btrfs_device_info *devices_info)
5287 u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5288 /* Number of stripes that count for block group size */
5292 * It should hold because:
5293 * dev_extent_min == dev_extent_want == zone_size * dev_stripes
5295 ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min);
5297 ctl->stripe_size = zone_size;
5298 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5299 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5301 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */
5302 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5303 ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5304 ctl->stripe_size) + ctl->nparity,
5306 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5307 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5308 ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size);
5311 ctl->chunk_size = ctl->stripe_size * data_stripes;
5316 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5317 struct alloc_chunk_ctl *ctl,
5318 struct btrfs_device_info *devices_info)
5320 struct btrfs_fs_info *info = fs_devices->fs_info;
5323 * Round down to number of usable stripes, devs_increment can be any
5324 * number so we can't use round_down() that requires power of 2, while
5325 * rounddown is safe.
5327 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5329 if (ctl->ndevs < ctl->devs_min) {
5330 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5332 "%s: not enough devices with free space: have=%d minimum required=%d",
5333 __func__, ctl->ndevs, ctl->devs_min);
5338 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5340 switch (fs_devices->chunk_alloc_policy) {
5341 case BTRFS_CHUNK_ALLOC_REGULAR:
5342 return decide_stripe_size_regular(ctl, devices_info);
5343 case BTRFS_CHUNK_ALLOC_ZONED:
5344 return decide_stripe_size_zoned(ctl, devices_info);
5350 static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
5351 struct alloc_chunk_ctl *ctl,
5352 struct btrfs_device_info *devices_info)
5354 struct btrfs_fs_info *info = trans->fs_info;
5355 struct map_lookup *map = NULL;
5356 struct extent_map_tree *em_tree;
5357 struct btrfs_block_group *block_group;
5358 struct extent_map *em;
5359 u64 start = ctl->start;
5360 u64 type = ctl->type;
5365 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5367 return ERR_PTR(-ENOMEM);
5368 map->num_stripes = ctl->num_stripes;
5370 for (i = 0; i < ctl->ndevs; ++i) {
5371 for (j = 0; j < ctl->dev_stripes; ++j) {
5372 int s = i * ctl->dev_stripes + j;
5373 map->stripes[s].dev = devices_info[i].dev;
5374 map->stripes[s].physical = devices_info[i].dev_offset +
5375 j * ctl->stripe_size;
5378 map->io_align = BTRFS_STRIPE_LEN;
5379 map->io_width = BTRFS_STRIPE_LEN;
5381 map->sub_stripes = ctl->sub_stripes;
5383 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5385 em = alloc_extent_map();
5388 return ERR_PTR(-ENOMEM);
5390 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5391 em->map_lookup = map;
5393 em->len = ctl->chunk_size;
5394 em->block_start = 0;
5395 em->block_len = em->len;
5396 em->orig_block_len = ctl->stripe_size;
5398 em_tree = &info->mapping_tree;
5399 write_lock(&em_tree->lock);
5400 ret = add_extent_mapping(em_tree, em, 0);
5402 write_unlock(&em_tree->lock);
5403 free_extent_map(em);
5404 return ERR_PTR(ret);
5406 write_unlock(&em_tree->lock);
5408 block_group = btrfs_make_block_group(trans, type, start, ctl->chunk_size);
5409 if (IS_ERR(block_group))
5410 goto error_del_extent;
5412 for (i = 0; i < map->num_stripes; i++) {
5413 struct btrfs_device *dev = map->stripes[i].dev;
5415 btrfs_device_set_bytes_used(dev,
5416 dev->bytes_used + ctl->stripe_size);
5417 if (list_empty(&dev->post_commit_list))
5418 list_add_tail(&dev->post_commit_list,
5419 &trans->transaction->dev_update_list);
5422 atomic64_sub(ctl->stripe_size * map->num_stripes,
5423 &info->free_chunk_space);
5425 free_extent_map(em);
5426 check_raid56_incompat_flag(info, type);
5427 check_raid1c34_incompat_flag(info, type);
5432 write_lock(&em_tree->lock);
5433 remove_extent_mapping(em_tree, em);
5434 write_unlock(&em_tree->lock);
5436 /* One for our allocation */
5437 free_extent_map(em);
5438 /* One for the tree reference */
5439 free_extent_map(em);
5444 struct btrfs_block_group *btrfs_create_chunk(struct btrfs_trans_handle *trans,
5447 struct btrfs_fs_info *info = trans->fs_info;
5448 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5449 struct btrfs_device_info *devices_info = NULL;
5450 struct alloc_chunk_ctl ctl;
5451 struct btrfs_block_group *block_group;
5454 lockdep_assert_held(&info->chunk_mutex);
5456 if (!alloc_profile_is_valid(type, 0)) {
5458 return ERR_PTR(-EINVAL);
5461 if (list_empty(&fs_devices->alloc_list)) {
5462 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5463 btrfs_debug(info, "%s: no writable device", __func__);
5464 return ERR_PTR(-ENOSPC);
5467 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5468 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5470 return ERR_PTR(-EINVAL);
5473 ctl.start = find_next_chunk(info);
5475 init_alloc_chunk_ctl(fs_devices, &ctl);
5477 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5480 return ERR_PTR(-ENOMEM);
5482 ret = gather_device_info(fs_devices, &ctl, devices_info);
5484 block_group = ERR_PTR(ret);
5488 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5490 block_group = ERR_PTR(ret);
5494 block_group = create_chunk(trans, &ctl, devices_info);
5497 kfree(devices_info);
5502 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5503 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5506 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5509 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
5510 struct btrfs_block_group *bg)
5512 struct btrfs_fs_info *fs_info = trans->fs_info;
5513 struct btrfs_root *chunk_root = fs_info->chunk_root;
5514 struct btrfs_key key;
5515 struct btrfs_chunk *chunk;
5516 struct btrfs_stripe *stripe;
5517 struct extent_map *em;
5518 struct map_lookup *map;
5524 * We take the chunk_mutex for 2 reasons:
5526 * 1) Updates and insertions in the chunk btree must be done while holding
5527 * the chunk_mutex, as well as updating the system chunk array in the
5528 * superblock. See the comment on top of btrfs_chunk_alloc() for the
5531 * 2) To prevent races with the final phase of a device replace operation
5532 * that replaces the device object associated with the map's stripes,
5533 * because the device object's id can change at any time during that
5534 * final phase of the device replace operation
5535 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5536 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5537 * which would cause a failure when updating the device item, which does
5538 * not exists, or persisting a stripe of the chunk item with such ID.
5539 * Here we can't use the device_list_mutex because our caller already
5540 * has locked the chunk_mutex, and the final phase of device replace
5541 * acquires both mutexes - first the device_list_mutex and then the
5542 * chunk_mutex. Using any of those two mutexes protects us from a
5543 * concurrent device replace.
5545 lockdep_assert_held(&fs_info->chunk_mutex);
5547 em = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
5550 btrfs_abort_transaction(trans, ret);
5554 map = em->map_lookup;
5555 item_size = btrfs_chunk_item_size(map->num_stripes);
5557 chunk = kzalloc(item_size, GFP_NOFS);
5560 btrfs_abort_transaction(trans, ret);
5564 for (i = 0; i < map->num_stripes; i++) {
5565 struct btrfs_device *device = map->stripes[i].dev;
5567 ret = btrfs_update_device(trans, device);
5572 stripe = &chunk->stripe;
5573 for (i = 0; i < map->num_stripes; i++) {
5574 struct btrfs_device *device = map->stripes[i].dev;
5575 const u64 dev_offset = map->stripes[i].physical;
5577 btrfs_set_stack_stripe_devid(stripe, device->devid);
5578 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5579 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5583 btrfs_set_stack_chunk_length(chunk, bg->length);
5584 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
5585 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
5586 btrfs_set_stack_chunk_type(chunk, map->type);
5587 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5588 btrfs_set_stack_chunk_io_align(chunk, BTRFS_STRIPE_LEN);
5589 btrfs_set_stack_chunk_io_width(chunk, BTRFS_STRIPE_LEN);
5590 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5591 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5593 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5594 key.type = BTRFS_CHUNK_ITEM_KEY;
5595 key.offset = bg->start;
5597 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5601 set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED, &bg->runtime_flags);
5603 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5604 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5611 free_extent_map(em);
5615 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5617 struct btrfs_fs_info *fs_info = trans->fs_info;
5619 struct btrfs_block_group *meta_bg;
5620 struct btrfs_block_group *sys_bg;
5623 * When adding a new device for sprouting, the seed device is read-only
5624 * so we must first allocate a metadata and a system chunk. But before
5625 * adding the block group items to the extent, device and chunk btrees,
5628 * 1) Create both chunks without doing any changes to the btrees, as
5629 * otherwise we would get -ENOSPC since the block groups from the
5630 * seed device are read-only;
5632 * 2) Add the device item for the new sprout device - finishing the setup
5633 * of a new block group requires updating the device item in the chunk
5634 * btree, so it must exist when we attempt to do it. The previous step
5635 * ensures this does not fail with -ENOSPC.
5637 * After that we can add the block group items to their btrees:
5638 * update existing device item in the chunk btree, add a new block group
5639 * item to the extent btree, add a new chunk item to the chunk btree and
5640 * finally add the new device extent items to the devices btree.
5643 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5644 meta_bg = btrfs_create_chunk(trans, alloc_profile);
5645 if (IS_ERR(meta_bg))
5646 return PTR_ERR(meta_bg);
5648 alloc_profile = btrfs_system_alloc_profile(fs_info);
5649 sys_bg = btrfs_create_chunk(trans, alloc_profile);
5651 return PTR_ERR(sys_bg);
5656 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5658 const int index = btrfs_bg_flags_to_raid_index(map->type);
5660 return btrfs_raid_array[index].tolerated_failures;
5663 bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5665 struct extent_map *em;
5666 struct map_lookup *map;
5671 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5675 map = em->map_lookup;
5676 for (i = 0; i < map->num_stripes; i++) {
5677 if (test_bit(BTRFS_DEV_STATE_MISSING,
5678 &map->stripes[i].dev->dev_state)) {
5682 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5683 &map->stripes[i].dev->dev_state)) {
5690 * If the number of missing devices is larger than max errors, we can
5691 * not write the data into that chunk successfully.
5693 if (miss_ndevs > btrfs_chunk_max_errors(map))
5696 free_extent_map(em);
5700 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5702 struct extent_map *em;
5705 write_lock(&tree->lock);
5706 em = lookup_extent_mapping(tree, 0, (u64)-1);
5708 remove_extent_mapping(tree, em);
5709 write_unlock(&tree->lock);
5713 free_extent_map(em);
5714 /* once for the tree */
5715 free_extent_map(em);
5719 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5721 struct extent_map *em;
5722 struct map_lookup *map;
5723 enum btrfs_raid_types index;
5726 em = btrfs_get_chunk_map(fs_info, logical, len);
5729 * We could return errors for these cases, but that could get
5730 * ugly and we'd probably do the same thing which is just not do
5731 * anything else and exit, so return 1 so the callers don't try
5732 * to use other copies.
5736 map = em->map_lookup;
5737 index = btrfs_bg_flags_to_raid_index(map->type);
5739 /* Non-RAID56, use their ncopies from btrfs_raid_array. */
5740 if (!(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5741 ret = btrfs_raid_array[index].ncopies;
5742 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5744 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5746 * There could be two corrupted data stripes, we need
5747 * to loop retry in order to rebuild the correct data.
5749 * Fail a stripe at a time on every retry except the
5750 * stripe under reconstruction.
5752 ret = map->num_stripes;
5753 free_extent_map(em);
5757 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5760 struct extent_map *em;
5761 struct map_lookup *map;
5762 unsigned long len = fs_info->sectorsize;
5764 if (!btrfs_fs_incompat(fs_info, RAID56))
5767 em = btrfs_get_chunk_map(fs_info, logical, len);
5769 if (!WARN_ON(IS_ERR(em))) {
5770 map = em->map_lookup;
5771 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5772 len = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
5773 free_extent_map(em);
5778 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5780 struct extent_map *em;
5781 struct map_lookup *map;
5784 if (!btrfs_fs_incompat(fs_info, RAID56))
5787 em = btrfs_get_chunk_map(fs_info, logical, len);
5789 if(!WARN_ON(IS_ERR(em))) {
5790 map = em->map_lookup;
5791 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5793 free_extent_map(em);
5798 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5799 struct map_lookup *map, int first,
5800 int dev_replace_is_ongoing)
5804 int preferred_mirror;
5806 struct btrfs_device *srcdev;
5809 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5811 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5812 num_stripes = map->sub_stripes;
5814 num_stripes = map->num_stripes;
5816 switch (fs_info->fs_devices->read_policy) {
5818 /* Shouldn't happen, just warn and use pid instead of failing */
5819 btrfs_warn_rl(fs_info,
5820 "unknown read_policy type %u, reset to pid",
5821 fs_info->fs_devices->read_policy);
5822 fs_info->fs_devices->read_policy = BTRFS_READ_POLICY_PID;
5824 case BTRFS_READ_POLICY_PID:
5825 preferred_mirror = first + (current->pid % num_stripes);
5829 if (dev_replace_is_ongoing &&
5830 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5831 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5832 srcdev = fs_info->dev_replace.srcdev;
5837 * try to avoid the drive that is the source drive for a
5838 * dev-replace procedure, only choose it if no other non-missing
5839 * mirror is available
5841 for (tolerance = 0; tolerance < 2; tolerance++) {
5842 if (map->stripes[preferred_mirror].dev->bdev &&
5843 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5844 return preferred_mirror;
5845 for (i = first; i < first + num_stripes; i++) {
5846 if (map->stripes[i].dev->bdev &&
5847 (tolerance || map->stripes[i].dev != srcdev))
5852 /* we couldn't find one that doesn't fail. Just return something
5853 * and the io error handling code will clean up eventually
5855 return preferred_mirror;
5858 static struct btrfs_io_context *alloc_btrfs_io_context(struct btrfs_fs_info *fs_info,
5862 struct btrfs_io_context *bioc;
5865 /* The size of btrfs_io_context */
5866 sizeof(struct btrfs_io_context) +
5867 /* Plus the variable array for the stripes */
5868 sizeof(struct btrfs_io_stripe) * (total_stripes),
5874 refcount_set(&bioc->refs, 1);
5876 bioc->fs_info = fs_info;
5877 bioc->replace_stripe_src = -1;
5878 bioc->full_stripe_logical = (u64)-1;
5879 bioc->logical = logical;
5884 void btrfs_get_bioc(struct btrfs_io_context *bioc)
5886 WARN_ON(!refcount_read(&bioc->refs));
5887 refcount_inc(&bioc->refs);
5890 void btrfs_put_bioc(struct btrfs_io_context *bioc)
5894 if (refcount_dec_and_test(&bioc->refs))
5899 * Please note that, discard won't be sent to target device of device
5902 struct btrfs_discard_stripe *btrfs_map_discard(struct btrfs_fs_info *fs_info,
5903 u64 logical, u64 *length_ret,
5906 struct extent_map *em;
5907 struct map_lookup *map;
5908 struct btrfs_discard_stripe *stripes;
5909 u64 length = *length_ret;
5914 u64 stripe_end_offset;
5918 u32 sub_stripes = 0;
5919 u32 stripes_per_dev = 0;
5920 u32 remaining_stripes = 0;
5921 u32 last_stripe = 0;
5925 em = btrfs_get_chunk_map(fs_info, logical, length);
5927 return ERR_CAST(em);
5929 map = em->map_lookup;
5931 /* we don't discard raid56 yet */
5932 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5937 offset = logical - em->start;
5938 length = min_t(u64, em->start + em->len - logical, length);
5939 *length_ret = length;
5942 * stripe_nr counts the total number of stripes we have to stride
5943 * to get to this block
5945 stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
5947 /* stripe_offset is the offset of this block in its stripe */
5948 stripe_offset = offset - btrfs_stripe_nr_to_offset(stripe_nr);
5950 stripe_nr_end = round_up(offset + length, BTRFS_STRIPE_LEN) >>
5951 BTRFS_STRIPE_LEN_SHIFT;
5952 stripe_cnt = stripe_nr_end - stripe_nr;
5953 stripe_end_offset = btrfs_stripe_nr_to_offset(stripe_nr_end) -
5956 * after this, stripe_nr is the number of stripes on this
5957 * device we have to walk to find the data, and stripe_index is
5958 * the number of our device in the stripe array
5962 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5963 BTRFS_BLOCK_GROUP_RAID10)) {
5964 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5967 sub_stripes = map->sub_stripes;
5969 factor = map->num_stripes / sub_stripes;
5970 *num_stripes = min_t(u64, map->num_stripes,
5971 sub_stripes * stripe_cnt);
5972 stripe_index = stripe_nr % factor;
5973 stripe_nr /= factor;
5974 stripe_index *= sub_stripes;
5976 remaining_stripes = stripe_cnt % factor;
5977 stripes_per_dev = stripe_cnt / factor;
5978 last_stripe = ((stripe_nr_end - 1) % factor) * sub_stripes;
5979 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5980 BTRFS_BLOCK_GROUP_DUP)) {
5981 *num_stripes = map->num_stripes;
5983 stripe_index = stripe_nr % map->num_stripes;
5984 stripe_nr /= map->num_stripes;
5987 stripes = kcalloc(*num_stripes, sizeof(*stripes), GFP_NOFS);
5993 for (i = 0; i < *num_stripes; i++) {
5994 stripes[i].physical =
5995 map->stripes[stripe_index].physical +
5996 stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr);
5997 stripes[i].dev = map->stripes[stripe_index].dev;
5999 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6000 BTRFS_BLOCK_GROUP_RAID10)) {
6001 stripes[i].length = btrfs_stripe_nr_to_offset(stripes_per_dev);
6003 if (i / sub_stripes < remaining_stripes)
6004 stripes[i].length += BTRFS_STRIPE_LEN;
6007 * Special for the first stripe and
6010 * |-------|...|-------|
6014 if (i < sub_stripes)
6015 stripes[i].length -= stripe_offset;
6017 if (stripe_index >= last_stripe &&
6018 stripe_index <= (last_stripe +
6020 stripes[i].length -= stripe_end_offset;
6022 if (i == sub_stripes - 1)
6025 stripes[i].length = length;
6029 if (stripe_index == map->num_stripes) {
6035 free_extent_map(em);
6038 free_extent_map(em);
6039 return ERR_PTR(ret);
6042 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6044 struct btrfs_block_group *cache;
6047 /* Non zoned filesystem does not use "to_copy" flag */
6048 if (!btrfs_is_zoned(fs_info))
6051 cache = btrfs_lookup_block_group(fs_info, logical);
6053 ret = test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
6055 btrfs_put_block_group(cache);
6059 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
6060 struct btrfs_io_context *bioc,
6061 struct btrfs_dev_replace *dev_replace,
6063 int *num_stripes_ret, int *max_errors_ret)
6065 u64 srcdev_devid = dev_replace->srcdev->devid;
6067 * At this stage, num_stripes is still the real number of stripes,
6068 * excluding the duplicated stripes.
6070 int num_stripes = *num_stripes_ret;
6071 int nr_extra_stripes = 0;
6072 int max_errors = *max_errors_ret;
6076 * A block group which has "to_copy" set will eventually be copied by
6077 * the dev-replace process. We can avoid cloning IO here.
6079 if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6083 * Duplicate the write operations while the dev-replace procedure is
6084 * running. Since the copying of the old disk to the new disk takes
6085 * place at run time while the filesystem is mounted writable, the
6086 * regular write operations to the old disk have to be duplicated to go
6087 * to the new disk as well.
6089 * Note that device->missing is handled by the caller, and that the
6090 * write to the old disk is already set up in the stripes array.
6092 for (i = 0; i < num_stripes; i++) {
6093 struct btrfs_io_stripe *old = &bioc->stripes[i];
6094 struct btrfs_io_stripe *new = &bioc->stripes[num_stripes + nr_extra_stripes];
6096 if (old->dev->devid != srcdev_devid)
6099 new->physical = old->physical;
6100 new->dev = dev_replace->tgtdev;
6101 if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK)
6102 bioc->replace_stripe_src = i;
6106 /* We can only have at most 2 extra nr_stripes (for DUP). */
6107 ASSERT(nr_extra_stripes <= 2);
6109 * For GET_READ_MIRRORS, we can only return at most 1 extra stripe for
6111 * If we have 2 extra stripes, only choose the one with smaller physical.
6113 if (op == BTRFS_MAP_GET_READ_MIRRORS && nr_extra_stripes == 2) {
6114 struct btrfs_io_stripe *first = &bioc->stripes[num_stripes];
6115 struct btrfs_io_stripe *second = &bioc->stripes[num_stripes + 1];
6117 /* Only DUP can have two extra stripes. */
6118 ASSERT(bioc->map_type & BTRFS_BLOCK_GROUP_DUP);
6121 * Swap the last stripe stripes and reduce @nr_extra_stripes.
6122 * The extra stripe would still be there, but won't be accessed.
6124 if (first->physical > second->physical) {
6125 swap(second->physical, first->physical);
6126 swap(second->dev, first->dev);
6131 *num_stripes_ret = num_stripes + nr_extra_stripes;
6132 *max_errors_ret = max_errors + nr_extra_stripes;
6133 bioc->replace_nr_stripes = nr_extra_stripes;
6136 static u64 btrfs_max_io_len(struct map_lookup *map, enum btrfs_map_op op,
6137 u64 offset, u32 *stripe_nr, u64 *stripe_offset,
6138 u64 *full_stripe_start)
6141 * Stripe_nr is the stripe where this block falls. stripe_offset is
6142 * the offset of this block in its stripe.
6144 *stripe_offset = offset & BTRFS_STRIPE_LEN_MASK;
6145 *stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6146 ASSERT(*stripe_offset < U32_MAX);
6148 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6149 unsigned long full_stripe_len =
6150 btrfs_stripe_nr_to_offset(nr_data_stripes(map));
6153 * For full stripe start, we use previously calculated
6154 * @stripe_nr. Align it to nr_data_stripes, then multiply with
6157 * By this we can avoid u64 division completely. And we have
6158 * to go rounddown(), not round_down(), as nr_data_stripes is
6159 * not ensured to be power of 2.
6161 *full_stripe_start =
6162 btrfs_stripe_nr_to_offset(
6163 rounddown(*stripe_nr, nr_data_stripes(map)));
6165 ASSERT(*full_stripe_start + full_stripe_len > offset);
6166 ASSERT(*full_stripe_start <= offset);
6168 * For writes to RAID56, allow to write a full stripe set, but
6169 * no straddling of stripe sets.
6171 if (op == BTRFS_MAP_WRITE)
6172 return full_stripe_len - (offset - *full_stripe_start);
6176 * For other RAID types and for RAID56 reads, allow a single stripe (on
6179 if (map->type & BTRFS_BLOCK_GROUP_STRIPE_MASK)
6180 return BTRFS_STRIPE_LEN - *stripe_offset;
6184 static int set_io_stripe(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6185 u64 logical, u64 *length, struct btrfs_io_stripe *dst,
6186 struct map_lookup *map, u32 stripe_index,
6187 u64 stripe_offset, u64 stripe_nr)
6189 dst->dev = map->stripes[stripe_index].dev;
6191 if (op == BTRFS_MAP_READ && btrfs_need_stripe_tree_update(fs_info, map->type))
6192 return btrfs_get_raid_extent_offset(fs_info, logical, length,
6193 map->type, stripe_index, dst);
6195 dst->physical = map->stripes[stripe_index].physical +
6196 stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr);
6201 * Map one logical range to one or more physical ranges.
6203 * @length: (Mandatory) mapped length of this run.
6204 * One logical range can be split into different segments
6205 * due to factors like zones and RAID0/5/6/10 stripe
6208 * @bioc_ret: (Mandatory) returned btrfs_io_context structure.
6209 * which has one or more physical ranges (btrfs_io_stripe)
6211 * Caller should call btrfs_put_bioc() to free it after use.
6213 * @smap: (Optional) single physical range optimization.
6214 * If the map request can be fulfilled by one single
6215 * physical range, and this is parameter is not NULL,
6216 * then @bioc_ret would be NULL, and @smap would be
6219 * @mirror_num_ret: (Mandatory) returned mirror number if the original
6222 * Mirror number 0 means to choose any live mirrors.
6224 * For non-RAID56 profiles, non-zero mirror_num means
6225 * the Nth mirror. (e.g. mirror_num 1 means the first
6228 * For RAID56 profile, mirror 1 means rebuild from P and
6229 * the remaining data stripes.
6231 * For RAID6 profile, mirror > 2 means mark another
6232 * data/P stripe error and rebuild from the remaining
6235 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6236 u64 logical, u64 *length,
6237 struct btrfs_io_context **bioc_ret,
6238 struct btrfs_io_stripe *smap, int *mirror_num_ret)
6240 struct extent_map *em;
6241 struct map_lookup *map;
6249 int mirror_num = (mirror_num_ret ? *mirror_num_ret : 0);
6253 struct btrfs_io_context *bioc = NULL;
6254 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6255 int dev_replace_is_ongoing = 0;
6256 u16 num_alloc_stripes;
6257 u64 raid56_full_stripe_start = (u64)-1;
6262 num_copies = btrfs_num_copies(fs_info, logical, fs_info->sectorsize);
6263 if (mirror_num > num_copies)
6266 em = btrfs_get_chunk_map(fs_info, logical, *length);
6270 map = em->map_lookup;
6271 data_stripes = nr_data_stripes(map);
6273 map_offset = logical - em->start;
6274 max_len = btrfs_max_io_len(map, op, map_offset, &stripe_nr,
6275 &stripe_offset, &raid56_full_stripe_start);
6276 *length = min_t(u64, em->len - map_offset, max_len);
6278 down_read(&dev_replace->rwsem);
6279 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6281 * Hold the semaphore for read during the whole operation, write is
6282 * requested at commit time but must wait.
6284 if (!dev_replace_is_ongoing)
6285 up_read(&dev_replace->rwsem);
6289 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6290 stripe_index = stripe_nr % map->num_stripes;
6291 stripe_nr /= map->num_stripes;
6292 if (op == BTRFS_MAP_READ)
6294 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6295 if (op != BTRFS_MAP_READ) {
6296 num_stripes = map->num_stripes;
6297 } else if (mirror_num) {
6298 stripe_index = mirror_num - 1;
6300 stripe_index = find_live_mirror(fs_info, map, 0,
6301 dev_replace_is_ongoing);
6302 mirror_num = stripe_index + 1;
6305 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6306 if (op != BTRFS_MAP_READ) {
6307 num_stripes = map->num_stripes;
6308 } else if (mirror_num) {
6309 stripe_index = mirror_num - 1;
6314 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6315 u32 factor = map->num_stripes / map->sub_stripes;
6317 stripe_index = (stripe_nr % factor) * map->sub_stripes;
6318 stripe_nr /= factor;
6320 if (op != BTRFS_MAP_READ)
6321 num_stripes = map->sub_stripes;
6322 else if (mirror_num)
6323 stripe_index += mirror_num - 1;
6325 int old_stripe_index = stripe_index;
6326 stripe_index = find_live_mirror(fs_info, map,
6328 dev_replace_is_ongoing);
6329 mirror_num = stripe_index - old_stripe_index + 1;
6332 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6333 if (op != BTRFS_MAP_READ || mirror_num > 1) {
6335 * Needs full stripe mapping.
6337 * Push stripe_nr back to the start of the full stripe
6338 * For those cases needing a full stripe, @stripe_nr
6339 * is the full stripe number.
6341 * Originally we go raid56_full_stripe_start / full_stripe_len,
6342 * but that can be expensive. Here we just divide
6343 * @stripe_nr with @data_stripes.
6345 stripe_nr /= data_stripes;
6347 /* RAID[56] write or recovery. Return all stripes */
6348 num_stripes = map->num_stripes;
6349 max_errors = btrfs_chunk_max_errors(map);
6351 /* Return the length to the full stripe end */
6352 *length = min(logical + *length,
6353 raid56_full_stripe_start + em->start +
6354 btrfs_stripe_nr_to_offset(data_stripes)) -
6359 ASSERT(mirror_num <= 1);
6360 /* Just grab the data stripe directly. */
6361 stripe_index = stripe_nr % data_stripes;
6362 stripe_nr /= data_stripes;
6364 /* We distribute the parity blocks across stripes */
6365 stripe_index = (stripe_nr + stripe_index) % map->num_stripes;
6366 if (op == BTRFS_MAP_READ && mirror_num < 1)
6371 * After this, stripe_nr is the number of stripes on this
6372 * device we have to walk to find the data, and stripe_index is
6373 * the number of our device in the stripe array
6375 stripe_index = stripe_nr % map->num_stripes;
6376 stripe_nr /= map->num_stripes;
6377 mirror_num = stripe_index + 1;
6379 if (stripe_index >= map->num_stripes) {
6381 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6382 stripe_index, map->num_stripes);
6387 num_alloc_stripes = num_stripes;
6388 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6389 op != BTRFS_MAP_READ)
6391 * For replace case, we need to add extra stripes for extra
6392 * duplicated stripes.
6394 * For both WRITE and GET_READ_MIRRORS, we may have at most
6395 * 2 more stripes (DUP types, otherwise 1).
6397 num_alloc_stripes += 2;
6400 * If this I/O maps to a single device, try to return the device and
6401 * physical block information on the stack instead of allocating an
6402 * I/O context structure.
6404 if (smap && num_alloc_stripes == 1 &&
6405 !(btrfs_need_stripe_tree_update(fs_info, map->type) &&
6406 op != BTRFS_MAP_READ) &&
6407 !((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) && mirror_num > 1)) {
6408 ret = set_io_stripe(fs_info, op, logical, length, smap, map,
6409 stripe_index, stripe_offset, stripe_nr);
6411 *mirror_num_ret = mirror_num;
6416 bioc = alloc_btrfs_io_context(fs_info, logical, num_alloc_stripes);
6421 bioc->map_type = map->type;
6424 * For RAID56 full map, we need to make sure the stripes[] follows the
6425 * rule that data stripes are all ordered, then followed with P and Q
6428 * It's still mostly the same as other profiles, just with extra rotation.
6430 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
6431 (op != BTRFS_MAP_READ || mirror_num > 1)) {
6433 * For RAID56 @stripe_nr is already the number of full stripes
6434 * before us, which is also the rotation value (needs to modulo
6435 * with num_stripes).
6437 * In this case, we just add @stripe_nr with @i, then do the
6438 * modulo, to reduce one modulo call.
6440 bioc->full_stripe_logical = em->start +
6441 btrfs_stripe_nr_to_offset(stripe_nr * data_stripes);
6442 for (int i = 0; i < num_stripes; i++) {
6443 ret = set_io_stripe(fs_info, op, logical, length,
6444 &bioc->stripes[i], map,
6445 (i + stripe_nr) % num_stripes,
6446 stripe_offset, stripe_nr);
6452 * For all other non-RAID56 profiles, just copy the target
6453 * stripe into the bioc.
6455 for (i = 0; i < num_stripes; i++) {
6456 ret = set_io_stripe(fs_info, op, logical, length,
6457 &bioc->stripes[i], map, stripe_index,
6458 stripe_offset, stripe_nr);
6467 btrfs_put_bioc(bioc);
6471 if (op != BTRFS_MAP_READ)
6472 max_errors = btrfs_chunk_max_errors(map);
6474 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6475 op != BTRFS_MAP_READ) {
6476 handle_ops_on_dev_replace(op, bioc, dev_replace, logical,
6477 &num_stripes, &max_errors);
6481 bioc->num_stripes = num_stripes;
6482 bioc->max_errors = max_errors;
6483 bioc->mirror_num = mirror_num;
6486 if (dev_replace_is_ongoing) {
6487 lockdep_assert_held(&dev_replace->rwsem);
6488 /* Unlock and let waiting writers proceed */
6489 up_read(&dev_replace->rwsem);
6491 free_extent_map(em);
6495 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args *args,
6496 const struct btrfs_fs_devices *fs_devices)
6498 if (args->fsid == NULL)
6500 if (memcmp(fs_devices->metadata_uuid, args->fsid, BTRFS_FSID_SIZE) == 0)
6505 static bool dev_args_match_device(const struct btrfs_dev_lookup_args *args,
6506 const struct btrfs_device *device)
6508 if (args->missing) {
6509 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) &&
6515 if (device->devid != args->devid)
6517 if (args->uuid && memcmp(device->uuid, args->uuid, BTRFS_UUID_SIZE) != 0)
6523 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6526 * If devid and uuid are both specified, the match must be exact, otherwise
6527 * only devid is used.
6529 struct btrfs_device *btrfs_find_device(const struct btrfs_fs_devices *fs_devices,
6530 const struct btrfs_dev_lookup_args *args)
6532 struct btrfs_device *device;
6533 struct btrfs_fs_devices *seed_devs;
6535 if (dev_args_match_fs_devices(args, fs_devices)) {
6536 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6537 if (dev_args_match_device(args, device))
6542 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6543 if (!dev_args_match_fs_devices(args, seed_devs))
6545 list_for_each_entry(device, &seed_devs->devices, dev_list) {
6546 if (dev_args_match_device(args, device))
6554 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6555 u64 devid, u8 *dev_uuid)
6557 struct btrfs_device *device;
6558 unsigned int nofs_flag;
6561 * We call this under the chunk_mutex, so we want to use NOFS for this
6562 * allocation, however we don't want to change btrfs_alloc_device() to
6563 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6567 nofs_flag = memalloc_nofs_save();
6568 device = btrfs_alloc_device(NULL, &devid, dev_uuid, NULL);
6569 memalloc_nofs_restore(nofs_flag);
6573 list_add(&device->dev_list, &fs_devices->devices);
6574 device->fs_devices = fs_devices;
6575 fs_devices->num_devices++;
6577 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6578 fs_devices->missing_devices++;
6584 * Allocate new device struct, set up devid and UUID.
6586 * @fs_info: used only for generating a new devid, can be NULL if
6587 * devid is provided (i.e. @devid != NULL).
6588 * @devid: a pointer to devid for this device. If NULL a new devid
6590 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6592 * @path: a pointer to device path if available, NULL otherwise.
6594 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6595 * on error. Returned struct is not linked onto any lists and must be
6596 * destroyed with btrfs_free_device.
6598 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6599 const u64 *devid, const u8 *uuid,
6602 struct btrfs_device *dev;
6605 if (WARN_ON(!devid && !fs_info))
6606 return ERR_PTR(-EINVAL);
6608 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
6610 return ERR_PTR(-ENOMEM);
6612 INIT_LIST_HEAD(&dev->dev_list);
6613 INIT_LIST_HEAD(&dev->dev_alloc_list);
6614 INIT_LIST_HEAD(&dev->post_commit_list);
6616 atomic_set(&dev->dev_stats_ccnt, 0);
6617 btrfs_device_data_ordered_init(dev);
6618 extent_io_tree_init(fs_info, &dev->alloc_state, IO_TREE_DEVICE_ALLOC_STATE);
6625 ret = find_next_devid(fs_info, &tmp);
6627 btrfs_free_device(dev);
6628 return ERR_PTR(ret);
6634 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6636 generate_random_uuid(dev->uuid);
6639 struct rcu_string *name;
6641 name = rcu_string_strdup(path, GFP_KERNEL);
6643 btrfs_free_device(dev);
6644 return ERR_PTR(-ENOMEM);
6646 rcu_assign_pointer(dev->name, name);
6652 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6653 u64 devid, u8 *uuid, bool error)
6656 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6659 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6663 u64 btrfs_calc_stripe_length(const struct extent_map *em)
6665 const struct map_lookup *map = em->map_lookup;
6666 const int data_stripes = calc_data_stripes(map->type, map->num_stripes);
6668 return div_u64(em->len, data_stripes);
6671 #if BITS_PER_LONG == 32
6673 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
6674 * can't be accessed on 32bit systems.
6676 * This function do mount time check to reject the fs if it already has
6677 * metadata chunk beyond that limit.
6679 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6680 u64 logical, u64 length, u64 type)
6682 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6685 if (logical + length < MAX_LFS_FILESIZE)
6688 btrfs_err_32bit_limit(fs_info);
6693 * This is to give early warning for any metadata chunk reaching
6694 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
6695 * Although we can still access the metadata, it's not going to be possible
6696 * once the limit is reached.
6698 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6699 u64 logical, u64 length, u64 type)
6701 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6704 if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6707 btrfs_warn_32bit_limit(fs_info);
6711 static struct btrfs_device *handle_missing_device(struct btrfs_fs_info *fs_info,
6712 u64 devid, u8 *uuid)
6714 struct btrfs_device *dev;
6716 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6717 btrfs_report_missing_device(fs_info, devid, uuid, true);
6718 return ERR_PTR(-ENOENT);
6721 dev = add_missing_dev(fs_info->fs_devices, devid, uuid);
6723 btrfs_err(fs_info, "failed to init missing device %llu: %ld",
6724 devid, PTR_ERR(dev));
6727 btrfs_report_missing_device(fs_info, devid, uuid, false);
6732 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6733 struct btrfs_chunk *chunk)
6735 BTRFS_DEV_LOOKUP_ARGS(args);
6736 struct btrfs_fs_info *fs_info = leaf->fs_info;
6737 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6738 struct map_lookup *map;
6739 struct extent_map *em;
6744 u8 uuid[BTRFS_UUID_SIZE];
6750 logical = key->offset;
6751 length = btrfs_chunk_length(leaf, chunk);
6752 type = btrfs_chunk_type(leaf, chunk);
6753 index = btrfs_bg_flags_to_raid_index(type);
6754 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6756 #if BITS_PER_LONG == 32
6757 ret = check_32bit_meta_chunk(fs_info, logical, length, type);
6760 warn_32bit_meta_chunk(fs_info, logical, length, type);
6764 * Only need to verify chunk item if we're reading from sys chunk array,
6765 * as chunk item in tree block is already verified by tree-checker.
6767 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6768 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6773 read_lock(&map_tree->lock);
6774 em = lookup_extent_mapping(map_tree, logical, 1);
6775 read_unlock(&map_tree->lock);
6777 /* already mapped? */
6778 if (em && em->start <= logical && em->start + em->len > logical) {
6779 free_extent_map(em);
6782 free_extent_map(em);
6785 em = alloc_extent_map();
6788 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6790 free_extent_map(em);
6794 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6795 em->map_lookup = map;
6796 em->start = logical;
6799 em->block_start = 0;
6800 em->block_len = em->len;
6802 map->num_stripes = num_stripes;
6803 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6804 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6807 * We can't use the sub_stripes value, as for profiles other than
6808 * RAID10, they may have 0 as sub_stripes for filesystems created by
6809 * older mkfs (<v5.4).
6810 * In that case, it can cause divide-by-zero errors later.
6811 * Since currently sub_stripes is fixed for each profile, let's
6812 * use the trusted value instead.
6814 map->sub_stripes = btrfs_raid_array[index].sub_stripes;
6815 map->verified_stripes = 0;
6816 em->orig_block_len = btrfs_calc_stripe_length(em);
6817 for (i = 0; i < num_stripes; i++) {
6818 map->stripes[i].physical =
6819 btrfs_stripe_offset_nr(leaf, chunk, i);
6820 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6822 read_extent_buffer(leaf, uuid, (unsigned long)
6823 btrfs_stripe_dev_uuid_nr(chunk, i),
6826 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, &args);
6827 if (!map->stripes[i].dev) {
6828 map->stripes[i].dev = handle_missing_device(fs_info,
6830 if (IS_ERR(map->stripes[i].dev)) {
6831 ret = PTR_ERR(map->stripes[i].dev);
6832 free_extent_map(em);
6837 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6838 &(map->stripes[i].dev->dev_state));
6841 write_lock(&map_tree->lock);
6842 ret = add_extent_mapping(map_tree, em, 0);
6843 write_unlock(&map_tree->lock);
6846 "failed to add chunk map, start=%llu len=%llu: %d",
6847 em->start, em->len, ret);
6849 free_extent_map(em);
6854 static void fill_device_from_item(struct extent_buffer *leaf,
6855 struct btrfs_dev_item *dev_item,
6856 struct btrfs_device *device)
6860 device->devid = btrfs_device_id(leaf, dev_item);
6861 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6862 device->total_bytes = device->disk_total_bytes;
6863 device->commit_total_bytes = device->disk_total_bytes;
6864 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6865 device->commit_bytes_used = device->bytes_used;
6866 device->type = btrfs_device_type(leaf, dev_item);
6867 device->io_align = btrfs_device_io_align(leaf, dev_item);
6868 device->io_width = btrfs_device_io_width(leaf, dev_item);
6869 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6870 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6871 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6873 ptr = btrfs_device_uuid(dev_item);
6874 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6877 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6880 struct btrfs_fs_devices *fs_devices;
6883 lockdep_assert_held(&uuid_mutex);
6886 /* This will match only for multi-device seed fs */
6887 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
6888 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6892 fs_devices = find_fsid(fsid, NULL);
6894 if (!btrfs_test_opt(fs_info, DEGRADED))
6895 return ERR_PTR(-ENOENT);
6897 fs_devices = alloc_fs_devices(fsid);
6898 if (IS_ERR(fs_devices))
6901 fs_devices->seeding = true;
6902 fs_devices->opened = 1;
6907 * Upon first call for a seed fs fsid, just create a private copy of the
6908 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
6910 fs_devices = clone_fs_devices(fs_devices);
6911 if (IS_ERR(fs_devices))
6914 ret = open_fs_devices(fs_devices, BLK_OPEN_READ, fs_info->bdev_holder);
6916 free_fs_devices(fs_devices);
6917 return ERR_PTR(ret);
6920 if (!fs_devices->seeding) {
6921 close_fs_devices(fs_devices);
6922 free_fs_devices(fs_devices);
6923 return ERR_PTR(-EINVAL);
6926 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
6931 static int read_one_dev(struct extent_buffer *leaf,
6932 struct btrfs_dev_item *dev_item)
6934 BTRFS_DEV_LOOKUP_ARGS(args);
6935 struct btrfs_fs_info *fs_info = leaf->fs_info;
6936 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6937 struct btrfs_device *device;
6940 u8 fs_uuid[BTRFS_FSID_SIZE];
6941 u8 dev_uuid[BTRFS_UUID_SIZE];
6943 devid = btrfs_device_id(leaf, dev_item);
6945 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6947 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6949 args.uuid = dev_uuid;
6950 args.fsid = fs_uuid;
6952 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6953 fs_devices = open_seed_devices(fs_info, fs_uuid);
6954 if (IS_ERR(fs_devices))
6955 return PTR_ERR(fs_devices);
6958 device = btrfs_find_device(fs_info->fs_devices, &args);
6960 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6961 btrfs_report_missing_device(fs_info, devid,
6966 device = add_missing_dev(fs_devices, devid, dev_uuid);
6967 if (IS_ERR(device)) {
6969 "failed to add missing dev %llu: %ld",
6970 devid, PTR_ERR(device));
6971 return PTR_ERR(device);
6973 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6975 if (!device->bdev) {
6976 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6977 btrfs_report_missing_device(fs_info,
6978 devid, dev_uuid, true);
6981 btrfs_report_missing_device(fs_info, devid,
6985 if (!device->bdev &&
6986 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6988 * this happens when a device that was properly setup
6989 * in the device info lists suddenly goes bad.
6990 * device->bdev is NULL, and so we have to set
6991 * device->missing to one here
6993 device->fs_devices->missing_devices++;
6994 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6997 /* Move the device to its own fs_devices */
6998 if (device->fs_devices != fs_devices) {
6999 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7000 &device->dev_state));
7002 list_move(&device->dev_list, &fs_devices->devices);
7003 device->fs_devices->num_devices--;
7004 fs_devices->num_devices++;
7006 device->fs_devices->missing_devices--;
7007 fs_devices->missing_devices++;
7009 device->fs_devices = fs_devices;
7013 if (device->fs_devices != fs_info->fs_devices) {
7014 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7015 if (device->generation !=
7016 btrfs_device_generation(leaf, dev_item))
7020 fill_device_from_item(leaf, dev_item, device);
7022 u64 max_total_bytes = bdev_nr_bytes(device->bdev);
7024 if (device->total_bytes > max_total_bytes) {
7026 "device total_bytes should be at most %llu but found %llu",
7027 max_total_bytes, device->total_bytes);
7031 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7032 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7033 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7034 device->fs_devices->total_rw_bytes += device->total_bytes;
7035 atomic64_add(device->total_bytes - device->bytes_used,
7036 &fs_info->free_chunk_space);
7042 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7044 struct btrfs_super_block *super_copy = fs_info->super_copy;
7045 struct extent_buffer *sb;
7046 struct btrfs_disk_key *disk_key;
7047 struct btrfs_chunk *chunk;
7049 unsigned long sb_array_offset;
7056 struct btrfs_key key;
7058 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7061 * We allocated a dummy extent, just to use extent buffer accessors.
7062 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
7063 * that's fine, we will not go beyond system chunk array anyway.
7065 sb = alloc_dummy_extent_buffer(fs_info, BTRFS_SUPER_INFO_OFFSET);
7068 set_extent_buffer_uptodate(sb);
7070 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7071 array_size = btrfs_super_sys_array_size(super_copy);
7073 array_ptr = super_copy->sys_chunk_array;
7074 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7077 while (cur_offset < array_size) {
7078 disk_key = (struct btrfs_disk_key *)array_ptr;
7079 len = sizeof(*disk_key);
7080 if (cur_offset + len > array_size)
7081 goto out_short_read;
7083 btrfs_disk_key_to_cpu(&key, disk_key);
7086 sb_array_offset += len;
7089 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
7091 "unexpected item type %u in sys_array at offset %u",
7092 (u32)key.type, cur_offset);
7097 chunk = (struct btrfs_chunk *)sb_array_offset;
7099 * At least one btrfs_chunk with one stripe must be present,
7100 * exact stripe count check comes afterwards
7102 len = btrfs_chunk_item_size(1);
7103 if (cur_offset + len > array_size)
7104 goto out_short_read;
7106 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7109 "invalid number of stripes %u in sys_array at offset %u",
7110 num_stripes, cur_offset);
7115 type = btrfs_chunk_type(sb, chunk);
7116 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7118 "invalid chunk type %llu in sys_array at offset %u",
7124 len = btrfs_chunk_item_size(num_stripes);
7125 if (cur_offset + len > array_size)
7126 goto out_short_read;
7128 ret = read_one_chunk(&key, sb, chunk);
7133 sb_array_offset += len;
7136 clear_extent_buffer_uptodate(sb);
7137 free_extent_buffer_stale(sb);
7141 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7143 clear_extent_buffer_uptodate(sb);
7144 free_extent_buffer_stale(sb);
7149 * Check if all chunks in the fs are OK for read-write degraded mount
7151 * If the @failing_dev is specified, it's accounted as missing.
7153 * Return true if all chunks meet the minimal RW mount requirements.
7154 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7156 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7157 struct btrfs_device *failing_dev)
7159 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7160 struct extent_map *em;
7164 read_lock(&map_tree->lock);
7165 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7166 read_unlock(&map_tree->lock);
7167 /* No chunk at all? Return false anyway */
7173 struct map_lookup *map;
7178 map = em->map_lookup;
7180 btrfs_get_num_tolerated_disk_barrier_failures(
7182 for (i = 0; i < map->num_stripes; i++) {
7183 struct btrfs_device *dev = map->stripes[i].dev;
7185 if (!dev || !dev->bdev ||
7186 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7187 dev->last_flush_error)
7189 else if (failing_dev && failing_dev == dev)
7192 if (missing > max_tolerated) {
7195 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7196 em->start, missing, max_tolerated);
7197 free_extent_map(em);
7201 next_start = extent_map_end(em);
7202 free_extent_map(em);
7204 read_lock(&map_tree->lock);
7205 em = lookup_extent_mapping(map_tree, next_start,
7206 (u64)(-1) - next_start);
7207 read_unlock(&map_tree->lock);
7213 static void readahead_tree_node_children(struct extent_buffer *node)
7216 const int nr_items = btrfs_header_nritems(node);
7218 for (i = 0; i < nr_items; i++)
7219 btrfs_readahead_node_child(node, i);
7222 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7224 struct btrfs_root *root = fs_info->chunk_root;
7225 struct btrfs_path *path;
7226 struct extent_buffer *leaf;
7227 struct btrfs_key key;
7228 struct btrfs_key found_key;
7233 u64 last_ra_node = 0;
7235 path = btrfs_alloc_path();
7240 * uuid_mutex is needed only if we are mounting a sprout FS
7241 * otherwise we don't need it.
7243 mutex_lock(&uuid_mutex);
7246 * It is possible for mount and umount to race in such a way that
7247 * we execute this code path, but open_fs_devices failed to clear
7248 * total_rw_bytes. We certainly want it cleared before reading the
7249 * device items, so clear it here.
7251 fs_info->fs_devices->total_rw_bytes = 0;
7254 * Lockdep complains about possible circular locking dependency between
7255 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7256 * used for freeze procection of a fs (struct super_block.s_writers),
7257 * which we take when starting a transaction, and extent buffers of the
7258 * chunk tree if we call read_one_dev() while holding a lock on an
7259 * extent buffer of the chunk tree. Since we are mounting the filesystem
7260 * and at this point there can't be any concurrent task modifying the
7261 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7263 ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
7264 path->skip_locking = 1;
7267 * Read all device items, and then all the chunk items. All
7268 * device items are found before any chunk item (their object id
7269 * is smaller than the lowest possible object id for a chunk
7270 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7272 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7275 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
7276 struct extent_buffer *node = path->nodes[1];
7278 leaf = path->nodes[0];
7279 slot = path->slots[0];
7282 if (last_ra_node != node->start) {
7283 readahead_tree_node_children(node);
7284 last_ra_node = node->start;
7287 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7288 struct btrfs_dev_item *dev_item;
7289 dev_item = btrfs_item_ptr(leaf, slot,
7290 struct btrfs_dev_item);
7291 ret = read_one_dev(leaf, dev_item);
7295 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7296 struct btrfs_chunk *chunk;
7299 * We are only called at mount time, so no need to take
7300 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7301 * we always lock first fs_info->chunk_mutex before
7302 * acquiring any locks on the chunk tree. This is a
7303 * requirement for chunk allocation, see the comment on
7304 * top of btrfs_chunk_alloc() for details.
7306 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7307 ret = read_one_chunk(&found_key, leaf, chunk);
7312 /* Catch error found during iteration */
7319 * After loading chunk tree, we've got all device information,
7320 * do another round of validation checks.
7322 if (total_dev != fs_info->fs_devices->total_devices) {
7324 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7325 btrfs_super_num_devices(fs_info->super_copy),
7327 fs_info->fs_devices->total_devices = total_dev;
7328 btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
7330 if (btrfs_super_total_bytes(fs_info->super_copy) <
7331 fs_info->fs_devices->total_rw_bytes) {
7333 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7334 btrfs_super_total_bytes(fs_info->super_copy),
7335 fs_info->fs_devices->total_rw_bytes);
7341 mutex_unlock(&uuid_mutex);
7343 btrfs_free_path(path);
7347 int btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7349 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7350 struct btrfs_device *device;
7353 fs_devices->fs_info = fs_info;
7355 mutex_lock(&fs_devices->device_list_mutex);
7356 list_for_each_entry(device, &fs_devices->devices, dev_list)
7357 device->fs_info = fs_info;
7359 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7360 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7361 device->fs_info = fs_info;
7362 ret = btrfs_get_dev_zone_info(device, false);
7367 seed_devs->fs_info = fs_info;
7369 mutex_unlock(&fs_devices->device_list_mutex);
7374 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7375 const struct btrfs_dev_stats_item *ptr,
7380 read_extent_buffer(eb, &val,
7381 offsetof(struct btrfs_dev_stats_item, values) +
7382 ((unsigned long)ptr) + (index * sizeof(u64)),
7387 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7388 struct btrfs_dev_stats_item *ptr,
7391 write_extent_buffer(eb, &val,
7392 offsetof(struct btrfs_dev_stats_item, values) +
7393 ((unsigned long)ptr) + (index * sizeof(u64)),
7397 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7398 struct btrfs_path *path)
7400 struct btrfs_dev_stats_item *ptr;
7401 struct extent_buffer *eb;
7402 struct btrfs_key key;
7406 if (!device->fs_info->dev_root)
7409 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7410 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7411 key.offset = device->devid;
7412 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7414 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7415 btrfs_dev_stat_set(device, i, 0);
7416 device->dev_stats_valid = 1;
7417 btrfs_release_path(path);
7418 return ret < 0 ? ret : 0;
7420 slot = path->slots[0];
7421 eb = path->nodes[0];
7422 item_size = btrfs_item_size(eb, slot);
7424 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7426 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7427 if (item_size >= (1 + i) * sizeof(__le64))
7428 btrfs_dev_stat_set(device, i,
7429 btrfs_dev_stats_value(eb, ptr, i));
7431 btrfs_dev_stat_set(device, i, 0);
7434 device->dev_stats_valid = 1;
7435 btrfs_dev_stat_print_on_load(device);
7436 btrfs_release_path(path);
7441 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7443 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7444 struct btrfs_device *device;
7445 struct btrfs_path *path = NULL;
7448 path = btrfs_alloc_path();
7452 mutex_lock(&fs_devices->device_list_mutex);
7453 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7454 ret = btrfs_device_init_dev_stats(device, path);
7458 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7459 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7460 ret = btrfs_device_init_dev_stats(device, path);
7466 mutex_unlock(&fs_devices->device_list_mutex);
7468 btrfs_free_path(path);
7472 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7473 struct btrfs_device *device)
7475 struct btrfs_fs_info *fs_info = trans->fs_info;
7476 struct btrfs_root *dev_root = fs_info->dev_root;
7477 struct btrfs_path *path;
7478 struct btrfs_key key;
7479 struct extent_buffer *eb;
7480 struct btrfs_dev_stats_item *ptr;
7484 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7485 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7486 key.offset = device->devid;
7488 path = btrfs_alloc_path();
7491 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7493 btrfs_warn_in_rcu(fs_info,
7494 "error %d while searching for dev_stats item for device %s",
7495 ret, btrfs_dev_name(device));
7500 btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7501 /* need to delete old one and insert a new one */
7502 ret = btrfs_del_item(trans, dev_root, path);
7504 btrfs_warn_in_rcu(fs_info,
7505 "delete too small dev_stats item for device %s failed %d",
7506 btrfs_dev_name(device), ret);
7513 /* need to insert a new item */
7514 btrfs_release_path(path);
7515 ret = btrfs_insert_empty_item(trans, dev_root, path,
7516 &key, sizeof(*ptr));
7518 btrfs_warn_in_rcu(fs_info,
7519 "insert dev_stats item for device %s failed %d",
7520 btrfs_dev_name(device), ret);
7525 eb = path->nodes[0];
7526 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7527 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7528 btrfs_set_dev_stats_value(eb, ptr, i,
7529 btrfs_dev_stat_read(device, i));
7530 btrfs_mark_buffer_dirty(trans, eb);
7533 btrfs_free_path(path);
7538 * called from commit_transaction. Writes all changed device stats to disk.
7540 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7542 struct btrfs_fs_info *fs_info = trans->fs_info;
7543 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7544 struct btrfs_device *device;
7548 mutex_lock(&fs_devices->device_list_mutex);
7549 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7550 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7551 if (!device->dev_stats_valid || stats_cnt == 0)
7556 * There is a LOAD-LOAD control dependency between the value of
7557 * dev_stats_ccnt and updating the on-disk values which requires
7558 * reading the in-memory counters. Such control dependencies
7559 * require explicit read memory barriers.
7561 * This memory barriers pairs with smp_mb__before_atomic in
7562 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7563 * barrier implied by atomic_xchg in
7564 * btrfs_dev_stats_read_and_reset
7568 ret = update_dev_stat_item(trans, device);
7570 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7572 mutex_unlock(&fs_devices->device_list_mutex);
7577 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7579 btrfs_dev_stat_inc(dev, index);
7581 if (!dev->dev_stats_valid)
7583 btrfs_err_rl_in_rcu(dev->fs_info,
7584 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7585 btrfs_dev_name(dev),
7586 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7587 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7588 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7589 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7590 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7593 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7597 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7598 if (btrfs_dev_stat_read(dev, i) != 0)
7600 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7601 return; /* all values == 0, suppress message */
7603 btrfs_info_in_rcu(dev->fs_info,
7604 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7605 btrfs_dev_name(dev),
7606 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7607 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7608 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7609 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7610 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7613 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7614 struct btrfs_ioctl_get_dev_stats *stats)
7616 BTRFS_DEV_LOOKUP_ARGS(args);
7617 struct btrfs_device *dev;
7618 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7621 mutex_lock(&fs_devices->device_list_mutex);
7622 args.devid = stats->devid;
7623 dev = btrfs_find_device(fs_info->fs_devices, &args);
7624 mutex_unlock(&fs_devices->device_list_mutex);
7627 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7629 } else if (!dev->dev_stats_valid) {
7630 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7632 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7633 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7634 if (stats->nr_items > i)
7636 btrfs_dev_stat_read_and_reset(dev, i);
7638 btrfs_dev_stat_set(dev, i, 0);
7640 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7641 current->comm, task_pid_nr(current));
7643 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7644 if (stats->nr_items > i)
7645 stats->values[i] = btrfs_dev_stat_read(dev, i);
7647 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7648 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7653 * Update the size and bytes used for each device where it changed. This is
7654 * delayed since we would otherwise get errors while writing out the
7657 * Must be invoked during transaction commit.
7659 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7661 struct btrfs_device *curr, *next;
7663 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7665 if (list_empty(&trans->dev_update_list))
7669 * We don't need the device_list_mutex here. This list is owned by the
7670 * transaction and the transaction must complete before the device is
7673 mutex_lock(&trans->fs_info->chunk_mutex);
7674 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7676 list_del_init(&curr->post_commit_list);
7677 curr->commit_total_bytes = curr->disk_total_bytes;
7678 curr->commit_bytes_used = curr->bytes_used;
7680 mutex_unlock(&trans->fs_info->chunk_mutex);
7684 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7686 int btrfs_bg_type_to_factor(u64 flags)
7688 const int index = btrfs_bg_flags_to_raid_index(flags);
7690 return btrfs_raid_array[index].ncopies;
7695 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7696 u64 chunk_offset, u64 devid,
7697 u64 physical_offset, u64 physical_len)
7699 struct btrfs_dev_lookup_args args = { .devid = devid };
7700 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7701 struct extent_map *em;
7702 struct map_lookup *map;
7703 struct btrfs_device *dev;
7709 read_lock(&em_tree->lock);
7710 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7711 read_unlock(&em_tree->lock);
7715 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7716 physical_offset, devid);
7721 map = em->map_lookup;
7722 stripe_len = btrfs_calc_stripe_length(em);
7723 if (physical_len != stripe_len) {
7725 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7726 physical_offset, devid, em->start, physical_len,
7733 * Very old mkfs.btrfs (before v4.1) will not respect the reserved
7734 * space. Although kernel can handle it without problem, better to warn
7737 if (physical_offset < BTRFS_DEVICE_RANGE_RESERVED)
7739 "devid %llu physical %llu len %llu inside the reserved space",
7740 devid, physical_offset, physical_len);
7742 for (i = 0; i < map->num_stripes; i++) {
7743 if (map->stripes[i].dev->devid == devid &&
7744 map->stripes[i].physical == physical_offset) {
7746 if (map->verified_stripes >= map->num_stripes) {
7748 "too many dev extents for chunk %llu found",
7753 map->verified_stripes++;
7759 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7760 physical_offset, devid);
7764 /* Make sure no dev extent is beyond device boundary */
7765 dev = btrfs_find_device(fs_info->fs_devices, &args);
7767 btrfs_err(fs_info, "failed to find devid %llu", devid);
7772 if (physical_offset + physical_len > dev->disk_total_bytes) {
7774 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7775 devid, physical_offset, physical_len,
7776 dev->disk_total_bytes);
7781 if (dev->zone_info) {
7782 u64 zone_size = dev->zone_info->zone_size;
7784 if (!IS_ALIGNED(physical_offset, zone_size) ||
7785 !IS_ALIGNED(physical_len, zone_size)) {
7787 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
7788 devid, physical_offset, physical_len);
7795 free_extent_map(em);
7799 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7801 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7802 struct extent_map *em;
7803 struct rb_node *node;
7806 read_lock(&em_tree->lock);
7807 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7808 em = rb_entry(node, struct extent_map, rb_node);
7809 if (em->map_lookup->num_stripes !=
7810 em->map_lookup->verified_stripes) {
7812 "chunk %llu has missing dev extent, have %d expect %d",
7813 em->start, em->map_lookup->verified_stripes,
7814 em->map_lookup->num_stripes);
7820 read_unlock(&em_tree->lock);
7825 * Ensure that all dev extents are mapped to correct chunk, otherwise
7826 * later chunk allocation/free would cause unexpected behavior.
7828 * NOTE: This will iterate through the whole device tree, which should be of
7829 * the same size level as the chunk tree. This slightly increases mount time.
7831 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7833 struct btrfs_path *path;
7834 struct btrfs_root *root = fs_info->dev_root;
7835 struct btrfs_key key;
7837 u64 prev_dev_ext_end = 0;
7841 * We don't have a dev_root because we mounted with ignorebadroots and
7842 * failed to load the root, so we want to skip the verification in this
7845 * However if the dev root is fine, but the tree itself is corrupted
7846 * we'd still fail to mount. This verification is only to make sure
7847 * writes can happen safely, so instead just bypass this check
7848 * completely in the case of IGNOREBADROOTS.
7850 if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
7854 key.type = BTRFS_DEV_EXTENT_KEY;
7857 path = btrfs_alloc_path();
7861 path->reada = READA_FORWARD;
7862 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7866 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7867 ret = btrfs_next_leaf(root, path);
7870 /* No dev extents at all? Not good */
7877 struct extent_buffer *leaf = path->nodes[0];
7878 struct btrfs_dev_extent *dext;
7879 int slot = path->slots[0];
7881 u64 physical_offset;
7885 btrfs_item_key_to_cpu(leaf, &key, slot);
7886 if (key.type != BTRFS_DEV_EXTENT_KEY)
7888 devid = key.objectid;
7889 physical_offset = key.offset;
7891 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7892 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7893 physical_len = btrfs_dev_extent_length(leaf, dext);
7895 /* Check if this dev extent overlaps with the previous one */
7896 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7898 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7899 devid, physical_offset, prev_dev_ext_end);
7904 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7905 physical_offset, physical_len);
7909 prev_dev_ext_end = physical_offset + physical_len;
7911 ret = btrfs_next_item(root, path);
7920 /* Ensure all chunks have corresponding dev extents */
7921 ret = verify_chunk_dev_extent_mapping(fs_info);
7923 btrfs_free_path(path);
7928 * Check whether the given block group or device is pinned by any inode being
7929 * used as a swapfile.
7931 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7933 struct btrfs_swapfile_pin *sp;
7934 struct rb_node *node;
7936 spin_lock(&fs_info->swapfile_pins_lock);
7937 node = fs_info->swapfile_pins.rb_node;
7939 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7941 node = node->rb_left;
7942 else if (ptr > sp->ptr)
7943 node = node->rb_right;
7947 spin_unlock(&fs_info->swapfile_pins_lock);
7948 return node != NULL;
7951 static int relocating_repair_kthread(void *data)
7953 struct btrfs_block_group *cache = data;
7954 struct btrfs_fs_info *fs_info = cache->fs_info;
7958 target = cache->start;
7959 btrfs_put_block_group(cache);
7961 sb_start_write(fs_info->sb);
7962 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
7964 "zoned: skip relocating block group %llu to repair: EBUSY",
7966 sb_end_write(fs_info->sb);
7970 mutex_lock(&fs_info->reclaim_bgs_lock);
7972 /* Ensure block group still exists */
7973 cache = btrfs_lookup_block_group(fs_info, target);
7977 if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags))
7980 ret = btrfs_may_alloc_data_chunk(fs_info, target);
7985 "zoned: relocating block group %llu to repair IO failure",
7987 ret = btrfs_relocate_chunk(fs_info, target);
7991 btrfs_put_block_group(cache);
7992 mutex_unlock(&fs_info->reclaim_bgs_lock);
7993 btrfs_exclop_finish(fs_info);
7994 sb_end_write(fs_info->sb);
7999 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8001 struct btrfs_block_group *cache;
8003 if (!btrfs_is_zoned(fs_info))
8006 /* Do not attempt to repair in degraded state */
8007 if (btrfs_test_opt(fs_info, DEGRADED))
8010 cache = btrfs_lookup_block_group(fs_info, logical);
8014 if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) {
8015 btrfs_put_block_group(cache);
8019 kthread_run(relocating_repair_kthread, cache,
8020 "btrfs-relocating-repair");
8025 static void map_raid56_repair_block(struct btrfs_io_context *bioc,
8026 struct btrfs_io_stripe *smap,
8029 int data_stripes = nr_bioc_data_stripes(bioc);
8032 for (i = 0; i < data_stripes; i++) {
8033 u64 stripe_start = bioc->full_stripe_logical +
8034 btrfs_stripe_nr_to_offset(i);
8036 if (logical >= stripe_start &&
8037 logical < stripe_start + BTRFS_STRIPE_LEN)
8040 ASSERT(i < data_stripes);
8041 smap->dev = bioc->stripes[i].dev;
8042 smap->physical = bioc->stripes[i].physical +
8043 ((logical - bioc->full_stripe_logical) &
8044 BTRFS_STRIPE_LEN_MASK);
8048 * Map a repair write into a single device.
8050 * A repair write is triggered by read time repair or scrub, which would only
8051 * update the contents of a single device.
8052 * Not update any other mirrors nor go through RMW path.
8054 * Callers should ensure:
8056 * - Call btrfs_bio_counter_inc_blocked() first
8057 * - The range does not cross stripe boundary
8058 * - Has a valid @mirror_num passed in.
8060 int btrfs_map_repair_block(struct btrfs_fs_info *fs_info,
8061 struct btrfs_io_stripe *smap, u64 logical,
8062 u32 length, int mirror_num)
8064 struct btrfs_io_context *bioc = NULL;
8065 u64 map_length = length;
8066 int mirror_ret = mirror_num;
8069 ASSERT(mirror_num > 0);
8071 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical, &map_length,
8072 &bioc, smap, &mirror_ret);
8076 /* The map range should not cross stripe boundary. */
8077 ASSERT(map_length >= length);
8079 /* Already mapped to single stripe. */
8083 /* Map the RAID56 multi-stripe writes to a single one. */
8084 if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
8085 map_raid56_repair_block(bioc, smap, logical);
8089 ASSERT(mirror_num <= bioc->num_stripes);
8090 smap->dev = bioc->stripes[mirror_num - 1].dev;
8091 smap->physical = bioc->stripes[mirror_num - 1].physical;
8093 btrfs_put_bioc(bioc);