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 block_device **bdev,
461 struct btrfs_super_block **disk_super)
465 *bdev = blkdev_get_by_path(device_path, flags, holder, NULL);
468 ret = PTR_ERR(*bdev);
473 sync_blockdev(*bdev);
474 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
476 blkdev_put(*bdev, holder);
479 invalidate_bdev(*bdev);
480 *disk_super = btrfs_read_dev_super(*bdev);
481 if (IS_ERR(*disk_super)) {
482 ret = PTR_ERR(*disk_super);
483 blkdev_put(*bdev, holder);
495 * Search and remove all stale devices (which are not mounted). When both
496 * inputs are NULL, it will search and release all stale devices.
498 * @devt: Optional. When provided will it release all unmounted devices
499 * matching this devt only.
500 * @skip_device: Optional. Will skip this device when searching for the stale
503 * Return: 0 for success or if @devt is 0.
504 * -EBUSY if @devt is a mounted device.
505 * -ENOENT if @devt does not match any device in the list.
507 static int btrfs_free_stale_devices(dev_t devt, struct btrfs_device *skip_device)
509 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
510 struct btrfs_device *device, *tmp_device;
514 lockdep_assert_held(&uuid_mutex);
516 /* Return good status if there is no instance of devt. */
518 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
520 mutex_lock(&fs_devices->device_list_mutex);
521 list_for_each_entry_safe(device, tmp_device,
522 &fs_devices->devices, dev_list) {
523 if (skip_device && skip_device == device)
525 if (devt && devt != device->devt)
527 if (fs_devices->opened) {
533 /* delete the stale device */
534 fs_devices->num_devices--;
535 list_del(&device->dev_list);
536 btrfs_free_device(device);
540 mutex_unlock(&fs_devices->device_list_mutex);
542 if (fs_devices->num_devices == 0) {
543 btrfs_sysfs_remove_fsid(fs_devices);
544 list_del(&fs_devices->fs_list);
545 free_fs_devices(fs_devices);
549 /* If there is at least one freed device return 0. */
556 static struct btrfs_fs_devices *find_fsid_by_device(
557 struct btrfs_super_block *disk_super,
558 dev_t devt, bool *same_fsid_diff_dev)
560 struct btrfs_fs_devices *fsid_fs_devices;
561 struct btrfs_fs_devices *devt_fs_devices;
562 const bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
563 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
564 bool found_by_devt = false;
566 /* Find the fs_device by the usual method, if found use it. */
567 fsid_fs_devices = find_fsid(disk_super->fsid,
568 has_metadata_uuid ? disk_super->metadata_uuid : NULL);
570 /* The temp_fsid feature is supported only with single device filesystem. */
571 if (btrfs_super_num_devices(disk_super) != 1)
572 return fsid_fs_devices;
575 * A seed device is an integral component of the sprout device, which
576 * functions as a multi-device filesystem. So, temp-fsid feature is
579 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING)
580 return fsid_fs_devices;
582 /* Try to find a fs_devices by matching devt. */
583 list_for_each_entry(devt_fs_devices, &fs_uuids, fs_list) {
584 struct btrfs_device *device;
586 list_for_each_entry(device, &devt_fs_devices->devices, dev_list) {
587 if (device->devt == devt) {
588 found_by_devt = true;
597 /* Existing device. */
598 if (fsid_fs_devices == NULL) {
599 if (devt_fs_devices->opened == 0) {
603 /* temp_fsid is mounting a subvol. */
604 return devt_fs_devices;
607 /* Regular or temp_fsid device mounting a subvol. */
608 return devt_fs_devices;
612 if (fsid_fs_devices == NULL) {
615 /* sb::fsid is already used create a new temp_fsid. */
616 *same_fsid_diff_dev = true;
625 * This is only used on mount, and we are protected from competing things
626 * messing with our fs_devices by the uuid_mutex, thus we do not need the
627 * fs_devices->device_list_mutex here.
629 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
630 struct btrfs_device *device, blk_mode_t flags,
633 struct block_device *bdev;
634 struct btrfs_super_block *disk_super;
643 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
648 devid = btrfs_stack_device_id(&disk_super->dev_item);
649 if (devid != device->devid)
650 goto error_free_page;
652 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
653 goto error_free_page;
655 device->generation = btrfs_super_generation(disk_super);
657 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
658 if (btrfs_super_incompat_flags(disk_super) &
659 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
661 "BTRFS: Invalid seeding and uuid-changed device detected\n");
662 goto error_free_page;
665 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
666 fs_devices->seeding = true;
668 if (bdev_read_only(bdev))
669 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
671 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
674 if (!bdev_nonrot(bdev))
675 fs_devices->rotating = true;
677 if (bdev_max_discard_sectors(bdev))
678 fs_devices->discardable = true;
681 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
682 device->holder = holder;
684 fs_devices->open_devices++;
685 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
686 device->devid != BTRFS_DEV_REPLACE_DEVID) {
687 fs_devices->rw_devices++;
688 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
690 btrfs_release_disk_super(disk_super);
695 btrfs_release_disk_super(disk_super);
696 blkdev_put(bdev, holder);
701 u8 *btrfs_sb_fsid_ptr(struct btrfs_super_block *sb)
703 bool has_metadata_uuid = (btrfs_super_incompat_flags(sb) &
704 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
706 return has_metadata_uuid ? sb->metadata_uuid : sb->fsid;
710 * Add new device to list of registered devices
713 * device pointer which was just added or updated when successful
714 * error pointer when failed
716 static noinline struct btrfs_device *device_list_add(const char *path,
717 struct btrfs_super_block *disk_super,
718 bool *new_device_added)
720 struct btrfs_device *device;
721 struct btrfs_fs_devices *fs_devices = NULL;
722 struct rcu_string *name;
723 u64 found_transid = btrfs_super_generation(disk_super);
724 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
727 bool same_fsid_diff_dev = false;
728 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
729 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
731 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
733 "device %s has incomplete metadata_uuid change, please use btrfstune to complete",
735 return ERR_PTR(-EAGAIN);
738 error = lookup_bdev(path, &path_devt);
740 btrfs_err(NULL, "failed to lookup block device for path %s: %d",
742 return ERR_PTR(error);
745 fs_devices = find_fsid_by_device(disk_super, path_devt, &same_fsid_diff_dev);
748 fs_devices = alloc_fs_devices(disk_super->fsid);
749 if (has_metadata_uuid)
750 memcpy(fs_devices->metadata_uuid,
751 disk_super->metadata_uuid, BTRFS_FSID_SIZE);
753 if (IS_ERR(fs_devices))
754 return ERR_CAST(fs_devices);
756 if (same_fsid_diff_dev) {
757 generate_random_uuid(fs_devices->fsid);
758 fs_devices->temp_fsid = true;
759 pr_info("BTRFS: device %s using temp-fsid %pU\n",
760 path, fs_devices->fsid);
763 mutex_lock(&fs_devices->device_list_mutex);
764 list_add(&fs_devices->fs_list, &fs_uuids);
768 struct btrfs_dev_lookup_args args = {
770 .uuid = disk_super->dev_item.uuid,
773 mutex_lock(&fs_devices->device_list_mutex);
774 device = btrfs_find_device(fs_devices, &args);
776 if (found_transid > fs_devices->latest_generation) {
777 memcpy(fs_devices->fsid, disk_super->fsid,
779 memcpy(fs_devices->metadata_uuid,
780 btrfs_sb_fsid_ptr(disk_super), BTRFS_FSID_SIZE);
785 unsigned int nofs_flag;
787 if (fs_devices->opened) {
789 "device %s belongs to fsid %pU, and the fs is already mounted, scanned by %s (%d)",
790 path, fs_devices->fsid, current->comm,
791 task_pid_nr(current));
792 mutex_unlock(&fs_devices->device_list_mutex);
793 return ERR_PTR(-EBUSY);
796 nofs_flag = memalloc_nofs_save();
797 device = btrfs_alloc_device(NULL, &devid,
798 disk_super->dev_item.uuid, path);
799 memalloc_nofs_restore(nofs_flag);
800 if (IS_ERR(device)) {
801 mutex_unlock(&fs_devices->device_list_mutex);
802 /* we can safely leave the fs_devices entry around */
806 device->devt = path_devt;
808 list_add_rcu(&device->dev_list, &fs_devices->devices);
809 fs_devices->num_devices++;
811 device->fs_devices = fs_devices;
812 *new_device_added = true;
814 if (disk_super->label[0])
816 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
817 disk_super->label, devid, found_transid, path,
818 current->comm, task_pid_nr(current));
821 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
822 disk_super->fsid, devid, found_transid, path,
823 current->comm, task_pid_nr(current));
825 } else if (!device->name || strcmp(device->name->str, path)) {
827 * When FS is already mounted.
828 * 1. If you are here and if the device->name is NULL that
829 * means this device was missing at time of FS mount.
830 * 2. If you are here and if the device->name is different
831 * from 'path' that means either
832 * a. The same device disappeared and reappeared with
834 * b. The missing-disk-which-was-replaced, has
837 * We must allow 1 and 2a above. But 2b would be a spurious
840 * Further in case of 1 and 2a above, the disk at 'path'
841 * would have missed some transaction when it was away and
842 * in case of 2a the stale bdev has to be updated as well.
843 * 2b must not be allowed at all time.
847 * For now, we do allow update to btrfs_fs_device through the
848 * btrfs dev scan cli after FS has been mounted. We're still
849 * tracking a problem where systems fail mount by subvolume id
850 * when we reject replacement on a mounted FS.
852 if (!fs_devices->opened && found_transid < device->generation) {
854 * That is if the FS is _not_ mounted and if you
855 * are here, that means there is more than one
856 * disk with same uuid and devid.We keep the one
857 * with larger generation number or the last-in if
858 * generation are equal.
860 mutex_unlock(&fs_devices->device_list_mutex);
862 "device %s already registered with a higher generation, found %llu expect %llu",
863 path, found_transid, device->generation);
864 return ERR_PTR(-EEXIST);
868 * We are going to replace the device path for a given devid,
869 * make sure it's the same device if the device is mounted
871 * NOTE: the device->fs_info may not be reliable here so pass
872 * in a NULL to message helpers instead. This avoids a possible
873 * use-after-free when the fs_info and fs_info->sb are already
877 if (device->devt != path_devt) {
878 mutex_unlock(&fs_devices->device_list_mutex);
879 btrfs_warn_in_rcu(NULL,
880 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
881 path, devid, found_transid,
883 task_pid_nr(current));
884 return ERR_PTR(-EEXIST);
886 btrfs_info_in_rcu(NULL,
887 "devid %llu device path %s changed to %s scanned by %s (%d)",
888 devid, btrfs_dev_name(device),
890 task_pid_nr(current));
893 name = rcu_string_strdup(path, GFP_NOFS);
895 mutex_unlock(&fs_devices->device_list_mutex);
896 return ERR_PTR(-ENOMEM);
898 rcu_string_free(device->name);
899 rcu_assign_pointer(device->name, name);
900 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
901 fs_devices->missing_devices--;
902 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
904 device->devt = path_devt;
908 * Unmount does not free the btrfs_device struct but would zero
909 * generation along with most of the other members. So just update
910 * it back. We need it to pick the disk with largest generation
913 if (!fs_devices->opened) {
914 device->generation = found_transid;
915 fs_devices->latest_generation = max_t(u64, found_transid,
916 fs_devices->latest_generation);
919 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
921 mutex_unlock(&fs_devices->device_list_mutex);
925 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
927 struct btrfs_fs_devices *fs_devices;
928 struct btrfs_device *device;
929 struct btrfs_device *orig_dev;
932 lockdep_assert_held(&uuid_mutex);
934 fs_devices = alloc_fs_devices(orig->fsid);
935 if (IS_ERR(fs_devices))
938 fs_devices->total_devices = orig->total_devices;
940 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
941 const char *dev_path = NULL;
944 * This is ok to do without RCU read locked because we hold the
945 * uuid mutex so nothing we touch in here is going to disappear.
948 dev_path = orig_dev->name->str;
950 device = btrfs_alloc_device(NULL, &orig_dev->devid,
951 orig_dev->uuid, dev_path);
952 if (IS_ERR(device)) {
953 ret = PTR_ERR(device);
957 if (orig_dev->zone_info) {
958 struct btrfs_zoned_device_info *zone_info;
960 zone_info = btrfs_clone_dev_zone_info(orig_dev);
962 btrfs_free_device(device);
966 device->zone_info = zone_info;
969 list_add(&device->dev_list, &fs_devices->devices);
970 device->fs_devices = fs_devices;
971 fs_devices->num_devices++;
975 free_fs_devices(fs_devices);
979 static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
980 struct btrfs_device **latest_dev)
982 struct btrfs_device *device, *next;
984 /* This is the initialized path, it is safe to release the devices. */
985 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
986 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
987 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
988 &device->dev_state) &&
989 !test_bit(BTRFS_DEV_STATE_MISSING,
990 &device->dev_state) &&
992 device->generation > (*latest_dev)->generation)) {
993 *latest_dev = device;
999 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1000 * in btrfs_init_dev_replace() so just continue.
1002 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1006 blkdev_put(device->bdev, device->holder);
1007 device->bdev = NULL;
1008 fs_devices->open_devices--;
1010 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1011 list_del_init(&device->dev_alloc_list);
1012 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1013 fs_devices->rw_devices--;
1015 list_del_init(&device->dev_list);
1016 fs_devices->num_devices--;
1017 btrfs_free_device(device);
1023 * After we have read the system tree and know devids belonging to this
1024 * filesystem, remove the device which does not belong there.
1026 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices)
1028 struct btrfs_device *latest_dev = NULL;
1029 struct btrfs_fs_devices *seed_dev;
1031 mutex_lock(&uuid_mutex);
1032 __btrfs_free_extra_devids(fs_devices, &latest_dev);
1034 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1035 __btrfs_free_extra_devids(seed_dev, &latest_dev);
1037 fs_devices->latest_dev = latest_dev;
1039 mutex_unlock(&uuid_mutex);
1042 static void btrfs_close_bdev(struct btrfs_device *device)
1047 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1048 sync_blockdev(device->bdev);
1049 invalidate_bdev(device->bdev);
1052 blkdev_put(device->bdev, device->holder);
1055 static void btrfs_close_one_device(struct btrfs_device *device)
1057 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1059 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1060 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1061 list_del_init(&device->dev_alloc_list);
1062 fs_devices->rw_devices--;
1065 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1066 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
1068 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1069 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1070 fs_devices->missing_devices--;
1073 btrfs_close_bdev(device);
1075 fs_devices->open_devices--;
1076 device->bdev = NULL;
1078 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1079 btrfs_destroy_dev_zone_info(device);
1081 device->fs_info = NULL;
1082 atomic_set(&device->dev_stats_ccnt, 0);
1083 extent_io_tree_release(&device->alloc_state);
1086 * Reset the flush error record. We might have a transient flush error
1087 * in this mount, and if so we aborted the current transaction and set
1088 * the fs to an error state, guaranteeing no super blocks can be further
1089 * committed. However that error might be transient and if we unmount the
1090 * filesystem and mount it again, we should allow the mount to succeed
1091 * (btrfs_check_rw_degradable() should not fail) - if after mounting the
1092 * filesystem again we still get flush errors, then we will again abort
1093 * any transaction and set the error state, guaranteeing no commits of
1094 * unsafe super blocks.
1096 device->last_flush_error = 0;
1098 /* Verify the device is back in a pristine state */
1099 WARN_ON(test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1100 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1101 WARN_ON(!list_empty(&device->dev_alloc_list));
1102 WARN_ON(!list_empty(&device->post_commit_list));
1105 static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
1107 struct btrfs_device *device, *tmp;
1109 lockdep_assert_held(&uuid_mutex);
1111 if (--fs_devices->opened > 0)
1114 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
1115 btrfs_close_one_device(device);
1117 WARN_ON(fs_devices->open_devices);
1118 WARN_ON(fs_devices->rw_devices);
1119 fs_devices->opened = 0;
1120 fs_devices->seeding = false;
1121 fs_devices->fs_info = NULL;
1124 void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1127 struct btrfs_fs_devices *tmp;
1129 mutex_lock(&uuid_mutex);
1130 close_fs_devices(fs_devices);
1131 if (!fs_devices->opened) {
1132 list_splice_init(&fs_devices->seed_list, &list);
1135 * If the struct btrfs_fs_devices is not assembled with any
1136 * other device, it can be re-initialized during the next mount
1137 * without the needing device-scan step. Therefore, it can be
1140 if (fs_devices->num_devices == 1) {
1141 list_del(&fs_devices->fs_list);
1142 free_fs_devices(fs_devices);
1147 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
1148 close_fs_devices(fs_devices);
1149 list_del(&fs_devices->seed_list);
1150 free_fs_devices(fs_devices);
1152 mutex_unlock(&uuid_mutex);
1155 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1156 blk_mode_t flags, void *holder)
1158 struct btrfs_device *device;
1159 struct btrfs_device *latest_dev = NULL;
1160 struct btrfs_device *tmp_device;
1162 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1166 ret = btrfs_open_one_device(fs_devices, device, flags, holder);
1168 (!latest_dev || device->generation > latest_dev->generation)) {
1169 latest_dev = device;
1170 } else if (ret == -ENODATA) {
1171 fs_devices->num_devices--;
1172 list_del(&device->dev_list);
1173 btrfs_free_device(device);
1176 if (fs_devices->open_devices == 0)
1179 fs_devices->opened = 1;
1180 fs_devices->latest_dev = latest_dev;
1181 fs_devices->total_rw_bytes = 0;
1182 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1183 fs_devices->read_policy = BTRFS_READ_POLICY_PID;
1188 static int devid_cmp(void *priv, const struct list_head *a,
1189 const struct list_head *b)
1191 const struct btrfs_device *dev1, *dev2;
1193 dev1 = list_entry(a, struct btrfs_device, dev_list);
1194 dev2 = list_entry(b, struct btrfs_device, dev_list);
1196 if (dev1->devid < dev2->devid)
1198 else if (dev1->devid > dev2->devid)
1203 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1204 blk_mode_t flags, void *holder)
1208 lockdep_assert_held(&uuid_mutex);
1210 * The device_list_mutex cannot be taken here in case opening the
1211 * underlying device takes further locks like open_mutex.
1213 * We also don't need the lock here as this is called during mount and
1214 * exclusion is provided by uuid_mutex
1217 if (fs_devices->opened) {
1218 fs_devices->opened++;
1221 list_sort(NULL, &fs_devices->devices, devid_cmp);
1222 ret = open_fs_devices(fs_devices, flags, holder);
1228 void btrfs_release_disk_super(struct btrfs_super_block *super)
1230 struct page *page = virt_to_page(super);
1235 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1236 u64 bytenr, u64 bytenr_orig)
1238 struct btrfs_super_block *disk_super;
1243 /* make sure our super fits in the device */
1244 if (bytenr + PAGE_SIZE >= bdev_nr_bytes(bdev))
1245 return ERR_PTR(-EINVAL);
1247 /* make sure our super fits in the page */
1248 if (sizeof(*disk_super) > PAGE_SIZE)
1249 return ERR_PTR(-EINVAL);
1251 /* make sure our super doesn't straddle pages on disk */
1252 index = bytenr >> PAGE_SHIFT;
1253 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1254 return ERR_PTR(-EINVAL);
1256 /* pull in the page with our super */
1257 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1260 return ERR_CAST(page);
1262 p = page_address(page);
1264 /* align our pointer to the offset of the super block */
1265 disk_super = p + offset_in_page(bytenr);
1267 if (btrfs_super_bytenr(disk_super) != bytenr_orig ||
1268 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1269 btrfs_release_disk_super(p);
1270 return ERR_PTR(-EINVAL);
1273 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1274 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1279 int btrfs_forget_devices(dev_t devt)
1283 mutex_lock(&uuid_mutex);
1284 ret = btrfs_free_stale_devices(devt, NULL);
1285 mutex_unlock(&uuid_mutex);
1291 * Look for a btrfs signature on a device. This may be called out of the mount path
1292 * and we are not allowed to call set_blocksize during the scan. The superblock
1293 * is read via pagecache.
1295 * With @mount_arg_dev it's a scan during mount time that will always register
1296 * the device or return an error. Multi-device and seeding devices are registered
1299 struct btrfs_device *btrfs_scan_one_device(const char *path, blk_mode_t flags,
1302 struct btrfs_super_block *disk_super;
1303 bool new_device_added = false;
1304 struct btrfs_device *device = NULL;
1305 struct block_device *bdev;
1306 u64 bytenr, bytenr_orig;
1309 lockdep_assert_held(&uuid_mutex);
1312 * we would like to check all the supers, but that would make
1313 * a btrfs mount succeed after a mkfs from a different FS.
1314 * So, we need to add a special mount option to scan for
1315 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1319 * Avoid an exclusive open here, as the systemd-udev may initiate the
1320 * device scan which may race with the user's mount or mkfs command,
1321 * resulting in failure.
1322 * Since the device scan is solely for reading purposes, there is no
1323 * need for an exclusive open. Additionally, the devices are read again
1324 * during the mount process. It is ok to get some inconsistent
1325 * values temporarily, as the device paths of the fsid are the only
1326 * required information for assembling the volume.
1328 bdev = blkdev_get_by_path(path, flags, NULL, NULL);
1330 return ERR_CAST(bdev);
1332 bytenr_orig = btrfs_sb_offset(0);
1333 ret = btrfs_sb_log_location_bdev(bdev, 0, READ, &bytenr);
1335 device = ERR_PTR(ret);
1336 goto error_bdev_put;
1339 disk_super = btrfs_read_disk_super(bdev, bytenr, bytenr_orig);
1340 if (IS_ERR(disk_super)) {
1341 device = ERR_CAST(disk_super);
1342 goto error_bdev_put;
1345 if (!mount_arg_dev && btrfs_super_num_devices(disk_super) == 1 &&
1346 !(btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING)) {
1349 ret = lookup_bdev(path, &devt);
1351 btrfs_warn(NULL, "lookup bdev failed for path %s: %d",
1354 btrfs_free_stale_devices(devt, NULL);
1356 pr_debug("BTRFS: skip registering single non-seed device %s\n", path);
1358 goto free_disk_super;
1361 device = device_list_add(path, disk_super, &new_device_added);
1362 if (!IS_ERR(device) && new_device_added)
1363 btrfs_free_stale_devices(device->devt, device);
1366 btrfs_release_disk_super(disk_super);
1369 blkdev_put(bdev, NULL);
1375 * Try to find a chunk that intersects [start, start + len] range and when one
1376 * such is found, record the end of it in *start
1378 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1381 u64 physical_start, physical_end;
1383 lockdep_assert_held(&device->fs_info->chunk_mutex);
1385 if (find_first_extent_bit(&device->alloc_state, *start,
1386 &physical_start, &physical_end,
1387 CHUNK_ALLOCATED, NULL)) {
1389 if (in_range(physical_start, *start, len) ||
1390 in_range(*start, physical_start,
1391 physical_end - physical_start)) {
1392 *start = physical_end + 1;
1399 static u64 dev_extent_search_start(struct btrfs_device *device)
1401 switch (device->fs_devices->chunk_alloc_policy) {
1402 case BTRFS_CHUNK_ALLOC_REGULAR:
1403 return BTRFS_DEVICE_RANGE_RESERVED;
1404 case BTRFS_CHUNK_ALLOC_ZONED:
1406 * We don't care about the starting region like regular
1407 * allocator, because we anyway use/reserve the first two zones
1408 * for superblock logging.
1416 static bool dev_extent_hole_check_zoned(struct btrfs_device *device,
1417 u64 *hole_start, u64 *hole_size,
1420 u64 zone_size = device->zone_info->zone_size;
1423 bool changed = false;
1425 ASSERT(IS_ALIGNED(*hole_start, zone_size));
1427 while (*hole_size > 0) {
1428 pos = btrfs_find_allocatable_zones(device, *hole_start,
1429 *hole_start + *hole_size,
1431 if (pos != *hole_start) {
1432 *hole_size = *hole_start + *hole_size - pos;
1435 if (*hole_size < num_bytes)
1439 ret = btrfs_ensure_empty_zones(device, pos, num_bytes);
1441 /* Range is ensured to be empty */
1445 /* Given hole range was invalid (outside of device) */
1446 if (ret == -ERANGE) {
1447 *hole_start += *hole_size;
1452 *hole_start += zone_size;
1453 *hole_size -= zone_size;
1461 * Check if specified hole is suitable for allocation.
1463 * @device: the device which we have the hole
1464 * @hole_start: starting position of the hole
1465 * @hole_size: the size of the hole
1466 * @num_bytes: the size of the free space that we need
1468 * This function may modify @hole_start and @hole_size to reflect the suitable
1469 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1471 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1472 u64 *hole_size, u64 num_bytes)
1474 bool changed = false;
1475 u64 hole_end = *hole_start + *hole_size;
1479 * Check before we set max_hole_start, otherwise we could end up
1480 * sending back this offset anyway.
1482 if (contains_pending_extent(device, hole_start, *hole_size)) {
1483 if (hole_end >= *hole_start)
1484 *hole_size = hole_end - *hole_start;
1490 switch (device->fs_devices->chunk_alloc_policy) {
1491 case BTRFS_CHUNK_ALLOC_REGULAR:
1492 /* No extra check */
1494 case BTRFS_CHUNK_ALLOC_ZONED:
1495 if (dev_extent_hole_check_zoned(device, hole_start,
1496 hole_size, num_bytes)) {
1499 * The changed hole can contain pending extent.
1500 * Loop again to check that.
1516 * Find free space in the specified device.
1518 * @device: the device which we search the free space in
1519 * @num_bytes: the size of the free space that we need
1520 * @search_start: the position from which to begin the search
1521 * @start: store the start of the free space.
1522 * @len: the size of the free space. that we find, or the size
1523 * of the max free space if we don't find suitable free space
1525 * This does a pretty simple search, the expectation is that it is called very
1526 * infrequently and that a given device has a small number of extents.
1528 * @start is used to store the start of the free space if we find. But if we
1529 * don't find suitable free space, it will be used to store the start position
1530 * of the max free space.
1532 * @len is used to store the size of the free space that we find.
1533 * But if we don't find suitable free space, it is used to store the size of
1534 * the max free space.
1536 * NOTE: This function will search *commit* root of device tree, and does extra
1537 * check to ensure dev extents are not double allocated.
1538 * This makes the function safe to allocate dev extents but may not report
1539 * correct usable device space, as device extent freed in current transaction
1540 * is not reported as available.
1542 static int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1543 u64 *start, u64 *len)
1545 struct btrfs_fs_info *fs_info = device->fs_info;
1546 struct btrfs_root *root = fs_info->dev_root;
1547 struct btrfs_key key;
1548 struct btrfs_dev_extent *dev_extent;
1549 struct btrfs_path *path;
1553 u64 max_hole_size = 0;
1555 u64 search_end = device->total_bytes;
1558 struct extent_buffer *l;
1560 search_start = dev_extent_search_start(device);
1561 max_hole_start = search_start;
1563 WARN_ON(device->zone_info &&
1564 !IS_ALIGNED(num_bytes, device->zone_info->zone_size));
1566 path = btrfs_alloc_path();
1572 if (search_start >= search_end ||
1573 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1578 path->reada = READA_FORWARD;
1579 path->search_commit_root = 1;
1580 path->skip_locking = 1;
1582 key.objectid = device->devid;
1583 key.offset = search_start;
1584 key.type = BTRFS_DEV_EXTENT_KEY;
1586 ret = btrfs_search_backwards(root, &key, path);
1590 while (search_start < search_end) {
1592 slot = path->slots[0];
1593 if (slot >= btrfs_header_nritems(l)) {
1594 ret = btrfs_next_leaf(root, path);
1602 btrfs_item_key_to_cpu(l, &key, slot);
1604 if (key.objectid < device->devid)
1607 if (key.objectid > device->devid)
1610 if (key.type != BTRFS_DEV_EXTENT_KEY)
1613 if (key.offset > search_end)
1616 if (key.offset > search_start) {
1617 hole_size = key.offset - search_start;
1618 dev_extent_hole_check(device, &search_start, &hole_size,
1621 if (hole_size > max_hole_size) {
1622 max_hole_start = search_start;
1623 max_hole_size = hole_size;
1627 * If this free space is greater than which we need,
1628 * it must be the max free space that we have found
1629 * until now, so max_hole_start must point to the start
1630 * of this free space and the length of this free space
1631 * is stored in max_hole_size. Thus, we return
1632 * max_hole_start and max_hole_size and go back to the
1635 if (hole_size >= num_bytes) {
1641 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1642 extent_end = key.offset + btrfs_dev_extent_length(l,
1644 if (extent_end > search_start)
1645 search_start = extent_end;
1652 * At this point, search_start should be the end of
1653 * allocated dev extents, and when shrinking the device,
1654 * search_end may be smaller than search_start.
1656 if (search_end > search_start) {
1657 hole_size = search_end - search_start;
1658 if (dev_extent_hole_check(device, &search_start, &hole_size,
1660 btrfs_release_path(path);
1664 if (hole_size > max_hole_size) {
1665 max_hole_start = search_start;
1666 max_hole_size = hole_size;
1671 if (max_hole_size < num_bytes)
1676 ASSERT(max_hole_start + max_hole_size <= search_end);
1678 btrfs_free_path(path);
1679 *start = max_hole_start;
1681 *len = max_hole_size;
1685 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1686 struct btrfs_device *device,
1687 u64 start, u64 *dev_extent_len)
1689 struct btrfs_fs_info *fs_info = device->fs_info;
1690 struct btrfs_root *root = fs_info->dev_root;
1692 struct btrfs_path *path;
1693 struct btrfs_key key;
1694 struct btrfs_key found_key;
1695 struct extent_buffer *leaf = NULL;
1696 struct btrfs_dev_extent *extent = NULL;
1698 path = btrfs_alloc_path();
1702 key.objectid = device->devid;
1704 key.type = BTRFS_DEV_EXTENT_KEY;
1706 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1708 ret = btrfs_previous_item(root, path, key.objectid,
1709 BTRFS_DEV_EXTENT_KEY);
1712 leaf = path->nodes[0];
1713 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1714 extent = btrfs_item_ptr(leaf, path->slots[0],
1715 struct btrfs_dev_extent);
1716 BUG_ON(found_key.offset > start || found_key.offset +
1717 btrfs_dev_extent_length(leaf, extent) < start);
1719 btrfs_release_path(path);
1721 } else if (ret == 0) {
1722 leaf = path->nodes[0];
1723 extent = btrfs_item_ptr(leaf, path->slots[0],
1724 struct btrfs_dev_extent);
1729 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1731 ret = btrfs_del_item(trans, root, path);
1733 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1735 btrfs_free_path(path);
1739 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1741 struct extent_map_tree *em_tree;
1742 struct extent_map *em;
1746 em_tree = &fs_info->mapping_tree;
1747 read_lock(&em_tree->lock);
1748 n = rb_last(&em_tree->map.rb_root);
1750 em = rb_entry(n, struct extent_map, rb_node);
1751 ret = em->start + em->len;
1753 read_unlock(&em_tree->lock);
1758 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1762 struct btrfs_key key;
1763 struct btrfs_key found_key;
1764 struct btrfs_path *path;
1766 path = btrfs_alloc_path();
1770 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1771 key.type = BTRFS_DEV_ITEM_KEY;
1772 key.offset = (u64)-1;
1774 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1780 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1785 ret = btrfs_previous_item(fs_info->chunk_root, path,
1786 BTRFS_DEV_ITEMS_OBJECTID,
1787 BTRFS_DEV_ITEM_KEY);
1791 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1793 *devid_ret = found_key.offset + 1;
1797 btrfs_free_path(path);
1802 * the device information is stored in the chunk root
1803 * the btrfs_device struct should be fully filled in
1805 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1806 struct btrfs_device *device)
1809 struct btrfs_path *path;
1810 struct btrfs_dev_item *dev_item;
1811 struct extent_buffer *leaf;
1812 struct btrfs_key key;
1815 path = btrfs_alloc_path();
1819 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1820 key.type = BTRFS_DEV_ITEM_KEY;
1821 key.offset = device->devid;
1823 btrfs_reserve_chunk_metadata(trans, true);
1824 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1825 &key, sizeof(*dev_item));
1826 btrfs_trans_release_chunk_metadata(trans);
1830 leaf = path->nodes[0];
1831 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1833 btrfs_set_device_id(leaf, dev_item, device->devid);
1834 btrfs_set_device_generation(leaf, dev_item, 0);
1835 btrfs_set_device_type(leaf, dev_item, device->type);
1836 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1837 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1838 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1839 btrfs_set_device_total_bytes(leaf, dev_item,
1840 btrfs_device_get_disk_total_bytes(device));
1841 btrfs_set_device_bytes_used(leaf, dev_item,
1842 btrfs_device_get_bytes_used(device));
1843 btrfs_set_device_group(leaf, dev_item, 0);
1844 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1845 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1846 btrfs_set_device_start_offset(leaf, dev_item, 0);
1848 ptr = btrfs_device_uuid(dev_item);
1849 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1850 ptr = btrfs_device_fsid(dev_item);
1851 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1852 ptr, BTRFS_FSID_SIZE);
1853 btrfs_mark_buffer_dirty(trans, leaf);
1857 btrfs_free_path(path);
1862 * Function to update ctime/mtime for a given device path.
1863 * Mainly used for ctime/mtime based probe like libblkid.
1865 * We don't care about errors here, this is just to be kind to userspace.
1867 static void update_dev_time(const char *device_path)
1872 ret = kern_path(device_path, LOOKUP_FOLLOW, &path);
1876 inode_update_time(d_inode(path.dentry), S_MTIME | S_CTIME | S_VERSION);
1880 static int btrfs_rm_dev_item(struct btrfs_trans_handle *trans,
1881 struct btrfs_device *device)
1883 struct btrfs_root *root = device->fs_info->chunk_root;
1885 struct btrfs_path *path;
1886 struct btrfs_key key;
1888 path = btrfs_alloc_path();
1892 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1893 key.type = BTRFS_DEV_ITEM_KEY;
1894 key.offset = device->devid;
1896 btrfs_reserve_chunk_metadata(trans, false);
1897 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1898 btrfs_trans_release_chunk_metadata(trans);
1905 ret = btrfs_del_item(trans, root, path);
1907 btrfs_free_path(path);
1912 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1913 * filesystem. It's up to the caller to adjust that number regarding eg. device
1916 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1924 seq = read_seqbegin(&fs_info->profiles_lock);
1926 all_avail = fs_info->avail_data_alloc_bits |
1927 fs_info->avail_system_alloc_bits |
1928 fs_info->avail_metadata_alloc_bits;
1929 } while (read_seqretry(&fs_info->profiles_lock, seq));
1931 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1932 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1935 if (num_devices < btrfs_raid_array[i].devs_min)
1936 return btrfs_raid_array[i].mindev_error;
1942 static struct btrfs_device * btrfs_find_next_active_device(
1943 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1945 struct btrfs_device *next_device;
1947 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1948 if (next_device != device &&
1949 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1950 && next_device->bdev)
1958 * Helper function to check if the given device is part of s_bdev / latest_dev
1959 * and replace it with the provided or the next active device, in the context
1960 * where this function called, there should be always be another device (or
1961 * this_dev) which is active.
1963 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
1964 struct btrfs_device *next_device)
1966 struct btrfs_fs_info *fs_info = device->fs_info;
1969 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1971 ASSERT(next_device);
1973 if (fs_info->sb->s_bdev &&
1974 (fs_info->sb->s_bdev == device->bdev))
1975 fs_info->sb->s_bdev = next_device->bdev;
1977 if (fs_info->fs_devices->latest_dev->bdev == device->bdev)
1978 fs_info->fs_devices->latest_dev = next_device;
1982 * Return btrfs_fs_devices::num_devices excluding the device that's being
1983 * currently replaced.
1985 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1987 u64 num_devices = fs_info->fs_devices->num_devices;
1989 down_read(&fs_info->dev_replace.rwsem);
1990 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1991 ASSERT(num_devices > 1);
1994 up_read(&fs_info->dev_replace.rwsem);
1999 static void btrfs_scratch_superblock(struct btrfs_fs_info *fs_info,
2000 struct block_device *bdev, int copy_num)
2002 struct btrfs_super_block *disk_super;
2003 const size_t len = sizeof(disk_super->magic);
2004 const u64 bytenr = btrfs_sb_offset(copy_num);
2007 disk_super = btrfs_read_disk_super(bdev, bytenr, bytenr);
2008 if (IS_ERR(disk_super))
2011 memset(&disk_super->magic, 0, len);
2012 folio_mark_dirty(virt_to_folio(disk_super));
2013 btrfs_release_disk_super(disk_super);
2015 ret = sync_blockdev_range(bdev, bytenr, bytenr + len - 1);
2017 btrfs_warn(fs_info, "error clearing superblock number %d (%d)",
2021 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2022 struct block_device *bdev,
2023 const char *device_path)
2030 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2031 if (bdev_is_zoned(bdev))
2032 btrfs_reset_sb_log_zones(bdev, copy_num);
2034 btrfs_scratch_superblock(fs_info, bdev, copy_num);
2037 /* Notify udev that device has changed */
2038 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2040 /* Update ctime/mtime for device path for libblkid */
2041 update_dev_time(device_path);
2044 int btrfs_rm_device(struct btrfs_fs_info *fs_info,
2045 struct btrfs_dev_lookup_args *args,
2046 struct block_device **bdev, void **holder)
2048 struct btrfs_trans_handle *trans;
2049 struct btrfs_device *device;
2050 struct btrfs_fs_devices *cur_devices;
2051 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2055 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2056 btrfs_err(fs_info, "device remove not supported on extent tree v2 yet");
2061 * The device list in fs_devices is accessed without locks (neither
2062 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2063 * filesystem and another device rm cannot run.
2065 num_devices = btrfs_num_devices(fs_info);
2067 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2071 device = btrfs_find_device(fs_info->fs_devices, args);
2074 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2080 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2081 btrfs_warn_in_rcu(fs_info,
2082 "cannot remove device %s (devid %llu) due to active swapfile",
2083 btrfs_dev_name(device), device->devid);
2087 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
2088 return BTRFS_ERROR_DEV_TGT_REPLACE;
2090 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2091 fs_info->fs_devices->rw_devices == 1)
2092 return BTRFS_ERROR_DEV_ONLY_WRITABLE;
2094 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2095 mutex_lock(&fs_info->chunk_mutex);
2096 list_del_init(&device->dev_alloc_list);
2097 device->fs_devices->rw_devices--;
2098 mutex_unlock(&fs_info->chunk_mutex);
2101 ret = btrfs_shrink_device(device, 0);
2105 trans = btrfs_start_transaction(fs_info->chunk_root, 0);
2106 if (IS_ERR(trans)) {
2107 ret = PTR_ERR(trans);
2111 ret = btrfs_rm_dev_item(trans, device);
2113 /* Any error in dev item removal is critical */
2115 "failed to remove device item for devid %llu: %d",
2116 device->devid, ret);
2117 btrfs_abort_transaction(trans, ret);
2118 btrfs_end_transaction(trans);
2122 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2123 btrfs_scrub_cancel_dev(device);
2126 * the device list mutex makes sure that we don't change
2127 * the device list while someone else is writing out all
2128 * the device supers. Whoever is writing all supers, should
2129 * lock the device list mutex before getting the number of
2130 * devices in the super block (super_copy). Conversely,
2131 * whoever updates the number of devices in the super block
2132 * (super_copy) should hold the device list mutex.
2136 * In normal cases the cur_devices == fs_devices. But in case
2137 * of deleting a seed device, the cur_devices should point to
2138 * its own fs_devices listed under the fs_devices->seed_list.
2140 cur_devices = device->fs_devices;
2141 mutex_lock(&fs_devices->device_list_mutex);
2142 list_del_rcu(&device->dev_list);
2144 cur_devices->num_devices--;
2145 cur_devices->total_devices--;
2146 /* Update total_devices of the parent fs_devices if it's seed */
2147 if (cur_devices != fs_devices)
2148 fs_devices->total_devices--;
2150 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2151 cur_devices->missing_devices--;
2153 btrfs_assign_next_active_device(device, NULL);
2156 cur_devices->open_devices--;
2157 /* remove sysfs entry */
2158 btrfs_sysfs_remove_device(device);
2161 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2162 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2163 mutex_unlock(&fs_devices->device_list_mutex);
2166 * At this point, the device is zero sized and detached from the
2167 * devices list. All that's left is to zero out the old supers and
2170 * We cannot call btrfs_close_bdev() here because we're holding the sb
2171 * write lock, and blkdev_put() will pull in the ->open_mutex on the
2172 * block device and it's dependencies. Instead just flush the device
2173 * and let the caller do the final blkdev_put.
2175 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2176 btrfs_scratch_superblocks(fs_info, device->bdev,
2179 sync_blockdev(device->bdev);
2180 invalidate_bdev(device->bdev);
2184 *bdev = device->bdev;
2185 *holder = device->holder;
2187 btrfs_free_device(device);
2190 * This can happen if cur_devices is the private seed devices list. We
2191 * cannot call close_fs_devices() here because it expects the uuid_mutex
2192 * to be held, but in fact we don't need that for the private
2193 * seed_devices, we can simply decrement cur_devices->opened and then
2194 * remove it from our list and free the fs_devices.
2196 if (cur_devices->num_devices == 0) {
2197 list_del_init(&cur_devices->seed_list);
2198 ASSERT(cur_devices->opened == 1);
2199 cur_devices->opened--;
2200 free_fs_devices(cur_devices);
2203 ret = btrfs_commit_transaction(trans);
2208 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2209 mutex_lock(&fs_info->chunk_mutex);
2210 list_add(&device->dev_alloc_list,
2211 &fs_devices->alloc_list);
2212 device->fs_devices->rw_devices++;
2213 mutex_unlock(&fs_info->chunk_mutex);
2218 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2220 struct btrfs_fs_devices *fs_devices;
2222 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2225 * in case of fs with no seed, srcdev->fs_devices will point
2226 * to fs_devices of fs_info. However when the dev being replaced is
2227 * a seed dev it will point to the seed's local fs_devices. In short
2228 * srcdev will have its correct fs_devices in both the cases.
2230 fs_devices = srcdev->fs_devices;
2232 list_del_rcu(&srcdev->dev_list);
2233 list_del(&srcdev->dev_alloc_list);
2234 fs_devices->num_devices--;
2235 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2236 fs_devices->missing_devices--;
2238 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2239 fs_devices->rw_devices--;
2242 fs_devices->open_devices--;
2245 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2247 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2249 mutex_lock(&uuid_mutex);
2251 btrfs_close_bdev(srcdev);
2253 btrfs_free_device(srcdev);
2255 /* if this is no devs we rather delete the fs_devices */
2256 if (!fs_devices->num_devices) {
2258 * On a mounted FS, num_devices can't be zero unless it's a
2259 * seed. In case of a seed device being replaced, the replace
2260 * target added to the sprout FS, so there will be no more
2261 * device left under the seed FS.
2263 ASSERT(fs_devices->seeding);
2265 list_del_init(&fs_devices->seed_list);
2266 close_fs_devices(fs_devices);
2267 free_fs_devices(fs_devices);
2269 mutex_unlock(&uuid_mutex);
2272 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2274 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2276 mutex_lock(&fs_devices->device_list_mutex);
2278 btrfs_sysfs_remove_device(tgtdev);
2281 fs_devices->open_devices--;
2283 fs_devices->num_devices--;
2285 btrfs_assign_next_active_device(tgtdev, NULL);
2287 list_del_rcu(&tgtdev->dev_list);
2289 mutex_unlock(&fs_devices->device_list_mutex);
2291 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2294 btrfs_close_bdev(tgtdev);
2296 btrfs_free_device(tgtdev);
2300 * Populate args from device at path.
2302 * @fs_info: the filesystem
2303 * @args: the args to populate
2304 * @path: the path to the device
2306 * This will read the super block of the device at @path and populate @args with
2307 * the devid, fsid, and uuid. This is meant to be used for ioctls that need to
2308 * lookup a device to operate on, but need to do it before we take any locks.
2309 * This properly handles the special case of "missing" that a user may pass in,
2310 * and does some basic sanity checks. The caller must make sure that @path is
2311 * properly NUL terminated before calling in, and must call
2312 * btrfs_put_dev_args_from_path() in order to free up the temporary fsid and
2315 * Return: 0 for success, -errno for failure
2317 int btrfs_get_dev_args_from_path(struct btrfs_fs_info *fs_info,
2318 struct btrfs_dev_lookup_args *args,
2321 struct btrfs_super_block *disk_super;
2322 struct block_device *bdev;
2325 if (!path || !path[0])
2327 if (!strcmp(path, "missing")) {
2328 args->missing = true;
2332 args->uuid = kzalloc(BTRFS_UUID_SIZE, GFP_KERNEL);
2333 args->fsid = kzalloc(BTRFS_FSID_SIZE, GFP_KERNEL);
2334 if (!args->uuid || !args->fsid) {
2335 btrfs_put_dev_args_from_path(args);
2339 ret = btrfs_get_bdev_and_sb(path, BLK_OPEN_READ, NULL, 0,
2340 &bdev, &disk_super);
2342 btrfs_put_dev_args_from_path(args);
2346 args->devid = btrfs_stack_device_id(&disk_super->dev_item);
2347 memcpy(args->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE);
2348 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2349 memcpy(args->fsid, disk_super->metadata_uuid, BTRFS_FSID_SIZE);
2351 memcpy(args->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
2352 btrfs_release_disk_super(disk_super);
2353 blkdev_put(bdev, NULL);
2358 * Only use this jointly with btrfs_get_dev_args_from_path() because we will
2359 * allocate our ->uuid and ->fsid pointers, everybody else uses local variables
2360 * that don't need to be freed.
2362 void btrfs_put_dev_args_from_path(struct btrfs_dev_lookup_args *args)
2370 struct btrfs_device *btrfs_find_device_by_devspec(
2371 struct btrfs_fs_info *fs_info, u64 devid,
2372 const char *device_path)
2374 BTRFS_DEV_LOOKUP_ARGS(args);
2375 struct btrfs_device *device;
2380 device = btrfs_find_device(fs_info->fs_devices, &args);
2382 return ERR_PTR(-ENOENT);
2386 ret = btrfs_get_dev_args_from_path(fs_info, &args, device_path);
2388 return ERR_PTR(ret);
2389 device = btrfs_find_device(fs_info->fs_devices, &args);
2390 btrfs_put_dev_args_from_path(&args);
2392 return ERR_PTR(-ENOENT);
2396 static struct btrfs_fs_devices *btrfs_init_sprout(struct btrfs_fs_info *fs_info)
2398 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2399 struct btrfs_fs_devices *old_devices;
2400 struct btrfs_fs_devices *seed_devices;
2402 lockdep_assert_held(&uuid_mutex);
2403 if (!fs_devices->seeding)
2404 return ERR_PTR(-EINVAL);
2407 * Private copy of the seed devices, anchored at
2408 * fs_info->fs_devices->seed_list
2410 seed_devices = alloc_fs_devices(NULL);
2411 if (IS_ERR(seed_devices))
2412 return seed_devices;
2415 * It's necessary to retain a copy of the original seed fs_devices in
2416 * fs_uuids so that filesystems which have been seeded can successfully
2417 * reference the seed device from open_seed_devices. This also supports
2420 old_devices = clone_fs_devices(fs_devices);
2421 if (IS_ERR(old_devices)) {
2422 kfree(seed_devices);
2426 list_add(&old_devices->fs_list, &fs_uuids);
2428 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2429 seed_devices->opened = 1;
2430 INIT_LIST_HEAD(&seed_devices->devices);
2431 INIT_LIST_HEAD(&seed_devices->alloc_list);
2432 mutex_init(&seed_devices->device_list_mutex);
2434 return seed_devices;
2438 * Splice seed devices into the sprout fs_devices.
2439 * Generate a new fsid for the sprouted read-write filesystem.
2441 static void btrfs_setup_sprout(struct btrfs_fs_info *fs_info,
2442 struct btrfs_fs_devices *seed_devices)
2444 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2445 struct btrfs_super_block *disk_super = fs_info->super_copy;
2446 struct btrfs_device *device;
2450 * We are updating the fsid, the thread leading to device_list_add()
2451 * could race, so uuid_mutex is needed.
2453 lockdep_assert_held(&uuid_mutex);
2456 * The threads listed below may traverse dev_list but can do that without
2457 * device_list_mutex:
2458 * - All device ops and balance - as we are in btrfs_exclop_start.
2459 * - Various dev_list readers - are using RCU.
2460 * - btrfs_ioctl_fitrim() - is using RCU.
2462 * For-read threads as below are using device_list_mutex:
2463 * - Readonly scrub btrfs_scrub_dev()
2464 * - Readonly scrub btrfs_scrub_progress()
2465 * - btrfs_get_dev_stats()
2467 lockdep_assert_held(&fs_devices->device_list_mutex);
2469 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2471 list_for_each_entry(device, &seed_devices->devices, dev_list)
2472 device->fs_devices = seed_devices;
2474 fs_devices->seeding = false;
2475 fs_devices->num_devices = 0;
2476 fs_devices->open_devices = 0;
2477 fs_devices->missing_devices = 0;
2478 fs_devices->rotating = false;
2479 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2481 generate_random_uuid(fs_devices->fsid);
2482 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2483 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2485 super_flags = btrfs_super_flags(disk_super) &
2486 ~BTRFS_SUPER_FLAG_SEEDING;
2487 btrfs_set_super_flags(disk_super, super_flags);
2491 * Store the expected generation for seed devices in device items.
2493 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2495 BTRFS_DEV_LOOKUP_ARGS(args);
2496 struct btrfs_fs_info *fs_info = trans->fs_info;
2497 struct btrfs_root *root = fs_info->chunk_root;
2498 struct btrfs_path *path;
2499 struct extent_buffer *leaf;
2500 struct btrfs_dev_item *dev_item;
2501 struct btrfs_device *device;
2502 struct btrfs_key key;
2503 u8 fs_uuid[BTRFS_FSID_SIZE];
2504 u8 dev_uuid[BTRFS_UUID_SIZE];
2507 path = btrfs_alloc_path();
2511 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2513 key.type = BTRFS_DEV_ITEM_KEY;
2516 btrfs_reserve_chunk_metadata(trans, false);
2517 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2518 btrfs_trans_release_chunk_metadata(trans);
2522 leaf = path->nodes[0];
2524 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2525 ret = btrfs_next_leaf(root, path);
2530 leaf = path->nodes[0];
2531 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2532 btrfs_release_path(path);
2536 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2537 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2538 key.type != BTRFS_DEV_ITEM_KEY)
2541 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2542 struct btrfs_dev_item);
2543 args.devid = btrfs_device_id(leaf, dev_item);
2544 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2546 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2548 args.uuid = dev_uuid;
2549 args.fsid = fs_uuid;
2550 device = btrfs_find_device(fs_info->fs_devices, &args);
2551 BUG_ON(!device); /* Logic error */
2553 if (device->fs_devices->seeding) {
2554 btrfs_set_device_generation(leaf, dev_item,
2555 device->generation);
2556 btrfs_mark_buffer_dirty(trans, leaf);
2564 btrfs_free_path(path);
2568 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2570 struct btrfs_root *root = fs_info->dev_root;
2571 struct btrfs_trans_handle *trans;
2572 struct btrfs_device *device;
2573 struct block_device *bdev;
2574 struct super_block *sb = fs_info->sb;
2575 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2576 struct btrfs_fs_devices *seed_devices = NULL;
2577 u64 orig_super_total_bytes;
2578 u64 orig_super_num_devices;
2580 bool seeding_dev = false;
2581 bool locked = false;
2583 if (sb_rdonly(sb) && !fs_devices->seeding)
2586 bdev = blkdev_get_by_path(device_path, BLK_OPEN_WRITE,
2587 fs_info->bdev_holder, NULL);
2589 return PTR_ERR(bdev);
2591 if (!btrfs_check_device_zone_type(fs_info, bdev)) {
2596 if (fs_devices->seeding) {
2598 down_write(&sb->s_umount);
2599 mutex_lock(&uuid_mutex);
2603 sync_blockdev(bdev);
2606 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2607 if (device->bdev == bdev) {
2615 device = btrfs_alloc_device(fs_info, NULL, NULL, device_path);
2616 if (IS_ERR(device)) {
2617 /* we can safely leave the fs_devices entry around */
2618 ret = PTR_ERR(device);
2622 device->fs_info = fs_info;
2623 device->bdev = bdev;
2624 ret = lookup_bdev(device_path, &device->devt);
2626 goto error_free_device;
2628 ret = btrfs_get_dev_zone_info(device, false);
2630 goto error_free_device;
2632 trans = btrfs_start_transaction(root, 0);
2633 if (IS_ERR(trans)) {
2634 ret = PTR_ERR(trans);
2635 goto error_free_zone;
2638 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2639 device->generation = trans->transid;
2640 device->io_width = fs_info->sectorsize;
2641 device->io_align = fs_info->sectorsize;
2642 device->sector_size = fs_info->sectorsize;
2643 device->total_bytes =
2644 round_down(bdev_nr_bytes(bdev), fs_info->sectorsize);
2645 device->disk_total_bytes = device->total_bytes;
2646 device->commit_total_bytes = device->total_bytes;
2647 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2648 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2649 device->holder = fs_info->bdev_holder;
2650 device->dev_stats_valid = 1;
2651 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2654 btrfs_clear_sb_rdonly(sb);
2656 /* GFP_KERNEL allocation must not be under device_list_mutex */
2657 seed_devices = btrfs_init_sprout(fs_info);
2658 if (IS_ERR(seed_devices)) {
2659 ret = PTR_ERR(seed_devices);
2660 btrfs_abort_transaction(trans, ret);
2665 mutex_lock(&fs_devices->device_list_mutex);
2667 btrfs_setup_sprout(fs_info, seed_devices);
2668 btrfs_assign_next_active_device(fs_info->fs_devices->latest_dev,
2672 device->fs_devices = fs_devices;
2674 mutex_lock(&fs_info->chunk_mutex);
2675 list_add_rcu(&device->dev_list, &fs_devices->devices);
2676 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2677 fs_devices->num_devices++;
2678 fs_devices->open_devices++;
2679 fs_devices->rw_devices++;
2680 fs_devices->total_devices++;
2681 fs_devices->total_rw_bytes += device->total_bytes;
2683 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2685 if (!bdev_nonrot(bdev))
2686 fs_devices->rotating = true;
2688 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2689 btrfs_set_super_total_bytes(fs_info->super_copy,
2690 round_down(orig_super_total_bytes + device->total_bytes,
2691 fs_info->sectorsize));
2693 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2694 btrfs_set_super_num_devices(fs_info->super_copy,
2695 orig_super_num_devices + 1);
2698 * we've got more storage, clear any full flags on the space
2701 btrfs_clear_space_info_full(fs_info);
2703 mutex_unlock(&fs_info->chunk_mutex);
2705 /* Add sysfs device entry */
2706 btrfs_sysfs_add_device(device);
2708 mutex_unlock(&fs_devices->device_list_mutex);
2711 mutex_lock(&fs_info->chunk_mutex);
2712 ret = init_first_rw_device(trans);
2713 mutex_unlock(&fs_info->chunk_mutex);
2715 btrfs_abort_transaction(trans, ret);
2720 ret = btrfs_add_dev_item(trans, device);
2722 btrfs_abort_transaction(trans, ret);
2727 ret = btrfs_finish_sprout(trans);
2729 btrfs_abort_transaction(trans, ret);
2734 * fs_devices now represents the newly sprouted filesystem and
2735 * its fsid has been changed by btrfs_sprout_splice().
2737 btrfs_sysfs_update_sprout_fsid(fs_devices);
2740 ret = btrfs_commit_transaction(trans);
2743 mutex_unlock(&uuid_mutex);
2744 up_write(&sb->s_umount);
2747 if (ret) /* transaction commit */
2750 ret = btrfs_relocate_sys_chunks(fs_info);
2752 btrfs_handle_fs_error(fs_info, ret,
2753 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2754 trans = btrfs_attach_transaction(root);
2755 if (IS_ERR(trans)) {
2756 if (PTR_ERR(trans) == -ENOENT)
2758 ret = PTR_ERR(trans);
2762 ret = btrfs_commit_transaction(trans);
2766 * Now that we have written a new super block to this device, check all
2767 * other fs_devices list if device_path alienates any other scanned
2769 * We can ignore the return value as it typically returns -EINVAL and
2770 * only succeeds if the device was an alien.
2772 btrfs_forget_devices(device->devt);
2774 /* Update ctime/mtime for blkid or udev */
2775 update_dev_time(device_path);
2780 btrfs_sysfs_remove_device(device);
2781 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2782 mutex_lock(&fs_info->chunk_mutex);
2783 list_del_rcu(&device->dev_list);
2784 list_del(&device->dev_alloc_list);
2785 fs_info->fs_devices->num_devices--;
2786 fs_info->fs_devices->open_devices--;
2787 fs_info->fs_devices->rw_devices--;
2788 fs_info->fs_devices->total_devices--;
2789 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2790 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2791 btrfs_set_super_total_bytes(fs_info->super_copy,
2792 orig_super_total_bytes);
2793 btrfs_set_super_num_devices(fs_info->super_copy,
2794 orig_super_num_devices);
2795 mutex_unlock(&fs_info->chunk_mutex);
2796 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2799 btrfs_set_sb_rdonly(sb);
2801 btrfs_end_transaction(trans);
2803 btrfs_destroy_dev_zone_info(device);
2805 btrfs_free_device(device);
2807 blkdev_put(bdev, fs_info->bdev_holder);
2809 mutex_unlock(&uuid_mutex);
2810 up_write(&sb->s_umount);
2815 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2816 struct btrfs_device *device)
2819 struct btrfs_path *path;
2820 struct btrfs_root *root = device->fs_info->chunk_root;
2821 struct btrfs_dev_item *dev_item;
2822 struct extent_buffer *leaf;
2823 struct btrfs_key key;
2825 path = btrfs_alloc_path();
2829 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2830 key.type = BTRFS_DEV_ITEM_KEY;
2831 key.offset = device->devid;
2833 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2842 leaf = path->nodes[0];
2843 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2845 btrfs_set_device_id(leaf, dev_item, device->devid);
2846 btrfs_set_device_type(leaf, dev_item, device->type);
2847 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2848 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2849 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2850 btrfs_set_device_total_bytes(leaf, dev_item,
2851 btrfs_device_get_disk_total_bytes(device));
2852 btrfs_set_device_bytes_used(leaf, dev_item,
2853 btrfs_device_get_bytes_used(device));
2854 btrfs_mark_buffer_dirty(trans, leaf);
2857 btrfs_free_path(path);
2861 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2862 struct btrfs_device *device, u64 new_size)
2864 struct btrfs_fs_info *fs_info = device->fs_info;
2865 struct btrfs_super_block *super_copy = fs_info->super_copy;
2870 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2873 new_size = round_down(new_size, fs_info->sectorsize);
2875 mutex_lock(&fs_info->chunk_mutex);
2876 old_total = btrfs_super_total_bytes(super_copy);
2877 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2879 if (new_size <= device->total_bytes ||
2880 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2881 mutex_unlock(&fs_info->chunk_mutex);
2885 btrfs_set_super_total_bytes(super_copy,
2886 round_down(old_total + diff, fs_info->sectorsize));
2887 device->fs_devices->total_rw_bytes += diff;
2888 atomic64_add(diff, &fs_info->free_chunk_space);
2890 btrfs_device_set_total_bytes(device, new_size);
2891 btrfs_device_set_disk_total_bytes(device, new_size);
2892 btrfs_clear_space_info_full(device->fs_info);
2893 if (list_empty(&device->post_commit_list))
2894 list_add_tail(&device->post_commit_list,
2895 &trans->transaction->dev_update_list);
2896 mutex_unlock(&fs_info->chunk_mutex);
2898 btrfs_reserve_chunk_metadata(trans, false);
2899 ret = btrfs_update_device(trans, device);
2900 btrfs_trans_release_chunk_metadata(trans);
2905 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2907 struct btrfs_fs_info *fs_info = trans->fs_info;
2908 struct btrfs_root *root = fs_info->chunk_root;
2910 struct btrfs_path *path;
2911 struct btrfs_key key;
2913 path = btrfs_alloc_path();
2917 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2918 key.offset = chunk_offset;
2919 key.type = BTRFS_CHUNK_ITEM_KEY;
2921 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2924 else if (ret > 0) { /* Logic error or corruption */
2925 btrfs_handle_fs_error(fs_info, -ENOENT,
2926 "Failed lookup while freeing chunk.");
2931 ret = btrfs_del_item(trans, root, path);
2933 btrfs_handle_fs_error(fs_info, ret,
2934 "Failed to delete chunk item.");
2936 btrfs_free_path(path);
2940 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2942 struct btrfs_super_block *super_copy = fs_info->super_copy;
2943 struct btrfs_disk_key *disk_key;
2944 struct btrfs_chunk *chunk;
2951 struct btrfs_key key;
2953 lockdep_assert_held(&fs_info->chunk_mutex);
2954 array_size = btrfs_super_sys_array_size(super_copy);
2956 ptr = super_copy->sys_chunk_array;
2959 while (cur < array_size) {
2960 disk_key = (struct btrfs_disk_key *)ptr;
2961 btrfs_disk_key_to_cpu(&key, disk_key);
2963 len = sizeof(*disk_key);
2965 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2966 chunk = (struct btrfs_chunk *)(ptr + len);
2967 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2968 len += btrfs_chunk_item_size(num_stripes);
2973 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2974 key.offset == chunk_offset) {
2975 memmove(ptr, ptr + len, array_size - (cur + len));
2977 btrfs_set_super_sys_array_size(super_copy, array_size);
2987 * Find the mapping containing the given logical extent.
2989 * @logical: Logical block offset in bytes.
2990 * @length: Length of extent in bytes.
2992 * Return: Chunk mapping or ERR_PTR.
2994 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2995 u64 logical, u64 length)
2997 struct extent_map_tree *em_tree;
2998 struct extent_map *em;
3000 em_tree = &fs_info->mapping_tree;
3001 read_lock(&em_tree->lock);
3002 em = lookup_extent_mapping(em_tree, logical, length);
3003 read_unlock(&em_tree->lock);
3006 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
3008 return ERR_PTR(-EINVAL);
3011 if (em->start > logical || em->start + em->len < logical) {
3013 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
3014 logical, length, em->start, em->start + em->len);
3015 free_extent_map(em);
3016 return ERR_PTR(-EINVAL);
3019 /* callers are responsible for dropping em's ref. */
3023 static int remove_chunk_item(struct btrfs_trans_handle *trans,
3024 struct map_lookup *map, u64 chunk_offset)
3029 * Removing chunk items and updating the device items in the chunks btree
3030 * requires holding the chunk_mutex.
3031 * See the comment at btrfs_chunk_alloc() for the details.
3033 lockdep_assert_held(&trans->fs_info->chunk_mutex);
3035 for (i = 0; i < map->num_stripes; i++) {
3038 ret = btrfs_update_device(trans, map->stripes[i].dev);
3043 return btrfs_free_chunk(trans, chunk_offset);
3046 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3048 struct btrfs_fs_info *fs_info = trans->fs_info;
3049 struct extent_map *em;
3050 struct map_lookup *map;
3051 u64 dev_extent_len = 0;
3053 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3055 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3058 * This is a logic error, but we don't want to just rely on the
3059 * user having built with ASSERT enabled, so if ASSERT doesn't
3060 * do anything we still error out.
3065 map = em->map_lookup;
3068 * First delete the device extent items from the devices btree.
3069 * We take the device_list_mutex to avoid racing with the finishing phase
3070 * of a device replace operation. See the comment below before acquiring
3071 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3072 * because that can result in a deadlock when deleting the device extent
3073 * items from the devices btree - COWing an extent buffer from the btree
3074 * may result in allocating a new metadata chunk, which would attempt to
3075 * lock again fs_info->chunk_mutex.
3077 mutex_lock(&fs_devices->device_list_mutex);
3078 for (i = 0; i < map->num_stripes; i++) {
3079 struct btrfs_device *device = map->stripes[i].dev;
3080 ret = btrfs_free_dev_extent(trans, device,
3081 map->stripes[i].physical,
3084 mutex_unlock(&fs_devices->device_list_mutex);
3085 btrfs_abort_transaction(trans, ret);
3089 if (device->bytes_used > 0) {
3090 mutex_lock(&fs_info->chunk_mutex);
3091 btrfs_device_set_bytes_used(device,
3092 device->bytes_used - dev_extent_len);
3093 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3094 btrfs_clear_space_info_full(fs_info);
3095 mutex_unlock(&fs_info->chunk_mutex);
3098 mutex_unlock(&fs_devices->device_list_mutex);
3101 * We acquire fs_info->chunk_mutex for 2 reasons:
3103 * 1) Just like with the first phase of the chunk allocation, we must
3104 * reserve system space, do all chunk btree updates and deletions, and
3105 * update the system chunk array in the superblock while holding this
3106 * mutex. This is for similar reasons as explained on the comment at
3107 * the top of btrfs_chunk_alloc();
3109 * 2) Prevent races with the final phase of a device replace operation
3110 * that replaces the device object associated with the map's stripes,
3111 * because the device object's id can change at any time during that
3112 * final phase of the device replace operation
3113 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3114 * replaced device and then see it with an ID of
3115 * BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3116 * the device item, which does not exists on the chunk btree.
3117 * The finishing phase of device replace acquires both the
3118 * device_list_mutex and the chunk_mutex, in that order, so we are
3119 * safe by just acquiring the chunk_mutex.
3121 trans->removing_chunk = true;
3122 mutex_lock(&fs_info->chunk_mutex);
3124 check_system_chunk(trans, map->type);
3126 ret = remove_chunk_item(trans, map, chunk_offset);
3128 * Normally we should not get -ENOSPC since we reserved space before
3129 * through the call to check_system_chunk().
3131 * Despite our system space_info having enough free space, we may not
3132 * be able to allocate extents from its block groups, because all have
3133 * an incompatible profile, which will force us to allocate a new system
3134 * block group with the right profile, or right after we called
3135 * check_system_space() above, a scrub turned the only system block group
3136 * with enough free space into RO mode.
3137 * This is explained with more detail at do_chunk_alloc().
3139 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3141 if (ret == -ENOSPC) {
3142 const u64 sys_flags = btrfs_system_alloc_profile(fs_info);
3143 struct btrfs_block_group *sys_bg;
3145 sys_bg = btrfs_create_chunk(trans, sys_flags);
3146 if (IS_ERR(sys_bg)) {
3147 ret = PTR_ERR(sys_bg);
3148 btrfs_abort_transaction(trans, ret);
3152 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3154 btrfs_abort_transaction(trans, ret);
3158 ret = remove_chunk_item(trans, map, chunk_offset);
3160 btrfs_abort_transaction(trans, ret);
3164 btrfs_abort_transaction(trans, ret);
3168 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3170 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3171 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3173 btrfs_abort_transaction(trans, ret);
3178 mutex_unlock(&fs_info->chunk_mutex);
3179 trans->removing_chunk = false;
3182 * We are done with chunk btree updates and deletions, so release the
3183 * system space we previously reserved (with check_system_chunk()).
3185 btrfs_trans_release_chunk_metadata(trans);
3187 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3189 btrfs_abort_transaction(trans, ret);
3194 if (trans->removing_chunk) {
3195 mutex_unlock(&fs_info->chunk_mutex);
3196 trans->removing_chunk = false;
3199 free_extent_map(em);
3203 int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3205 struct btrfs_root *root = fs_info->chunk_root;
3206 struct btrfs_trans_handle *trans;
3207 struct btrfs_block_group *block_group;
3211 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3213 "relocate: not supported on extent tree v2 yet");
3218 * Prevent races with automatic removal of unused block groups.
3219 * After we relocate and before we remove the chunk with offset
3220 * chunk_offset, automatic removal of the block group can kick in,
3221 * resulting in a failure when calling btrfs_remove_chunk() below.
3223 * Make sure to acquire this mutex before doing a tree search (dev
3224 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3225 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3226 * we release the path used to search the chunk/dev tree and before
3227 * the current task acquires this mutex and calls us.
3229 lockdep_assert_held(&fs_info->reclaim_bgs_lock);
3231 /* step one, relocate all the extents inside this chunk */
3232 btrfs_scrub_pause(fs_info);
3233 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3234 btrfs_scrub_continue(fs_info);
3237 * If we had a transaction abort, stop all running scrubs.
3238 * See transaction.c:cleanup_transaction() why we do it here.
3240 if (BTRFS_FS_ERROR(fs_info))
3241 btrfs_scrub_cancel(fs_info);
3245 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3248 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3249 length = block_group->length;
3250 btrfs_put_block_group(block_group);
3253 * On a zoned file system, discard the whole block group, this will
3254 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3255 * resetting the zone fails, don't treat it as a fatal problem from the
3256 * filesystem's point of view.
3258 if (btrfs_is_zoned(fs_info)) {
3259 ret = btrfs_discard_extent(fs_info, chunk_offset, length, NULL);
3262 "failed to reset zone %llu after relocation",
3266 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3268 if (IS_ERR(trans)) {
3269 ret = PTR_ERR(trans);
3270 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3275 * step two, delete the device extents and the
3276 * chunk tree entries
3278 ret = btrfs_remove_chunk(trans, chunk_offset);
3279 btrfs_end_transaction(trans);
3283 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3285 struct btrfs_root *chunk_root = fs_info->chunk_root;
3286 struct btrfs_path *path;
3287 struct extent_buffer *leaf;
3288 struct btrfs_chunk *chunk;
3289 struct btrfs_key key;
3290 struct btrfs_key found_key;
3292 bool retried = false;
3296 path = btrfs_alloc_path();
3301 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3302 key.offset = (u64)-1;
3303 key.type = BTRFS_CHUNK_ITEM_KEY;
3306 mutex_lock(&fs_info->reclaim_bgs_lock);
3307 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3309 mutex_unlock(&fs_info->reclaim_bgs_lock);
3312 BUG_ON(ret == 0); /* Corruption */
3314 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3317 mutex_unlock(&fs_info->reclaim_bgs_lock);
3323 leaf = path->nodes[0];
3324 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3326 chunk = btrfs_item_ptr(leaf, path->slots[0],
3327 struct btrfs_chunk);
3328 chunk_type = btrfs_chunk_type(leaf, chunk);
3329 btrfs_release_path(path);
3331 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3332 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3338 mutex_unlock(&fs_info->reclaim_bgs_lock);
3340 if (found_key.offset == 0)
3342 key.offset = found_key.offset - 1;
3345 if (failed && !retried) {
3349 } else if (WARN_ON(failed && retried)) {
3353 btrfs_free_path(path);
3358 * return 1 : allocate a data chunk successfully,
3359 * return <0: errors during allocating a data chunk,
3360 * return 0 : no need to allocate a data chunk.
3362 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3365 struct btrfs_block_group *cache;
3369 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3371 chunk_type = cache->flags;
3372 btrfs_put_block_group(cache);
3374 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3377 spin_lock(&fs_info->data_sinfo->lock);
3378 bytes_used = fs_info->data_sinfo->bytes_used;
3379 spin_unlock(&fs_info->data_sinfo->lock);
3382 struct btrfs_trans_handle *trans;
3385 trans = btrfs_join_transaction(fs_info->tree_root);
3387 return PTR_ERR(trans);
3389 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3390 btrfs_end_transaction(trans);
3399 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3400 struct btrfs_balance_control *bctl)
3402 struct btrfs_root *root = fs_info->tree_root;
3403 struct btrfs_trans_handle *trans;
3404 struct btrfs_balance_item *item;
3405 struct btrfs_disk_balance_args disk_bargs;
3406 struct btrfs_path *path;
3407 struct extent_buffer *leaf;
3408 struct btrfs_key key;
3411 path = btrfs_alloc_path();
3415 trans = btrfs_start_transaction(root, 0);
3416 if (IS_ERR(trans)) {
3417 btrfs_free_path(path);
3418 return PTR_ERR(trans);
3421 key.objectid = BTRFS_BALANCE_OBJECTID;
3422 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3425 ret = btrfs_insert_empty_item(trans, root, path, &key,
3430 leaf = path->nodes[0];
3431 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3433 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3435 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3436 btrfs_set_balance_data(leaf, item, &disk_bargs);
3437 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3438 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3439 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3440 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3442 btrfs_set_balance_flags(leaf, item, bctl->flags);
3444 btrfs_mark_buffer_dirty(trans, leaf);
3446 btrfs_free_path(path);
3447 err = btrfs_commit_transaction(trans);
3453 static int del_balance_item(struct btrfs_fs_info *fs_info)
3455 struct btrfs_root *root = fs_info->tree_root;
3456 struct btrfs_trans_handle *trans;
3457 struct btrfs_path *path;
3458 struct btrfs_key key;
3461 path = btrfs_alloc_path();
3465 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3466 if (IS_ERR(trans)) {
3467 btrfs_free_path(path);
3468 return PTR_ERR(trans);
3471 key.objectid = BTRFS_BALANCE_OBJECTID;
3472 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3475 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3483 ret = btrfs_del_item(trans, root, path);
3485 btrfs_free_path(path);
3486 err = btrfs_commit_transaction(trans);
3493 * This is a heuristic used to reduce the number of chunks balanced on
3494 * resume after balance was interrupted.
3496 static void update_balance_args(struct btrfs_balance_control *bctl)
3499 * Turn on soft mode for chunk types that were being converted.
3501 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3502 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3503 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3504 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3505 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3506 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3509 * Turn on usage filter if is not already used. The idea is
3510 * that chunks that we have already balanced should be
3511 * reasonably full. Don't do it for chunks that are being
3512 * converted - that will keep us from relocating unconverted
3513 * (albeit full) chunks.
3515 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3516 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3517 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3518 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3519 bctl->data.usage = 90;
3521 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3522 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3523 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3524 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3525 bctl->sys.usage = 90;
3527 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3528 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3529 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3530 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3531 bctl->meta.usage = 90;
3536 * Clear the balance status in fs_info and delete the balance item from disk.
3538 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3540 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3543 BUG_ON(!fs_info->balance_ctl);
3545 spin_lock(&fs_info->balance_lock);
3546 fs_info->balance_ctl = NULL;
3547 spin_unlock(&fs_info->balance_lock);
3550 ret = del_balance_item(fs_info);
3552 btrfs_handle_fs_error(fs_info, ret, NULL);
3556 * Balance filters. Return 1 if chunk should be filtered out
3557 * (should not be balanced).
3559 static int chunk_profiles_filter(u64 chunk_type,
3560 struct btrfs_balance_args *bargs)
3562 chunk_type = chunk_to_extended(chunk_type) &
3563 BTRFS_EXTENDED_PROFILE_MASK;
3565 if (bargs->profiles & chunk_type)
3571 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3572 struct btrfs_balance_args *bargs)
3574 struct btrfs_block_group *cache;
3576 u64 user_thresh_min;
3577 u64 user_thresh_max;
3580 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3581 chunk_used = cache->used;
3583 if (bargs->usage_min == 0)
3584 user_thresh_min = 0;
3586 user_thresh_min = mult_perc(cache->length, bargs->usage_min);
3588 if (bargs->usage_max == 0)
3589 user_thresh_max = 1;
3590 else if (bargs->usage_max > 100)
3591 user_thresh_max = cache->length;
3593 user_thresh_max = mult_perc(cache->length, bargs->usage_max);
3595 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3598 btrfs_put_block_group(cache);
3602 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3603 u64 chunk_offset, struct btrfs_balance_args *bargs)
3605 struct btrfs_block_group *cache;
3606 u64 chunk_used, user_thresh;
3609 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3610 chunk_used = cache->used;
3612 if (bargs->usage_min == 0)
3614 else if (bargs->usage > 100)
3615 user_thresh = cache->length;
3617 user_thresh = mult_perc(cache->length, bargs->usage);
3619 if (chunk_used < user_thresh)
3622 btrfs_put_block_group(cache);
3626 static int chunk_devid_filter(struct extent_buffer *leaf,
3627 struct btrfs_chunk *chunk,
3628 struct btrfs_balance_args *bargs)
3630 struct btrfs_stripe *stripe;
3631 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3634 for (i = 0; i < num_stripes; i++) {
3635 stripe = btrfs_stripe_nr(chunk, i);
3636 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3643 static u64 calc_data_stripes(u64 type, int num_stripes)
3645 const int index = btrfs_bg_flags_to_raid_index(type);
3646 const int ncopies = btrfs_raid_array[index].ncopies;
3647 const int nparity = btrfs_raid_array[index].nparity;
3649 return (num_stripes - nparity) / ncopies;
3652 /* [pstart, pend) */
3653 static int chunk_drange_filter(struct extent_buffer *leaf,
3654 struct btrfs_chunk *chunk,
3655 struct btrfs_balance_args *bargs)
3657 struct btrfs_stripe *stripe;
3658 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3665 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3668 type = btrfs_chunk_type(leaf, chunk);
3669 factor = calc_data_stripes(type, num_stripes);
3671 for (i = 0; i < num_stripes; i++) {
3672 stripe = btrfs_stripe_nr(chunk, i);
3673 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3676 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3677 stripe_length = btrfs_chunk_length(leaf, chunk);
3678 stripe_length = div_u64(stripe_length, factor);
3680 if (stripe_offset < bargs->pend &&
3681 stripe_offset + stripe_length > bargs->pstart)
3688 /* [vstart, vend) */
3689 static int chunk_vrange_filter(struct extent_buffer *leaf,
3690 struct btrfs_chunk *chunk,
3692 struct btrfs_balance_args *bargs)
3694 if (chunk_offset < bargs->vend &&
3695 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3696 /* at least part of the chunk is inside this vrange */
3702 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3703 struct btrfs_chunk *chunk,
3704 struct btrfs_balance_args *bargs)
3706 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3708 if (bargs->stripes_min <= num_stripes
3709 && num_stripes <= bargs->stripes_max)
3715 static int chunk_soft_convert_filter(u64 chunk_type,
3716 struct btrfs_balance_args *bargs)
3718 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3721 chunk_type = chunk_to_extended(chunk_type) &
3722 BTRFS_EXTENDED_PROFILE_MASK;
3724 if (bargs->target == chunk_type)
3730 static int should_balance_chunk(struct extent_buffer *leaf,
3731 struct btrfs_chunk *chunk, u64 chunk_offset)
3733 struct btrfs_fs_info *fs_info = leaf->fs_info;
3734 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3735 struct btrfs_balance_args *bargs = NULL;
3736 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3739 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3740 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3744 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3745 bargs = &bctl->data;
3746 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3748 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3749 bargs = &bctl->meta;
3751 /* profiles filter */
3752 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3753 chunk_profiles_filter(chunk_type, bargs)) {
3758 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3759 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3761 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3762 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3767 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3768 chunk_devid_filter(leaf, chunk, bargs)) {
3772 /* drange filter, makes sense only with devid filter */
3773 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3774 chunk_drange_filter(leaf, chunk, bargs)) {
3779 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3780 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3784 /* stripes filter */
3785 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3786 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3790 /* soft profile changing mode */
3791 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3792 chunk_soft_convert_filter(chunk_type, bargs)) {
3797 * limited by count, must be the last filter
3799 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3800 if (bargs->limit == 0)
3804 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3806 * Same logic as the 'limit' filter; the minimum cannot be
3807 * determined here because we do not have the global information
3808 * about the count of all chunks that satisfy the filters.
3810 if (bargs->limit_max == 0)
3819 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3821 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3822 struct btrfs_root *chunk_root = fs_info->chunk_root;
3824 struct btrfs_chunk *chunk;
3825 struct btrfs_path *path = NULL;
3826 struct btrfs_key key;
3827 struct btrfs_key found_key;
3828 struct extent_buffer *leaf;
3831 int enospc_errors = 0;
3832 bool counting = true;
3833 /* The single value limit and min/max limits use the same bytes in the */
3834 u64 limit_data = bctl->data.limit;
3835 u64 limit_meta = bctl->meta.limit;
3836 u64 limit_sys = bctl->sys.limit;
3840 int chunk_reserved = 0;
3842 path = btrfs_alloc_path();
3848 /* zero out stat counters */
3849 spin_lock(&fs_info->balance_lock);
3850 memset(&bctl->stat, 0, sizeof(bctl->stat));
3851 spin_unlock(&fs_info->balance_lock);
3855 * The single value limit and min/max limits use the same bytes
3858 bctl->data.limit = limit_data;
3859 bctl->meta.limit = limit_meta;
3860 bctl->sys.limit = limit_sys;
3862 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3863 key.offset = (u64)-1;
3864 key.type = BTRFS_CHUNK_ITEM_KEY;
3867 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3868 atomic_read(&fs_info->balance_cancel_req)) {
3873 mutex_lock(&fs_info->reclaim_bgs_lock);
3874 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3876 mutex_unlock(&fs_info->reclaim_bgs_lock);
3881 * this shouldn't happen, it means the last relocate
3885 BUG(); /* FIXME break ? */
3887 ret = btrfs_previous_item(chunk_root, path, 0,
3888 BTRFS_CHUNK_ITEM_KEY);
3890 mutex_unlock(&fs_info->reclaim_bgs_lock);
3895 leaf = path->nodes[0];
3896 slot = path->slots[0];
3897 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3899 if (found_key.objectid != key.objectid) {
3900 mutex_unlock(&fs_info->reclaim_bgs_lock);
3904 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3905 chunk_type = btrfs_chunk_type(leaf, chunk);
3908 spin_lock(&fs_info->balance_lock);
3909 bctl->stat.considered++;
3910 spin_unlock(&fs_info->balance_lock);
3913 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3915 btrfs_release_path(path);
3917 mutex_unlock(&fs_info->reclaim_bgs_lock);
3922 mutex_unlock(&fs_info->reclaim_bgs_lock);
3923 spin_lock(&fs_info->balance_lock);
3924 bctl->stat.expected++;
3925 spin_unlock(&fs_info->balance_lock);
3927 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3929 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3931 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3938 * Apply limit_min filter, no need to check if the LIMITS
3939 * filter is used, limit_min is 0 by default
3941 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3942 count_data < bctl->data.limit_min)
3943 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3944 count_meta < bctl->meta.limit_min)
3945 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3946 count_sys < bctl->sys.limit_min)) {
3947 mutex_unlock(&fs_info->reclaim_bgs_lock);
3951 if (!chunk_reserved) {
3953 * We may be relocating the only data chunk we have,
3954 * which could potentially end up with losing data's
3955 * raid profile, so lets allocate an empty one in
3958 ret = btrfs_may_alloc_data_chunk(fs_info,
3961 mutex_unlock(&fs_info->reclaim_bgs_lock);
3963 } else if (ret == 1) {
3968 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3969 mutex_unlock(&fs_info->reclaim_bgs_lock);
3970 if (ret == -ENOSPC) {
3972 } else if (ret == -ETXTBSY) {
3974 "skipping relocation of block group %llu due to active swapfile",
3980 spin_lock(&fs_info->balance_lock);
3981 bctl->stat.completed++;
3982 spin_unlock(&fs_info->balance_lock);
3985 if (found_key.offset == 0)
3987 key.offset = found_key.offset - 1;
3991 btrfs_release_path(path);
3996 btrfs_free_path(path);
3997 if (enospc_errors) {
3998 btrfs_info(fs_info, "%d enospc errors during balance",
4008 * See if a given profile is valid and reduced.
4010 * @flags: profile to validate
4011 * @extended: if true @flags is treated as an extended profile
4013 static int alloc_profile_is_valid(u64 flags, int extended)
4015 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
4016 BTRFS_BLOCK_GROUP_PROFILE_MASK);
4018 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
4020 /* 1) check that all other bits are zeroed */
4024 /* 2) see if profile is reduced */
4026 return !extended; /* "0" is valid for usual profiles */
4028 return has_single_bit_set(flags);
4032 * Validate target profile against allowed profiles and return true if it's OK.
4033 * Otherwise print the error message and return false.
4035 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
4036 const struct btrfs_balance_args *bargs,
4037 u64 allowed, const char *type)
4039 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4042 /* Profile is valid and does not have bits outside of the allowed set */
4043 if (alloc_profile_is_valid(bargs->target, 1) &&
4044 (bargs->target & ~allowed) == 0)
4047 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
4048 type, btrfs_bg_type_to_raid_name(bargs->target));
4053 * Fill @buf with textual description of balance filter flags @bargs, up to
4054 * @size_buf including the terminating null. The output may be trimmed if it
4055 * does not fit into the provided buffer.
4057 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4061 u32 size_bp = size_buf;
4063 u64 flags = bargs->flags;
4064 char tmp_buf[128] = {'\0'};
4069 #define CHECK_APPEND_NOARG(a) \
4071 ret = snprintf(bp, size_bp, (a)); \
4072 if (ret < 0 || ret >= size_bp) \
4073 goto out_overflow; \
4078 #define CHECK_APPEND_1ARG(a, v1) \
4080 ret = snprintf(bp, size_bp, (a), (v1)); \
4081 if (ret < 0 || ret >= size_bp) \
4082 goto out_overflow; \
4087 #define CHECK_APPEND_2ARG(a, v1, v2) \
4089 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
4090 if (ret < 0 || ret >= size_bp) \
4091 goto out_overflow; \
4096 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4097 CHECK_APPEND_1ARG("convert=%s,",
4098 btrfs_bg_type_to_raid_name(bargs->target));
4100 if (flags & BTRFS_BALANCE_ARGS_SOFT)
4101 CHECK_APPEND_NOARG("soft,");
4103 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4104 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4106 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4109 if (flags & BTRFS_BALANCE_ARGS_USAGE)
4110 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4112 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4113 CHECK_APPEND_2ARG("usage=%u..%u,",
4114 bargs->usage_min, bargs->usage_max);
4116 if (flags & BTRFS_BALANCE_ARGS_DEVID)
4117 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4119 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4120 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4121 bargs->pstart, bargs->pend);
4123 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4124 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4125 bargs->vstart, bargs->vend);
4127 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4128 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4130 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4131 CHECK_APPEND_2ARG("limit=%u..%u,",
4132 bargs->limit_min, bargs->limit_max);
4134 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4135 CHECK_APPEND_2ARG("stripes=%u..%u,",
4136 bargs->stripes_min, bargs->stripes_max);
4138 #undef CHECK_APPEND_2ARG
4139 #undef CHECK_APPEND_1ARG
4140 #undef CHECK_APPEND_NOARG
4144 if (size_bp < size_buf)
4145 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4150 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4152 u32 size_buf = 1024;
4153 char tmp_buf[192] = {'\0'};
4156 u32 size_bp = size_buf;
4158 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4160 buf = kzalloc(size_buf, GFP_KERNEL);
4166 #define CHECK_APPEND_1ARG(a, v1) \
4168 ret = snprintf(bp, size_bp, (a), (v1)); \
4169 if (ret < 0 || ret >= size_bp) \
4170 goto out_overflow; \
4175 if (bctl->flags & BTRFS_BALANCE_FORCE)
4176 CHECK_APPEND_1ARG("%s", "-f ");
4178 if (bctl->flags & BTRFS_BALANCE_DATA) {
4179 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4180 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4183 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4184 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4185 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4188 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4189 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4190 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4193 #undef CHECK_APPEND_1ARG
4197 if (size_bp < size_buf)
4198 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4199 btrfs_info(fs_info, "balance: %s %s",
4200 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4201 "resume" : "start", buf);
4207 * Should be called with balance mutexe held
4209 int btrfs_balance(struct btrfs_fs_info *fs_info,
4210 struct btrfs_balance_control *bctl,
4211 struct btrfs_ioctl_balance_args *bargs)
4213 u64 meta_target, data_target;
4219 bool reducing_redundancy;
4220 bool paused = false;
4223 if (btrfs_fs_closing(fs_info) ||
4224 atomic_read(&fs_info->balance_pause_req) ||
4225 btrfs_should_cancel_balance(fs_info)) {
4230 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4231 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4235 * In case of mixed groups both data and meta should be picked,
4236 * and identical options should be given for both of them.
4238 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4239 if (mixed && (bctl->flags & allowed)) {
4240 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4241 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4242 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4244 "balance: mixed groups data and metadata options must be the same");
4251 * rw_devices will not change at the moment, device add/delete/replace
4254 num_devices = fs_info->fs_devices->rw_devices;
4257 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4258 * special bit for it, to make it easier to distinguish. Thus we need
4259 * to set it manually, or balance would refuse the profile.
4261 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4262 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4263 if (num_devices >= btrfs_raid_array[i].devs_min)
4264 allowed |= btrfs_raid_array[i].bg_flag;
4266 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4267 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4268 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
4274 * Allow to reduce metadata or system integrity only if force set for
4275 * profiles with redundancy (copies, parity)
4278 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4279 if (btrfs_raid_array[i].ncopies >= 2 ||
4280 btrfs_raid_array[i].tolerated_failures >= 1)
4281 allowed |= btrfs_raid_array[i].bg_flag;
4284 seq = read_seqbegin(&fs_info->profiles_lock);
4286 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4287 (fs_info->avail_system_alloc_bits & allowed) &&
4288 !(bctl->sys.target & allowed)) ||
4289 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4290 (fs_info->avail_metadata_alloc_bits & allowed) &&
4291 !(bctl->meta.target & allowed)))
4292 reducing_redundancy = true;
4294 reducing_redundancy = false;
4296 /* if we're not converting, the target field is uninitialized */
4297 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4298 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4299 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4300 bctl->data.target : fs_info->avail_data_alloc_bits;
4301 } while (read_seqretry(&fs_info->profiles_lock, seq));
4303 if (reducing_redundancy) {
4304 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4306 "balance: force reducing metadata redundancy");
4309 "balance: reduces metadata redundancy, use --force if you want this");
4315 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4316 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4318 "balance: metadata profile %s has lower redundancy than data profile %s",
4319 btrfs_bg_type_to_raid_name(meta_target),
4320 btrfs_bg_type_to_raid_name(data_target));
4323 ret = insert_balance_item(fs_info, bctl);
4324 if (ret && ret != -EEXIST)
4327 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4328 BUG_ON(ret == -EEXIST);
4329 BUG_ON(fs_info->balance_ctl);
4330 spin_lock(&fs_info->balance_lock);
4331 fs_info->balance_ctl = bctl;
4332 spin_unlock(&fs_info->balance_lock);
4334 BUG_ON(ret != -EEXIST);
4335 spin_lock(&fs_info->balance_lock);
4336 update_balance_args(bctl);
4337 spin_unlock(&fs_info->balance_lock);
4340 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4341 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4342 describe_balance_start_or_resume(fs_info);
4343 mutex_unlock(&fs_info->balance_mutex);
4345 ret = __btrfs_balance(fs_info);
4347 mutex_lock(&fs_info->balance_mutex);
4348 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req)) {
4349 btrfs_info(fs_info, "balance: paused");
4350 btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
4354 * Balance can be canceled by:
4356 * - Regular cancel request
4357 * Then ret == -ECANCELED and balance_cancel_req > 0
4359 * - Fatal signal to "btrfs" process
4360 * Either the signal caught by wait_reserve_ticket() and callers
4361 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4363 * Either way, in this case balance_cancel_req = 0, and
4364 * ret == -EINTR or ret == -ECANCELED.
4366 * So here we only check the return value to catch canceled balance.
4368 else if (ret == -ECANCELED || ret == -EINTR)
4369 btrfs_info(fs_info, "balance: canceled");
4371 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4373 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4376 memset(bargs, 0, sizeof(*bargs));
4377 btrfs_update_ioctl_balance_args(fs_info, bargs);
4380 /* We didn't pause, we can clean everything up. */
4382 reset_balance_state(fs_info);
4383 btrfs_exclop_finish(fs_info);
4386 wake_up(&fs_info->balance_wait_q);
4390 if (bctl->flags & BTRFS_BALANCE_RESUME)
4391 reset_balance_state(fs_info);
4394 btrfs_exclop_finish(fs_info);
4399 static int balance_kthread(void *data)
4401 struct btrfs_fs_info *fs_info = data;
4404 sb_start_write(fs_info->sb);
4405 mutex_lock(&fs_info->balance_mutex);
4406 if (fs_info->balance_ctl)
4407 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4408 mutex_unlock(&fs_info->balance_mutex);
4409 sb_end_write(fs_info->sb);
4414 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4416 struct task_struct *tsk;
4418 mutex_lock(&fs_info->balance_mutex);
4419 if (!fs_info->balance_ctl) {
4420 mutex_unlock(&fs_info->balance_mutex);
4423 mutex_unlock(&fs_info->balance_mutex);
4425 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4426 btrfs_info(fs_info, "balance: resume skipped");
4430 spin_lock(&fs_info->super_lock);
4431 ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED);
4432 fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
4433 spin_unlock(&fs_info->super_lock);
4435 * A ro->rw remount sequence should continue with the paused balance
4436 * regardless of who pauses it, system or the user as of now, so set
4439 spin_lock(&fs_info->balance_lock);
4440 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4441 spin_unlock(&fs_info->balance_lock);
4443 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4444 return PTR_ERR_OR_ZERO(tsk);
4447 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4449 struct btrfs_balance_control *bctl;
4450 struct btrfs_balance_item *item;
4451 struct btrfs_disk_balance_args disk_bargs;
4452 struct btrfs_path *path;
4453 struct extent_buffer *leaf;
4454 struct btrfs_key key;
4457 path = btrfs_alloc_path();
4461 key.objectid = BTRFS_BALANCE_OBJECTID;
4462 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4465 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4468 if (ret > 0) { /* ret = -ENOENT; */
4473 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4479 leaf = path->nodes[0];
4480 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4482 bctl->flags = btrfs_balance_flags(leaf, item);
4483 bctl->flags |= BTRFS_BALANCE_RESUME;
4485 btrfs_balance_data(leaf, item, &disk_bargs);
4486 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4487 btrfs_balance_meta(leaf, item, &disk_bargs);
4488 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4489 btrfs_balance_sys(leaf, item, &disk_bargs);
4490 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4493 * This should never happen, as the paused balance state is recovered
4494 * during mount without any chance of other exclusive ops to collide.
4496 * This gives the exclusive op status to balance and keeps in paused
4497 * state until user intervention (cancel or umount). If the ownership
4498 * cannot be assigned, show a message but do not fail. The balance
4499 * is in a paused state and must have fs_info::balance_ctl properly
4502 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED))
4504 "balance: cannot set exclusive op status, resume manually");
4506 btrfs_release_path(path);
4508 mutex_lock(&fs_info->balance_mutex);
4509 BUG_ON(fs_info->balance_ctl);
4510 spin_lock(&fs_info->balance_lock);
4511 fs_info->balance_ctl = bctl;
4512 spin_unlock(&fs_info->balance_lock);
4513 mutex_unlock(&fs_info->balance_mutex);
4515 btrfs_free_path(path);
4519 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4523 mutex_lock(&fs_info->balance_mutex);
4524 if (!fs_info->balance_ctl) {
4525 mutex_unlock(&fs_info->balance_mutex);
4529 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4530 atomic_inc(&fs_info->balance_pause_req);
4531 mutex_unlock(&fs_info->balance_mutex);
4533 wait_event(fs_info->balance_wait_q,
4534 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4536 mutex_lock(&fs_info->balance_mutex);
4537 /* we are good with balance_ctl ripped off from under us */
4538 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4539 atomic_dec(&fs_info->balance_pause_req);
4544 mutex_unlock(&fs_info->balance_mutex);
4548 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4550 mutex_lock(&fs_info->balance_mutex);
4551 if (!fs_info->balance_ctl) {
4552 mutex_unlock(&fs_info->balance_mutex);
4557 * A paused balance with the item stored on disk can be resumed at
4558 * mount time if the mount is read-write. Otherwise it's still paused
4559 * and we must not allow cancelling as it deletes the item.
4561 if (sb_rdonly(fs_info->sb)) {
4562 mutex_unlock(&fs_info->balance_mutex);
4566 atomic_inc(&fs_info->balance_cancel_req);
4568 * if we are running just wait and return, balance item is
4569 * deleted in btrfs_balance in this case
4571 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4572 mutex_unlock(&fs_info->balance_mutex);
4573 wait_event(fs_info->balance_wait_q,
4574 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4575 mutex_lock(&fs_info->balance_mutex);
4577 mutex_unlock(&fs_info->balance_mutex);
4579 * Lock released to allow other waiters to continue, we'll
4580 * reexamine the status again.
4582 mutex_lock(&fs_info->balance_mutex);
4584 if (fs_info->balance_ctl) {
4585 reset_balance_state(fs_info);
4586 btrfs_exclop_finish(fs_info);
4587 btrfs_info(fs_info, "balance: canceled");
4591 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4592 atomic_dec(&fs_info->balance_cancel_req);
4593 mutex_unlock(&fs_info->balance_mutex);
4597 int btrfs_uuid_scan_kthread(void *data)
4599 struct btrfs_fs_info *fs_info = data;
4600 struct btrfs_root *root = fs_info->tree_root;
4601 struct btrfs_key key;
4602 struct btrfs_path *path = NULL;
4604 struct extent_buffer *eb;
4606 struct btrfs_root_item root_item;
4608 struct btrfs_trans_handle *trans = NULL;
4609 bool closing = false;
4611 path = btrfs_alloc_path();
4618 key.type = BTRFS_ROOT_ITEM_KEY;
4622 if (btrfs_fs_closing(fs_info)) {
4626 ret = btrfs_search_forward(root, &key, path,
4627 BTRFS_OLDEST_GENERATION);
4634 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4635 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4636 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4637 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4640 eb = path->nodes[0];
4641 slot = path->slots[0];
4642 item_size = btrfs_item_size(eb, slot);
4643 if (item_size < sizeof(root_item))
4646 read_extent_buffer(eb, &root_item,
4647 btrfs_item_ptr_offset(eb, slot),
4648 (int)sizeof(root_item));
4649 if (btrfs_root_refs(&root_item) == 0)
4652 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4653 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4657 btrfs_release_path(path);
4659 * 1 - subvol uuid item
4660 * 1 - received_subvol uuid item
4662 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4663 if (IS_ERR(trans)) {
4664 ret = PTR_ERR(trans);
4672 btrfs_release_path(path);
4673 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4674 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4675 BTRFS_UUID_KEY_SUBVOL,
4678 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4684 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4685 ret = btrfs_uuid_tree_add(trans,
4686 root_item.received_uuid,
4687 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4690 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4697 btrfs_release_path(path);
4699 ret = btrfs_end_transaction(trans);
4705 if (key.offset < (u64)-1) {
4707 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4709 key.type = BTRFS_ROOT_ITEM_KEY;
4710 } else if (key.objectid < (u64)-1) {
4712 key.type = BTRFS_ROOT_ITEM_KEY;
4721 btrfs_free_path(path);
4722 if (trans && !IS_ERR(trans))
4723 btrfs_end_transaction(trans);
4725 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4727 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4728 up(&fs_info->uuid_tree_rescan_sem);
4732 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4734 struct btrfs_trans_handle *trans;
4735 struct btrfs_root *tree_root = fs_info->tree_root;
4736 struct btrfs_root *uuid_root;
4737 struct task_struct *task;
4744 trans = btrfs_start_transaction(tree_root, 2);
4746 return PTR_ERR(trans);
4748 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4749 if (IS_ERR(uuid_root)) {
4750 ret = PTR_ERR(uuid_root);
4751 btrfs_abort_transaction(trans, ret);
4752 btrfs_end_transaction(trans);
4756 fs_info->uuid_root = uuid_root;
4758 ret = btrfs_commit_transaction(trans);
4762 down(&fs_info->uuid_tree_rescan_sem);
4763 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4765 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4766 btrfs_warn(fs_info, "failed to start uuid_scan task");
4767 up(&fs_info->uuid_tree_rescan_sem);
4768 return PTR_ERR(task);
4775 * shrinking a device means finding all of the device extents past
4776 * the new size, and then following the back refs to the chunks.
4777 * The chunk relocation code actually frees the device extent
4779 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4781 struct btrfs_fs_info *fs_info = device->fs_info;
4782 struct btrfs_root *root = fs_info->dev_root;
4783 struct btrfs_trans_handle *trans;
4784 struct btrfs_dev_extent *dev_extent = NULL;
4785 struct btrfs_path *path;
4791 bool retried = false;
4792 struct extent_buffer *l;
4793 struct btrfs_key key;
4794 struct btrfs_super_block *super_copy = fs_info->super_copy;
4795 u64 old_total = btrfs_super_total_bytes(super_copy);
4796 u64 old_size = btrfs_device_get_total_bytes(device);
4801 new_size = round_down(new_size, fs_info->sectorsize);
4803 diff = round_down(old_size - new_size, fs_info->sectorsize);
4805 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4808 path = btrfs_alloc_path();
4812 path->reada = READA_BACK;
4814 trans = btrfs_start_transaction(root, 0);
4815 if (IS_ERR(trans)) {
4816 btrfs_free_path(path);
4817 return PTR_ERR(trans);
4820 mutex_lock(&fs_info->chunk_mutex);
4822 btrfs_device_set_total_bytes(device, new_size);
4823 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4824 device->fs_devices->total_rw_bytes -= diff;
4827 * The new free_chunk_space is new_size - used, so we have to
4828 * subtract the delta of the old free_chunk_space which included
4829 * old_size - used. If used > new_size then just subtract this
4830 * entire device's free space.
4832 if (device->bytes_used < new_size)
4833 free_diff = (old_size - device->bytes_used) -
4834 (new_size - device->bytes_used);
4836 free_diff = old_size - device->bytes_used;
4837 atomic64_sub(free_diff, &fs_info->free_chunk_space);
4841 * Once the device's size has been set to the new size, ensure all
4842 * in-memory chunks are synced to disk so that the loop below sees them
4843 * and relocates them accordingly.
4845 if (contains_pending_extent(device, &start, diff)) {
4846 mutex_unlock(&fs_info->chunk_mutex);
4847 ret = btrfs_commit_transaction(trans);
4851 mutex_unlock(&fs_info->chunk_mutex);
4852 btrfs_end_transaction(trans);
4856 key.objectid = device->devid;
4857 key.offset = (u64)-1;
4858 key.type = BTRFS_DEV_EXTENT_KEY;
4861 mutex_lock(&fs_info->reclaim_bgs_lock);
4862 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4864 mutex_unlock(&fs_info->reclaim_bgs_lock);
4868 ret = btrfs_previous_item(root, path, 0, key.type);
4870 mutex_unlock(&fs_info->reclaim_bgs_lock);
4874 btrfs_release_path(path);
4879 slot = path->slots[0];
4880 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4882 if (key.objectid != device->devid) {
4883 mutex_unlock(&fs_info->reclaim_bgs_lock);
4884 btrfs_release_path(path);
4888 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4889 length = btrfs_dev_extent_length(l, dev_extent);
4891 if (key.offset + length <= new_size) {
4892 mutex_unlock(&fs_info->reclaim_bgs_lock);
4893 btrfs_release_path(path);
4897 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4898 btrfs_release_path(path);
4901 * We may be relocating the only data chunk we have,
4902 * which could potentially end up with losing data's
4903 * raid profile, so lets allocate an empty one in
4906 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4908 mutex_unlock(&fs_info->reclaim_bgs_lock);
4912 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4913 mutex_unlock(&fs_info->reclaim_bgs_lock);
4914 if (ret == -ENOSPC) {
4917 if (ret == -ETXTBSY) {
4919 "could not shrink block group %llu due to active swapfile",
4924 } while (key.offset-- > 0);
4926 if (failed && !retried) {
4930 } else if (failed && retried) {
4935 /* Shrinking succeeded, else we would be at "done". */
4936 trans = btrfs_start_transaction(root, 0);
4937 if (IS_ERR(trans)) {
4938 ret = PTR_ERR(trans);
4942 mutex_lock(&fs_info->chunk_mutex);
4943 /* Clear all state bits beyond the shrunk device size */
4944 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4947 btrfs_device_set_disk_total_bytes(device, new_size);
4948 if (list_empty(&device->post_commit_list))
4949 list_add_tail(&device->post_commit_list,
4950 &trans->transaction->dev_update_list);
4952 WARN_ON(diff > old_total);
4953 btrfs_set_super_total_bytes(super_copy,
4954 round_down(old_total - diff, fs_info->sectorsize));
4955 mutex_unlock(&fs_info->chunk_mutex);
4957 btrfs_reserve_chunk_metadata(trans, false);
4958 /* Now btrfs_update_device() will change the on-disk size. */
4959 ret = btrfs_update_device(trans, device);
4960 btrfs_trans_release_chunk_metadata(trans);
4962 btrfs_abort_transaction(trans, ret);
4963 btrfs_end_transaction(trans);
4965 ret = btrfs_commit_transaction(trans);
4968 btrfs_free_path(path);
4970 mutex_lock(&fs_info->chunk_mutex);
4971 btrfs_device_set_total_bytes(device, old_size);
4972 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4973 device->fs_devices->total_rw_bytes += diff;
4974 atomic64_add(free_diff, &fs_info->free_chunk_space);
4976 mutex_unlock(&fs_info->chunk_mutex);
4981 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4982 struct btrfs_key *key,
4983 struct btrfs_chunk *chunk, int item_size)
4985 struct btrfs_super_block *super_copy = fs_info->super_copy;
4986 struct btrfs_disk_key disk_key;
4990 lockdep_assert_held(&fs_info->chunk_mutex);
4992 array_size = btrfs_super_sys_array_size(super_copy);
4993 if (array_size + item_size + sizeof(disk_key)
4994 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
4997 ptr = super_copy->sys_chunk_array + array_size;
4998 btrfs_cpu_key_to_disk(&disk_key, key);
4999 memcpy(ptr, &disk_key, sizeof(disk_key));
5000 ptr += sizeof(disk_key);
5001 memcpy(ptr, chunk, item_size);
5002 item_size += sizeof(disk_key);
5003 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
5009 * sort the devices in descending order by max_avail, total_avail
5011 static int btrfs_cmp_device_info(const void *a, const void *b)
5013 const struct btrfs_device_info *di_a = a;
5014 const struct btrfs_device_info *di_b = b;
5016 if (di_a->max_avail > di_b->max_avail)
5018 if (di_a->max_avail < di_b->max_avail)
5020 if (di_a->total_avail > di_b->total_avail)
5022 if (di_a->total_avail < di_b->total_avail)
5027 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
5029 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5032 btrfs_set_fs_incompat(info, RAID56);
5035 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
5037 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
5040 btrfs_set_fs_incompat(info, RAID1C34);
5044 * Structure used internally for btrfs_create_chunk() function.
5045 * Wraps needed parameters.
5047 struct alloc_chunk_ctl {
5050 /* Total number of stripes to allocate */
5052 /* sub_stripes info for map */
5054 /* Stripes per device */
5056 /* Maximum number of devices to use */
5058 /* Minimum number of devices to use */
5060 /* ndevs has to be a multiple of this */
5062 /* Number of copies */
5064 /* Number of stripes worth of bytes to store parity information */
5066 u64 max_stripe_size;
5074 static void init_alloc_chunk_ctl_policy_regular(
5075 struct btrfs_fs_devices *fs_devices,
5076 struct alloc_chunk_ctl *ctl)
5078 struct btrfs_space_info *space_info;
5080 space_info = btrfs_find_space_info(fs_devices->fs_info, ctl->type);
5083 ctl->max_chunk_size = READ_ONCE(space_info->chunk_size);
5084 ctl->max_stripe_size = ctl->max_chunk_size;
5086 if (ctl->type & BTRFS_BLOCK_GROUP_SYSTEM)
5087 ctl->devs_max = min_t(int, ctl->devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
5089 /* We don't want a chunk larger than 10% of writable space */
5090 ctl->max_chunk_size = min(mult_perc(fs_devices->total_rw_bytes, 10),
5091 ctl->max_chunk_size);
5092 ctl->dev_extent_min = btrfs_stripe_nr_to_offset(ctl->dev_stripes);
5095 static void init_alloc_chunk_ctl_policy_zoned(
5096 struct btrfs_fs_devices *fs_devices,
5097 struct alloc_chunk_ctl *ctl)
5099 u64 zone_size = fs_devices->fs_info->zone_size;
5101 int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5102 int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5103 u64 min_chunk_size = min_data_stripes * zone_size;
5104 u64 type = ctl->type;
5106 ctl->max_stripe_size = zone_size;
5107 if (type & BTRFS_BLOCK_GROUP_DATA) {
5108 ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5110 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5111 ctl->max_chunk_size = ctl->max_stripe_size;
5112 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5113 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5114 ctl->devs_max = min_t(int, ctl->devs_max,
5115 BTRFS_MAX_DEVS_SYS_CHUNK);
5120 /* We don't want a chunk larger than 10% of writable space */
5121 limit = max(round_down(mult_perc(fs_devices->total_rw_bytes, 10),
5124 ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5125 ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5128 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5129 struct alloc_chunk_ctl *ctl)
5131 int index = btrfs_bg_flags_to_raid_index(ctl->type);
5133 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5134 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5135 ctl->devs_max = btrfs_raid_array[index].devs_max;
5137 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5138 ctl->devs_min = btrfs_raid_array[index].devs_min;
5139 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5140 ctl->ncopies = btrfs_raid_array[index].ncopies;
5141 ctl->nparity = btrfs_raid_array[index].nparity;
5144 switch (fs_devices->chunk_alloc_policy) {
5145 case BTRFS_CHUNK_ALLOC_REGULAR:
5146 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5148 case BTRFS_CHUNK_ALLOC_ZONED:
5149 init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5156 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5157 struct alloc_chunk_ctl *ctl,
5158 struct btrfs_device_info *devices_info)
5160 struct btrfs_fs_info *info = fs_devices->fs_info;
5161 struct btrfs_device *device;
5163 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5170 * in the first pass through the devices list, we gather information
5171 * about the available holes on each device.
5173 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5174 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5176 "BTRFS: read-only device in alloc_list\n");
5180 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5181 &device->dev_state) ||
5182 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5185 if (device->total_bytes > device->bytes_used)
5186 total_avail = device->total_bytes - device->bytes_used;
5190 /* If there is no space on this device, skip it. */
5191 if (total_avail < ctl->dev_extent_min)
5194 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5196 if (ret && ret != -ENOSPC)
5200 max_avail = dev_extent_want;
5202 if (max_avail < ctl->dev_extent_min) {
5203 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5205 "%s: devid %llu has no free space, have=%llu want=%llu",
5206 __func__, device->devid, max_avail,
5207 ctl->dev_extent_min);
5211 if (ndevs == fs_devices->rw_devices) {
5212 WARN(1, "%s: found more than %llu devices\n",
5213 __func__, fs_devices->rw_devices);
5216 devices_info[ndevs].dev_offset = dev_offset;
5217 devices_info[ndevs].max_avail = max_avail;
5218 devices_info[ndevs].total_avail = total_avail;
5219 devices_info[ndevs].dev = device;
5225 * now sort the devices by hole size / available space
5227 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5228 btrfs_cmp_device_info, NULL);
5233 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5234 struct btrfs_device_info *devices_info)
5236 /* Number of stripes that count for block group size */
5240 * The primary goal is to maximize the number of stripes, so use as
5241 * many devices as possible, even if the stripes are not maximum sized.
5243 * The DUP profile stores more than one stripe per device, the
5244 * max_avail is the total size so we have to adjust.
5246 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5248 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5250 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5251 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5254 * Use the number of data stripes to figure out how big this chunk is
5255 * really going to be in terms of logical address space, and compare
5256 * that answer with the max chunk size. If it's higher, we try to
5257 * reduce stripe_size.
5259 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5261 * Reduce stripe_size, round it up to a 16MB boundary again and
5262 * then use it, unless it ends up being even bigger than the
5263 * previous value we had already.
5265 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5266 data_stripes), SZ_16M),
5270 /* Stripe size should not go beyond 1G. */
5271 ctl->stripe_size = min_t(u64, ctl->stripe_size, SZ_1G);
5273 /* Align to BTRFS_STRIPE_LEN */
5274 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5275 ctl->chunk_size = ctl->stripe_size * data_stripes;
5280 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5281 struct btrfs_device_info *devices_info)
5283 u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5284 /* Number of stripes that count for block group size */
5288 * It should hold because:
5289 * dev_extent_min == dev_extent_want == zone_size * dev_stripes
5291 ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min);
5293 ctl->stripe_size = zone_size;
5294 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5295 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5297 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */
5298 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5299 ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5300 ctl->stripe_size) + ctl->nparity,
5302 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5303 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5304 ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size);
5307 ctl->chunk_size = ctl->stripe_size * data_stripes;
5312 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5313 struct alloc_chunk_ctl *ctl,
5314 struct btrfs_device_info *devices_info)
5316 struct btrfs_fs_info *info = fs_devices->fs_info;
5319 * Round down to number of usable stripes, devs_increment can be any
5320 * number so we can't use round_down() that requires power of 2, while
5321 * rounddown is safe.
5323 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5325 if (ctl->ndevs < ctl->devs_min) {
5326 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5328 "%s: not enough devices with free space: have=%d minimum required=%d",
5329 __func__, ctl->ndevs, ctl->devs_min);
5334 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5336 switch (fs_devices->chunk_alloc_policy) {
5337 case BTRFS_CHUNK_ALLOC_REGULAR:
5338 return decide_stripe_size_regular(ctl, devices_info);
5339 case BTRFS_CHUNK_ALLOC_ZONED:
5340 return decide_stripe_size_zoned(ctl, devices_info);
5346 static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
5347 struct alloc_chunk_ctl *ctl,
5348 struct btrfs_device_info *devices_info)
5350 struct btrfs_fs_info *info = trans->fs_info;
5351 struct map_lookup *map = NULL;
5352 struct extent_map_tree *em_tree;
5353 struct btrfs_block_group *block_group;
5354 struct extent_map *em;
5355 u64 start = ctl->start;
5356 u64 type = ctl->type;
5361 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5363 return ERR_PTR(-ENOMEM);
5364 map->num_stripes = ctl->num_stripes;
5366 for (i = 0; i < ctl->ndevs; ++i) {
5367 for (j = 0; j < ctl->dev_stripes; ++j) {
5368 int s = i * ctl->dev_stripes + j;
5369 map->stripes[s].dev = devices_info[i].dev;
5370 map->stripes[s].physical = devices_info[i].dev_offset +
5371 j * ctl->stripe_size;
5374 map->io_align = BTRFS_STRIPE_LEN;
5375 map->io_width = BTRFS_STRIPE_LEN;
5377 map->sub_stripes = ctl->sub_stripes;
5379 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5381 em = alloc_extent_map();
5384 return ERR_PTR(-ENOMEM);
5386 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5387 em->map_lookup = map;
5389 em->len = ctl->chunk_size;
5390 em->block_start = 0;
5391 em->block_len = em->len;
5392 em->orig_block_len = ctl->stripe_size;
5394 em_tree = &info->mapping_tree;
5395 write_lock(&em_tree->lock);
5396 ret = add_extent_mapping(em_tree, em, 0);
5398 write_unlock(&em_tree->lock);
5399 free_extent_map(em);
5400 return ERR_PTR(ret);
5402 write_unlock(&em_tree->lock);
5404 block_group = btrfs_make_block_group(trans, type, start, ctl->chunk_size);
5405 if (IS_ERR(block_group))
5406 goto error_del_extent;
5408 for (i = 0; i < map->num_stripes; i++) {
5409 struct btrfs_device *dev = map->stripes[i].dev;
5411 btrfs_device_set_bytes_used(dev,
5412 dev->bytes_used + ctl->stripe_size);
5413 if (list_empty(&dev->post_commit_list))
5414 list_add_tail(&dev->post_commit_list,
5415 &trans->transaction->dev_update_list);
5418 atomic64_sub(ctl->stripe_size * map->num_stripes,
5419 &info->free_chunk_space);
5421 free_extent_map(em);
5422 check_raid56_incompat_flag(info, type);
5423 check_raid1c34_incompat_flag(info, type);
5428 write_lock(&em_tree->lock);
5429 remove_extent_mapping(em_tree, em);
5430 write_unlock(&em_tree->lock);
5432 /* One for our allocation */
5433 free_extent_map(em);
5434 /* One for the tree reference */
5435 free_extent_map(em);
5440 struct btrfs_block_group *btrfs_create_chunk(struct btrfs_trans_handle *trans,
5443 struct btrfs_fs_info *info = trans->fs_info;
5444 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5445 struct btrfs_device_info *devices_info = NULL;
5446 struct alloc_chunk_ctl ctl;
5447 struct btrfs_block_group *block_group;
5450 lockdep_assert_held(&info->chunk_mutex);
5452 if (!alloc_profile_is_valid(type, 0)) {
5454 return ERR_PTR(-EINVAL);
5457 if (list_empty(&fs_devices->alloc_list)) {
5458 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5459 btrfs_debug(info, "%s: no writable device", __func__);
5460 return ERR_PTR(-ENOSPC);
5463 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5464 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5466 return ERR_PTR(-EINVAL);
5469 ctl.start = find_next_chunk(info);
5471 init_alloc_chunk_ctl(fs_devices, &ctl);
5473 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5476 return ERR_PTR(-ENOMEM);
5478 ret = gather_device_info(fs_devices, &ctl, devices_info);
5480 block_group = ERR_PTR(ret);
5484 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5486 block_group = ERR_PTR(ret);
5490 block_group = create_chunk(trans, &ctl, devices_info);
5493 kfree(devices_info);
5498 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5499 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5502 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5505 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
5506 struct btrfs_block_group *bg)
5508 struct btrfs_fs_info *fs_info = trans->fs_info;
5509 struct btrfs_root *chunk_root = fs_info->chunk_root;
5510 struct btrfs_key key;
5511 struct btrfs_chunk *chunk;
5512 struct btrfs_stripe *stripe;
5513 struct extent_map *em;
5514 struct map_lookup *map;
5520 * We take the chunk_mutex for 2 reasons:
5522 * 1) Updates and insertions in the chunk btree must be done while holding
5523 * the chunk_mutex, as well as updating the system chunk array in the
5524 * superblock. See the comment on top of btrfs_chunk_alloc() for the
5527 * 2) To prevent races with the final phase of a device replace operation
5528 * that replaces the device object associated with the map's stripes,
5529 * because the device object's id can change at any time during that
5530 * final phase of the device replace operation
5531 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5532 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5533 * which would cause a failure when updating the device item, which does
5534 * not exists, or persisting a stripe of the chunk item with such ID.
5535 * Here we can't use the device_list_mutex because our caller already
5536 * has locked the chunk_mutex, and the final phase of device replace
5537 * acquires both mutexes - first the device_list_mutex and then the
5538 * chunk_mutex. Using any of those two mutexes protects us from a
5539 * concurrent device replace.
5541 lockdep_assert_held(&fs_info->chunk_mutex);
5543 em = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
5546 btrfs_abort_transaction(trans, ret);
5550 map = em->map_lookup;
5551 item_size = btrfs_chunk_item_size(map->num_stripes);
5553 chunk = kzalloc(item_size, GFP_NOFS);
5556 btrfs_abort_transaction(trans, ret);
5560 for (i = 0; i < map->num_stripes; i++) {
5561 struct btrfs_device *device = map->stripes[i].dev;
5563 ret = btrfs_update_device(trans, device);
5568 stripe = &chunk->stripe;
5569 for (i = 0; i < map->num_stripes; i++) {
5570 struct btrfs_device *device = map->stripes[i].dev;
5571 const u64 dev_offset = map->stripes[i].physical;
5573 btrfs_set_stack_stripe_devid(stripe, device->devid);
5574 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5575 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5579 btrfs_set_stack_chunk_length(chunk, bg->length);
5580 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
5581 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
5582 btrfs_set_stack_chunk_type(chunk, map->type);
5583 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5584 btrfs_set_stack_chunk_io_align(chunk, BTRFS_STRIPE_LEN);
5585 btrfs_set_stack_chunk_io_width(chunk, BTRFS_STRIPE_LEN);
5586 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5587 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5589 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5590 key.type = BTRFS_CHUNK_ITEM_KEY;
5591 key.offset = bg->start;
5593 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5597 set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED, &bg->runtime_flags);
5599 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5600 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5607 free_extent_map(em);
5611 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5613 struct btrfs_fs_info *fs_info = trans->fs_info;
5615 struct btrfs_block_group *meta_bg;
5616 struct btrfs_block_group *sys_bg;
5619 * When adding a new device for sprouting, the seed device is read-only
5620 * so we must first allocate a metadata and a system chunk. But before
5621 * adding the block group items to the extent, device and chunk btrees,
5624 * 1) Create both chunks without doing any changes to the btrees, as
5625 * otherwise we would get -ENOSPC since the block groups from the
5626 * seed device are read-only;
5628 * 2) Add the device item for the new sprout device - finishing the setup
5629 * of a new block group requires updating the device item in the chunk
5630 * btree, so it must exist when we attempt to do it. The previous step
5631 * ensures this does not fail with -ENOSPC.
5633 * After that we can add the block group items to their btrees:
5634 * update existing device item in the chunk btree, add a new block group
5635 * item to the extent btree, add a new chunk item to the chunk btree and
5636 * finally add the new device extent items to the devices btree.
5639 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5640 meta_bg = btrfs_create_chunk(trans, alloc_profile);
5641 if (IS_ERR(meta_bg))
5642 return PTR_ERR(meta_bg);
5644 alloc_profile = btrfs_system_alloc_profile(fs_info);
5645 sys_bg = btrfs_create_chunk(trans, alloc_profile);
5647 return PTR_ERR(sys_bg);
5652 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5654 const int index = btrfs_bg_flags_to_raid_index(map->type);
5656 return btrfs_raid_array[index].tolerated_failures;
5659 bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5661 struct extent_map *em;
5662 struct map_lookup *map;
5667 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5671 map = em->map_lookup;
5672 for (i = 0; i < map->num_stripes; i++) {
5673 if (test_bit(BTRFS_DEV_STATE_MISSING,
5674 &map->stripes[i].dev->dev_state)) {
5678 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5679 &map->stripes[i].dev->dev_state)) {
5686 * If the number of missing devices is larger than max errors, we can
5687 * not write the data into that chunk successfully.
5689 if (miss_ndevs > btrfs_chunk_max_errors(map))
5692 free_extent_map(em);
5696 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5698 struct extent_map *em;
5701 write_lock(&tree->lock);
5702 em = lookup_extent_mapping(tree, 0, (u64)-1);
5704 remove_extent_mapping(tree, em);
5705 write_unlock(&tree->lock);
5709 free_extent_map(em);
5710 /* once for the tree */
5711 free_extent_map(em);
5715 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5717 struct extent_map *em;
5718 struct map_lookup *map;
5719 enum btrfs_raid_types index;
5722 em = btrfs_get_chunk_map(fs_info, logical, len);
5725 * We could return errors for these cases, but that could get
5726 * ugly and we'd probably do the same thing which is just not do
5727 * anything else and exit, so return 1 so the callers don't try
5728 * to use other copies.
5732 map = em->map_lookup;
5733 index = btrfs_bg_flags_to_raid_index(map->type);
5735 /* Non-RAID56, use their ncopies from btrfs_raid_array. */
5736 if (!(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5737 ret = btrfs_raid_array[index].ncopies;
5738 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5740 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5742 * There could be two corrupted data stripes, we need
5743 * to loop retry in order to rebuild the correct data.
5745 * Fail a stripe at a time on every retry except the
5746 * stripe under reconstruction.
5748 ret = map->num_stripes;
5749 free_extent_map(em);
5753 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5756 struct extent_map *em;
5757 struct map_lookup *map;
5758 unsigned long len = fs_info->sectorsize;
5760 if (!btrfs_fs_incompat(fs_info, RAID56))
5763 em = btrfs_get_chunk_map(fs_info, logical, len);
5765 if (!WARN_ON(IS_ERR(em))) {
5766 map = em->map_lookup;
5767 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5768 len = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
5769 free_extent_map(em);
5774 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5776 struct extent_map *em;
5777 struct map_lookup *map;
5780 if (!btrfs_fs_incompat(fs_info, RAID56))
5783 em = btrfs_get_chunk_map(fs_info, logical, len);
5785 if(!WARN_ON(IS_ERR(em))) {
5786 map = em->map_lookup;
5787 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5789 free_extent_map(em);
5794 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5795 struct map_lookup *map, int first,
5796 int dev_replace_is_ongoing)
5800 int preferred_mirror;
5802 struct btrfs_device *srcdev;
5805 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5807 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5808 num_stripes = map->sub_stripes;
5810 num_stripes = map->num_stripes;
5812 switch (fs_info->fs_devices->read_policy) {
5814 /* Shouldn't happen, just warn and use pid instead of failing */
5815 btrfs_warn_rl(fs_info,
5816 "unknown read_policy type %u, reset to pid",
5817 fs_info->fs_devices->read_policy);
5818 fs_info->fs_devices->read_policy = BTRFS_READ_POLICY_PID;
5820 case BTRFS_READ_POLICY_PID:
5821 preferred_mirror = first + (current->pid % num_stripes);
5825 if (dev_replace_is_ongoing &&
5826 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5827 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5828 srcdev = fs_info->dev_replace.srcdev;
5833 * try to avoid the drive that is the source drive for a
5834 * dev-replace procedure, only choose it if no other non-missing
5835 * mirror is available
5837 for (tolerance = 0; tolerance < 2; tolerance++) {
5838 if (map->stripes[preferred_mirror].dev->bdev &&
5839 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5840 return preferred_mirror;
5841 for (i = first; i < first + num_stripes; i++) {
5842 if (map->stripes[i].dev->bdev &&
5843 (tolerance || map->stripes[i].dev != srcdev))
5848 /* we couldn't find one that doesn't fail. Just return something
5849 * and the io error handling code will clean up eventually
5851 return preferred_mirror;
5854 static struct btrfs_io_context *alloc_btrfs_io_context(struct btrfs_fs_info *fs_info,
5858 struct btrfs_io_context *bioc;
5861 /* The size of btrfs_io_context */
5862 sizeof(struct btrfs_io_context) +
5863 /* Plus the variable array for the stripes */
5864 sizeof(struct btrfs_io_stripe) * (total_stripes),
5870 refcount_set(&bioc->refs, 1);
5872 bioc->fs_info = fs_info;
5873 bioc->replace_stripe_src = -1;
5874 bioc->full_stripe_logical = (u64)-1;
5875 bioc->logical = logical;
5880 void btrfs_get_bioc(struct btrfs_io_context *bioc)
5882 WARN_ON(!refcount_read(&bioc->refs));
5883 refcount_inc(&bioc->refs);
5886 void btrfs_put_bioc(struct btrfs_io_context *bioc)
5890 if (refcount_dec_and_test(&bioc->refs))
5895 * Please note that, discard won't be sent to target device of device
5898 struct btrfs_discard_stripe *btrfs_map_discard(struct btrfs_fs_info *fs_info,
5899 u64 logical, u64 *length_ret,
5902 struct extent_map *em;
5903 struct map_lookup *map;
5904 struct btrfs_discard_stripe *stripes;
5905 u64 length = *length_ret;
5910 u64 stripe_end_offset;
5914 u32 sub_stripes = 0;
5915 u32 stripes_per_dev = 0;
5916 u32 remaining_stripes = 0;
5917 u32 last_stripe = 0;
5921 em = btrfs_get_chunk_map(fs_info, logical, length);
5923 return ERR_CAST(em);
5925 map = em->map_lookup;
5927 /* we don't discard raid56 yet */
5928 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5933 offset = logical - em->start;
5934 length = min_t(u64, em->start + em->len - logical, length);
5935 *length_ret = length;
5938 * stripe_nr counts the total number of stripes we have to stride
5939 * to get to this block
5941 stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
5943 /* stripe_offset is the offset of this block in its stripe */
5944 stripe_offset = offset - btrfs_stripe_nr_to_offset(stripe_nr);
5946 stripe_nr_end = round_up(offset + length, BTRFS_STRIPE_LEN) >>
5947 BTRFS_STRIPE_LEN_SHIFT;
5948 stripe_cnt = stripe_nr_end - stripe_nr;
5949 stripe_end_offset = btrfs_stripe_nr_to_offset(stripe_nr_end) -
5952 * after this, stripe_nr is the number of stripes on this
5953 * device we have to walk to find the data, and stripe_index is
5954 * the number of our device in the stripe array
5958 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5959 BTRFS_BLOCK_GROUP_RAID10)) {
5960 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5963 sub_stripes = map->sub_stripes;
5965 factor = map->num_stripes / sub_stripes;
5966 *num_stripes = min_t(u64, map->num_stripes,
5967 sub_stripes * stripe_cnt);
5968 stripe_index = stripe_nr % factor;
5969 stripe_nr /= factor;
5970 stripe_index *= sub_stripes;
5972 remaining_stripes = stripe_cnt % factor;
5973 stripes_per_dev = stripe_cnt / factor;
5974 last_stripe = ((stripe_nr_end - 1) % factor) * sub_stripes;
5975 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5976 BTRFS_BLOCK_GROUP_DUP)) {
5977 *num_stripes = map->num_stripes;
5979 stripe_index = stripe_nr % map->num_stripes;
5980 stripe_nr /= map->num_stripes;
5983 stripes = kcalloc(*num_stripes, sizeof(*stripes), GFP_NOFS);
5989 for (i = 0; i < *num_stripes; i++) {
5990 stripes[i].physical =
5991 map->stripes[stripe_index].physical +
5992 stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr);
5993 stripes[i].dev = map->stripes[stripe_index].dev;
5995 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5996 BTRFS_BLOCK_GROUP_RAID10)) {
5997 stripes[i].length = btrfs_stripe_nr_to_offset(stripes_per_dev);
5999 if (i / sub_stripes < remaining_stripes)
6000 stripes[i].length += BTRFS_STRIPE_LEN;
6003 * Special for the first stripe and
6006 * |-------|...|-------|
6010 if (i < sub_stripes)
6011 stripes[i].length -= stripe_offset;
6013 if (stripe_index >= last_stripe &&
6014 stripe_index <= (last_stripe +
6016 stripes[i].length -= stripe_end_offset;
6018 if (i == sub_stripes - 1)
6021 stripes[i].length = length;
6025 if (stripe_index == map->num_stripes) {
6031 free_extent_map(em);
6034 free_extent_map(em);
6035 return ERR_PTR(ret);
6038 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6040 struct btrfs_block_group *cache;
6043 /* Non zoned filesystem does not use "to_copy" flag */
6044 if (!btrfs_is_zoned(fs_info))
6047 cache = btrfs_lookup_block_group(fs_info, logical);
6049 ret = test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
6051 btrfs_put_block_group(cache);
6055 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
6056 struct btrfs_io_context *bioc,
6057 struct btrfs_dev_replace *dev_replace,
6059 int *num_stripes_ret, int *max_errors_ret)
6061 u64 srcdev_devid = dev_replace->srcdev->devid;
6063 * At this stage, num_stripes is still the real number of stripes,
6064 * excluding the duplicated stripes.
6066 int num_stripes = *num_stripes_ret;
6067 int nr_extra_stripes = 0;
6068 int max_errors = *max_errors_ret;
6072 * A block group which has "to_copy" set will eventually be copied by
6073 * the dev-replace process. We can avoid cloning IO here.
6075 if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6079 * Duplicate the write operations while the dev-replace procedure is
6080 * running. Since the copying of the old disk to the new disk takes
6081 * place at run time while the filesystem is mounted writable, the
6082 * regular write operations to the old disk have to be duplicated to go
6083 * to the new disk as well.
6085 * Note that device->missing is handled by the caller, and that the
6086 * write to the old disk is already set up in the stripes array.
6088 for (i = 0; i < num_stripes; i++) {
6089 struct btrfs_io_stripe *old = &bioc->stripes[i];
6090 struct btrfs_io_stripe *new = &bioc->stripes[num_stripes + nr_extra_stripes];
6092 if (old->dev->devid != srcdev_devid)
6095 new->physical = old->physical;
6096 new->dev = dev_replace->tgtdev;
6097 if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK)
6098 bioc->replace_stripe_src = i;
6102 /* We can only have at most 2 extra nr_stripes (for DUP). */
6103 ASSERT(nr_extra_stripes <= 2);
6105 * For GET_READ_MIRRORS, we can only return at most 1 extra stripe for
6107 * If we have 2 extra stripes, only choose the one with smaller physical.
6109 if (op == BTRFS_MAP_GET_READ_MIRRORS && nr_extra_stripes == 2) {
6110 struct btrfs_io_stripe *first = &bioc->stripes[num_stripes];
6111 struct btrfs_io_stripe *second = &bioc->stripes[num_stripes + 1];
6113 /* Only DUP can have two extra stripes. */
6114 ASSERT(bioc->map_type & BTRFS_BLOCK_GROUP_DUP);
6117 * Swap the last stripe stripes and reduce @nr_extra_stripes.
6118 * The extra stripe would still be there, but won't be accessed.
6120 if (first->physical > second->physical) {
6121 swap(second->physical, first->physical);
6122 swap(second->dev, first->dev);
6127 *num_stripes_ret = num_stripes + nr_extra_stripes;
6128 *max_errors_ret = max_errors + nr_extra_stripes;
6129 bioc->replace_nr_stripes = nr_extra_stripes;
6132 static u64 btrfs_max_io_len(struct map_lookup *map, enum btrfs_map_op op,
6133 u64 offset, u32 *stripe_nr, u64 *stripe_offset,
6134 u64 *full_stripe_start)
6137 * Stripe_nr is the stripe where this block falls. stripe_offset is
6138 * the offset of this block in its stripe.
6140 *stripe_offset = offset & BTRFS_STRIPE_LEN_MASK;
6141 *stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6142 ASSERT(*stripe_offset < U32_MAX);
6144 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6145 unsigned long full_stripe_len =
6146 btrfs_stripe_nr_to_offset(nr_data_stripes(map));
6149 * For full stripe start, we use previously calculated
6150 * @stripe_nr. Align it to nr_data_stripes, then multiply with
6153 * By this we can avoid u64 division completely. And we have
6154 * to go rounddown(), not round_down(), as nr_data_stripes is
6155 * not ensured to be power of 2.
6157 *full_stripe_start =
6158 btrfs_stripe_nr_to_offset(
6159 rounddown(*stripe_nr, nr_data_stripes(map)));
6161 ASSERT(*full_stripe_start + full_stripe_len > offset);
6162 ASSERT(*full_stripe_start <= offset);
6164 * For writes to RAID56, allow to write a full stripe set, but
6165 * no straddling of stripe sets.
6167 if (op == BTRFS_MAP_WRITE)
6168 return full_stripe_len - (offset - *full_stripe_start);
6172 * For other RAID types and for RAID56 reads, allow a single stripe (on
6175 if (map->type & BTRFS_BLOCK_GROUP_STRIPE_MASK)
6176 return BTRFS_STRIPE_LEN - *stripe_offset;
6180 static int set_io_stripe(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6181 u64 logical, u64 *length, struct btrfs_io_stripe *dst,
6182 struct map_lookup *map, u32 stripe_index,
6183 u64 stripe_offset, u64 stripe_nr)
6185 dst->dev = map->stripes[stripe_index].dev;
6187 if (op == BTRFS_MAP_READ && btrfs_need_stripe_tree_update(fs_info, map->type))
6188 return btrfs_get_raid_extent_offset(fs_info, logical, length,
6189 map->type, stripe_index, dst);
6191 dst->physical = map->stripes[stripe_index].physical +
6192 stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr);
6197 * Map one logical range to one or more physical ranges.
6199 * @length: (Mandatory) mapped length of this run.
6200 * One logical range can be split into different segments
6201 * due to factors like zones and RAID0/5/6/10 stripe
6204 * @bioc_ret: (Mandatory) returned btrfs_io_context structure.
6205 * which has one or more physical ranges (btrfs_io_stripe)
6207 * Caller should call btrfs_put_bioc() to free it after use.
6209 * @smap: (Optional) single physical range optimization.
6210 * If the map request can be fulfilled by one single
6211 * physical range, and this is parameter is not NULL,
6212 * then @bioc_ret would be NULL, and @smap would be
6215 * @mirror_num_ret: (Mandatory) returned mirror number if the original
6218 * Mirror number 0 means to choose any live mirrors.
6220 * For non-RAID56 profiles, non-zero mirror_num means
6221 * the Nth mirror. (e.g. mirror_num 1 means the first
6224 * For RAID56 profile, mirror 1 means rebuild from P and
6225 * the remaining data stripes.
6227 * For RAID6 profile, mirror > 2 means mark another
6228 * data/P stripe error and rebuild from the remaining
6231 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6232 u64 logical, u64 *length,
6233 struct btrfs_io_context **bioc_ret,
6234 struct btrfs_io_stripe *smap, int *mirror_num_ret)
6236 struct extent_map *em;
6237 struct map_lookup *map;
6245 int mirror_num = (mirror_num_ret ? *mirror_num_ret : 0);
6249 struct btrfs_io_context *bioc = NULL;
6250 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6251 int dev_replace_is_ongoing = 0;
6252 u16 num_alloc_stripes;
6253 u64 raid56_full_stripe_start = (u64)-1;
6258 num_copies = btrfs_num_copies(fs_info, logical, fs_info->sectorsize);
6259 if (mirror_num > num_copies)
6262 em = btrfs_get_chunk_map(fs_info, logical, *length);
6266 map = em->map_lookup;
6267 data_stripes = nr_data_stripes(map);
6269 map_offset = logical - em->start;
6270 max_len = btrfs_max_io_len(map, op, map_offset, &stripe_nr,
6271 &stripe_offset, &raid56_full_stripe_start);
6272 *length = min_t(u64, em->len - map_offset, max_len);
6274 down_read(&dev_replace->rwsem);
6275 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6277 * Hold the semaphore for read during the whole operation, write is
6278 * requested at commit time but must wait.
6280 if (!dev_replace_is_ongoing)
6281 up_read(&dev_replace->rwsem);
6285 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6286 stripe_index = stripe_nr % map->num_stripes;
6287 stripe_nr /= map->num_stripes;
6288 if (op == BTRFS_MAP_READ)
6290 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6291 if (op != BTRFS_MAP_READ) {
6292 num_stripes = map->num_stripes;
6293 } else if (mirror_num) {
6294 stripe_index = mirror_num - 1;
6296 stripe_index = find_live_mirror(fs_info, map, 0,
6297 dev_replace_is_ongoing);
6298 mirror_num = stripe_index + 1;
6301 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6302 if (op != BTRFS_MAP_READ) {
6303 num_stripes = map->num_stripes;
6304 } else if (mirror_num) {
6305 stripe_index = mirror_num - 1;
6310 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6311 u32 factor = map->num_stripes / map->sub_stripes;
6313 stripe_index = (stripe_nr % factor) * map->sub_stripes;
6314 stripe_nr /= factor;
6316 if (op != BTRFS_MAP_READ)
6317 num_stripes = map->sub_stripes;
6318 else if (mirror_num)
6319 stripe_index += mirror_num - 1;
6321 int old_stripe_index = stripe_index;
6322 stripe_index = find_live_mirror(fs_info, map,
6324 dev_replace_is_ongoing);
6325 mirror_num = stripe_index - old_stripe_index + 1;
6328 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6329 if (op != BTRFS_MAP_READ || mirror_num > 1) {
6331 * Needs full stripe mapping.
6333 * Push stripe_nr back to the start of the full stripe
6334 * For those cases needing a full stripe, @stripe_nr
6335 * is the full stripe number.
6337 * Originally we go raid56_full_stripe_start / full_stripe_len,
6338 * but that can be expensive. Here we just divide
6339 * @stripe_nr with @data_stripes.
6341 stripe_nr /= data_stripes;
6343 /* RAID[56] write or recovery. Return all stripes */
6344 num_stripes = map->num_stripes;
6345 max_errors = btrfs_chunk_max_errors(map);
6347 /* Return the length to the full stripe end */
6348 *length = min(logical + *length,
6349 raid56_full_stripe_start + em->start +
6350 btrfs_stripe_nr_to_offset(data_stripes)) -
6355 ASSERT(mirror_num <= 1);
6356 /* Just grab the data stripe directly. */
6357 stripe_index = stripe_nr % data_stripes;
6358 stripe_nr /= data_stripes;
6360 /* We distribute the parity blocks across stripes */
6361 stripe_index = (stripe_nr + stripe_index) % map->num_stripes;
6362 if (op == BTRFS_MAP_READ && mirror_num < 1)
6367 * After this, stripe_nr is the number of stripes on this
6368 * device we have to walk to find the data, and stripe_index is
6369 * the number of our device in the stripe array
6371 stripe_index = stripe_nr % map->num_stripes;
6372 stripe_nr /= map->num_stripes;
6373 mirror_num = stripe_index + 1;
6375 if (stripe_index >= map->num_stripes) {
6377 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6378 stripe_index, map->num_stripes);
6383 num_alloc_stripes = num_stripes;
6384 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6385 op != BTRFS_MAP_READ)
6387 * For replace case, we need to add extra stripes for extra
6388 * duplicated stripes.
6390 * For both WRITE and GET_READ_MIRRORS, we may have at most
6391 * 2 more stripes (DUP types, otherwise 1).
6393 num_alloc_stripes += 2;
6396 * If this I/O maps to a single device, try to return the device and
6397 * physical block information on the stack instead of allocating an
6398 * I/O context structure.
6400 if (smap && num_alloc_stripes == 1 &&
6401 !(btrfs_need_stripe_tree_update(fs_info, map->type) &&
6402 op != BTRFS_MAP_READ) &&
6403 !((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) && mirror_num > 1)) {
6404 ret = set_io_stripe(fs_info, op, logical, length, smap, map,
6405 stripe_index, stripe_offset, stripe_nr);
6407 *mirror_num_ret = mirror_num;
6412 bioc = alloc_btrfs_io_context(fs_info, logical, num_alloc_stripes);
6417 bioc->map_type = map->type;
6420 * For RAID56 full map, we need to make sure the stripes[] follows the
6421 * rule that data stripes are all ordered, then followed with P and Q
6424 * It's still mostly the same as other profiles, just with extra rotation.
6426 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
6427 (op != BTRFS_MAP_READ || mirror_num > 1)) {
6429 * For RAID56 @stripe_nr is already the number of full stripes
6430 * before us, which is also the rotation value (needs to modulo
6431 * with num_stripes).
6433 * In this case, we just add @stripe_nr with @i, then do the
6434 * modulo, to reduce one modulo call.
6436 bioc->full_stripe_logical = em->start +
6437 btrfs_stripe_nr_to_offset(stripe_nr * data_stripes);
6438 for (int i = 0; i < num_stripes; i++) {
6439 ret = set_io_stripe(fs_info, op, logical, length,
6440 &bioc->stripes[i], map,
6441 (i + stripe_nr) % num_stripes,
6442 stripe_offset, stripe_nr);
6448 * For all other non-RAID56 profiles, just copy the target
6449 * stripe into the bioc.
6451 for (i = 0; i < num_stripes; i++) {
6452 ret = set_io_stripe(fs_info, op, logical, length,
6453 &bioc->stripes[i], map, stripe_index,
6454 stripe_offset, stripe_nr);
6463 btrfs_put_bioc(bioc);
6467 if (op != BTRFS_MAP_READ)
6468 max_errors = btrfs_chunk_max_errors(map);
6470 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6471 op != BTRFS_MAP_READ) {
6472 handle_ops_on_dev_replace(op, bioc, dev_replace, logical,
6473 &num_stripes, &max_errors);
6477 bioc->num_stripes = num_stripes;
6478 bioc->max_errors = max_errors;
6479 bioc->mirror_num = mirror_num;
6482 if (dev_replace_is_ongoing) {
6483 lockdep_assert_held(&dev_replace->rwsem);
6484 /* Unlock and let waiting writers proceed */
6485 up_read(&dev_replace->rwsem);
6487 free_extent_map(em);
6491 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args *args,
6492 const struct btrfs_fs_devices *fs_devices)
6494 if (args->fsid == NULL)
6496 if (memcmp(fs_devices->metadata_uuid, args->fsid, BTRFS_FSID_SIZE) == 0)
6501 static bool dev_args_match_device(const struct btrfs_dev_lookup_args *args,
6502 const struct btrfs_device *device)
6504 if (args->missing) {
6505 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) &&
6511 if (device->devid != args->devid)
6513 if (args->uuid && memcmp(device->uuid, args->uuid, BTRFS_UUID_SIZE) != 0)
6519 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6522 * If devid and uuid are both specified, the match must be exact, otherwise
6523 * only devid is used.
6525 struct btrfs_device *btrfs_find_device(const struct btrfs_fs_devices *fs_devices,
6526 const struct btrfs_dev_lookup_args *args)
6528 struct btrfs_device *device;
6529 struct btrfs_fs_devices *seed_devs;
6531 if (dev_args_match_fs_devices(args, fs_devices)) {
6532 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6533 if (dev_args_match_device(args, device))
6538 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6539 if (!dev_args_match_fs_devices(args, seed_devs))
6541 list_for_each_entry(device, &seed_devs->devices, dev_list) {
6542 if (dev_args_match_device(args, device))
6550 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6551 u64 devid, u8 *dev_uuid)
6553 struct btrfs_device *device;
6554 unsigned int nofs_flag;
6557 * We call this under the chunk_mutex, so we want to use NOFS for this
6558 * allocation, however we don't want to change btrfs_alloc_device() to
6559 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6563 nofs_flag = memalloc_nofs_save();
6564 device = btrfs_alloc_device(NULL, &devid, dev_uuid, NULL);
6565 memalloc_nofs_restore(nofs_flag);
6569 list_add(&device->dev_list, &fs_devices->devices);
6570 device->fs_devices = fs_devices;
6571 fs_devices->num_devices++;
6573 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6574 fs_devices->missing_devices++;
6580 * Allocate new device struct, set up devid and UUID.
6582 * @fs_info: used only for generating a new devid, can be NULL if
6583 * devid is provided (i.e. @devid != NULL).
6584 * @devid: a pointer to devid for this device. If NULL a new devid
6586 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6588 * @path: a pointer to device path if available, NULL otherwise.
6590 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6591 * on error. Returned struct is not linked onto any lists and must be
6592 * destroyed with btrfs_free_device.
6594 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6595 const u64 *devid, const u8 *uuid,
6598 struct btrfs_device *dev;
6601 if (WARN_ON(!devid && !fs_info))
6602 return ERR_PTR(-EINVAL);
6604 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
6606 return ERR_PTR(-ENOMEM);
6608 INIT_LIST_HEAD(&dev->dev_list);
6609 INIT_LIST_HEAD(&dev->dev_alloc_list);
6610 INIT_LIST_HEAD(&dev->post_commit_list);
6612 atomic_set(&dev->dev_stats_ccnt, 0);
6613 btrfs_device_data_ordered_init(dev);
6614 extent_io_tree_init(fs_info, &dev->alloc_state, IO_TREE_DEVICE_ALLOC_STATE);
6621 ret = find_next_devid(fs_info, &tmp);
6623 btrfs_free_device(dev);
6624 return ERR_PTR(ret);
6630 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6632 generate_random_uuid(dev->uuid);
6635 struct rcu_string *name;
6637 name = rcu_string_strdup(path, GFP_KERNEL);
6639 btrfs_free_device(dev);
6640 return ERR_PTR(-ENOMEM);
6642 rcu_assign_pointer(dev->name, name);
6648 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6649 u64 devid, u8 *uuid, bool error)
6652 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6655 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6659 u64 btrfs_calc_stripe_length(const struct extent_map *em)
6661 const struct map_lookup *map = em->map_lookup;
6662 const int data_stripes = calc_data_stripes(map->type, map->num_stripes);
6664 return div_u64(em->len, data_stripes);
6667 #if BITS_PER_LONG == 32
6669 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
6670 * can't be accessed on 32bit systems.
6672 * This function do mount time check to reject the fs if it already has
6673 * metadata chunk beyond that limit.
6675 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6676 u64 logical, u64 length, u64 type)
6678 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6681 if (logical + length < MAX_LFS_FILESIZE)
6684 btrfs_err_32bit_limit(fs_info);
6689 * This is to give early warning for any metadata chunk reaching
6690 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
6691 * Although we can still access the metadata, it's not going to be possible
6692 * once the limit is reached.
6694 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6695 u64 logical, u64 length, u64 type)
6697 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6700 if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6703 btrfs_warn_32bit_limit(fs_info);
6707 static struct btrfs_device *handle_missing_device(struct btrfs_fs_info *fs_info,
6708 u64 devid, u8 *uuid)
6710 struct btrfs_device *dev;
6712 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6713 btrfs_report_missing_device(fs_info, devid, uuid, true);
6714 return ERR_PTR(-ENOENT);
6717 dev = add_missing_dev(fs_info->fs_devices, devid, uuid);
6719 btrfs_err(fs_info, "failed to init missing device %llu: %ld",
6720 devid, PTR_ERR(dev));
6723 btrfs_report_missing_device(fs_info, devid, uuid, false);
6728 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6729 struct btrfs_chunk *chunk)
6731 BTRFS_DEV_LOOKUP_ARGS(args);
6732 struct btrfs_fs_info *fs_info = leaf->fs_info;
6733 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6734 struct map_lookup *map;
6735 struct extent_map *em;
6740 u8 uuid[BTRFS_UUID_SIZE];
6746 logical = key->offset;
6747 length = btrfs_chunk_length(leaf, chunk);
6748 type = btrfs_chunk_type(leaf, chunk);
6749 index = btrfs_bg_flags_to_raid_index(type);
6750 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6752 #if BITS_PER_LONG == 32
6753 ret = check_32bit_meta_chunk(fs_info, logical, length, type);
6756 warn_32bit_meta_chunk(fs_info, logical, length, type);
6760 * Only need to verify chunk item if we're reading from sys chunk array,
6761 * as chunk item in tree block is already verified by tree-checker.
6763 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6764 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6769 read_lock(&map_tree->lock);
6770 em = lookup_extent_mapping(map_tree, logical, 1);
6771 read_unlock(&map_tree->lock);
6773 /* already mapped? */
6774 if (em && em->start <= logical && em->start + em->len > logical) {
6775 free_extent_map(em);
6778 free_extent_map(em);
6781 em = alloc_extent_map();
6784 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6786 free_extent_map(em);
6790 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6791 em->map_lookup = map;
6792 em->start = logical;
6795 em->block_start = 0;
6796 em->block_len = em->len;
6798 map->num_stripes = num_stripes;
6799 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6800 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6803 * We can't use the sub_stripes value, as for profiles other than
6804 * RAID10, they may have 0 as sub_stripes for filesystems created by
6805 * older mkfs (<v5.4).
6806 * In that case, it can cause divide-by-zero errors later.
6807 * Since currently sub_stripes is fixed for each profile, let's
6808 * use the trusted value instead.
6810 map->sub_stripes = btrfs_raid_array[index].sub_stripes;
6811 map->verified_stripes = 0;
6812 em->orig_block_len = btrfs_calc_stripe_length(em);
6813 for (i = 0; i < num_stripes; i++) {
6814 map->stripes[i].physical =
6815 btrfs_stripe_offset_nr(leaf, chunk, i);
6816 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6818 read_extent_buffer(leaf, uuid, (unsigned long)
6819 btrfs_stripe_dev_uuid_nr(chunk, i),
6822 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, &args);
6823 if (!map->stripes[i].dev) {
6824 map->stripes[i].dev = handle_missing_device(fs_info,
6826 if (IS_ERR(map->stripes[i].dev)) {
6827 ret = PTR_ERR(map->stripes[i].dev);
6828 free_extent_map(em);
6833 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6834 &(map->stripes[i].dev->dev_state));
6837 write_lock(&map_tree->lock);
6838 ret = add_extent_mapping(map_tree, em, 0);
6839 write_unlock(&map_tree->lock);
6842 "failed to add chunk map, start=%llu len=%llu: %d",
6843 em->start, em->len, ret);
6845 free_extent_map(em);
6850 static void fill_device_from_item(struct extent_buffer *leaf,
6851 struct btrfs_dev_item *dev_item,
6852 struct btrfs_device *device)
6856 device->devid = btrfs_device_id(leaf, dev_item);
6857 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6858 device->total_bytes = device->disk_total_bytes;
6859 device->commit_total_bytes = device->disk_total_bytes;
6860 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6861 device->commit_bytes_used = device->bytes_used;
6862 device->type = btrfs_device_type(leaf, dev_item);
6863 device->io_align = btrfs_device_io_align(leaf, dev_item);
6864 device->io_width = btrfs_device_io_width(leaf, dev_item);
6865 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6866 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6867 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6869 ptr = btrfs_device_uuid(dev_item);
6870 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6873 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6876 struct btrfs_fs_devices *fs_devices;
6879 lockdep_assert_held(&uuid_mutex);
6882 /* This will match only for multi-device seed fs */
6883 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
6884 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6888 fs_devices = find_fsid(fsid, NULL);
6890 if (!btrfs_test_opt(fs_info, DEGRADED))
6891 return ERR_PTR(-ENOENT);
6893 fs_devices = alloc_fs_devices(fsid);
6894 if (IS_ERR(fs_devices))
6897 fs_devices->seeding = true;
6898 fs_devices->opened = 1;
6903 * Upon first call for a seed fs fsid, just create a private copy of the
6904 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
6906 fs_devices = clone_fs_devices(fs_devices);
6907 if (IS_ERR(fs_devices))
6910 ret = open_fs_devices(fs_devices, BLK_OPEN_READ, fs_info->bdev_holder);
6912 free_fs_devices(fs_devices);
6913 return ERR_PTR(ret);
6916 if (!fs_devices->seeding) {
6917 close_fs_devices(fs_devices);
6918 free_fs_devices(fs_devices);
6919 return ERR_PTR(-EINVAL);
6922 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
6927 static int read_one_dev(struct extent_buffer *leaf,
6928 struct btrfs_dev_item *dev_item)
6930 BTRFS_DEV_LOOKUP_ARGS(args);
6931 struct btrfs_fs_info *fs_info = leaf->fs_info;
6932 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6933 struct btrfs_device *device;
6936 u8 fs_uuid[BTRFS_FSID_SIZE];
6937 u8 dev_uuid[BTRFS_UUID_SIZE];
6939 devid = btrfs_device_id(leaf, dev_item);
6941 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6943 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6945 args.uuid = dev_uuid;
6946 args.fsid = fs_uuid;
6948 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6949 fs_devices = open_seed_devices(fs_info, fs_uuid);
6950 if (IS_ERR(fs_devices))
6951 return PTR_ERR(fs_devices);
6954 device = btrfs_find_device(fs_info->fs_devices, &args);
6956 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6957 btrfs_report_missing_device(fs_info, devid,
6962 device = add_missing_dev(fs_devices, devid, dev_uuid);
6963 if (IS_ERR(device)) {
6965 "failed to add missing dev %llu: %ld",
6966 devid, PTR_ERR(device));
6967 return PTR_ERR(device);
6969 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6971 if (!device->bdev) {
6972 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6973 btrfs_report_missing_device(fs_info,
6974 devid, dev_uuid, true);
6977 btrfs_report_missing_device(fs_info, devid,
6981 if (!device->bdev &&
6982 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6984 * this happens when a device that was properly setup
6985 * in the device info lists suddenly goes bad.
6986 * device->bdev is NULL, and so we have to set
6987 * device->missing to one here
6989 device->fs_devices->missing_devices++;
6990 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6993 /* Move the device to its own fs_devices */
6994 if (device->fs_devices != fs_devices) {
6995 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6996 &device->dev_state));
6998 list_move(&device->dev_list, &fs_devices->devices);
6999 device->fs_devices->num_devices--;
7000 fs_devices->num_devices++;
7002 device->fs_devices->missing_devices--;
7003 fs_devices->missing_devices++;
7005 device->fs_devices = fs_devices;
7009 if (device->fs_devices != fs_info->fs_devices) {
7010 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7011 if (device->generation !=
7012 btrfs_device_generation(leaf, dev_item))
7016 fill_device_from_item(leaf, dev_item, device);
7018 u64 max_total_bytes = bdev_nr_bytes(device->bdev);
7020 if (device->total_bytes > max_total_bytes) {
7022 "device total_bytes should be at most %llu but found %llu",
7023 max_total_bytes, device->total_bytes);
7027 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7028 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7029 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7030 device->fs_devices->total_rw_bytes += device->total_bytes;
7031 atomic64_add(device->total_bytes - device->bytes_used,
7032 &fs_info->free_chunk_space);
7038 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7040 struct btrfs_super_block *super_copy = fs_info->super_copy;
7041 struct extent_buffer *sb;
7042 struct btrfs_disk_key *disk_key;
7043 struct btrfs_chunk *chunk;
7045 unsigned long sb_array_offset;
7052 struct btrfs_key key;
7054 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7057 * We allocated a dummy extent, just to use extent buffer accessors.
7058 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
7059 * that's fine, we will not go beyond system chunk array anyway.
7061 sb = alloc_dummy_extent_buffer(fs_info, BTRFS_SUPER_INFO_OFFSET);
7064 set_extent_buffer_uptodate(sb);
7066 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7067 array_size = btrfs_super_sys_array_size(super_copy);
7069 array_ptr = super_copy->sys_chunk_array;
7070 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7073 while (cur_offset < array_size) {
7074 disk_key = (struct btrfs_disk_key *)array_ptr;
7075 len = sizeof(*disk_key);
7076 if (cur_offset + len > array_size)
7077 goto out_short_read;
7079 btrfs_disk_key_to_cpu(&key, disk_key);
7082 sb_array_offset += len;
7085 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
7087 "unexpected item type %u in sys_array at offset %u",
7088 (u32)key.type, cur_offset);
7093 chunk = (struct btrfs_chunk *)sb_array_offset;
7095 * At least one btrfs_chunk with one stripe must be present,
7096 * exact stripe count check comes afterwards
7098 len = btrfs_chunk_item_size(1);
7099 if (cur_offset + len > array_size)
7100 goto out_short_read;
7102 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7105 "invalid number of stripes %u in sys_array at offset %u",
7106 num_stripes, cur_offset);
7111 type = btrfs_chunk_type(sb, chunk);
7112 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7114 "invalid chunk type %llu in sys_array at offset %u",
7120 len = btrfs_chunk_item_size(num_stripes);
7121 if (cur_offset + len > array_size)
7122 goto out_short_read;
7124 ret = read_one_chunk(&key, sb, chunk);
7129 sb_array_offset += len;
7132 clear_extent_buffer_uptodate(sb);
7133 free_extent_buffer_stale(sb);
7137 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7139 clear_extent_buffer_uptodate(sb);
7140 free_extent_buffer_stale(sb);
7145 * Check if all chunks in the fs are OK for read-write degraded mount
7147 * If the @failing_dev is specified, it's accounted as missing.
7149 * Return true if all chunks meet the minimal RW mount requirements.
7150 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7152 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7153 struct btrfs_device *failing_dev)
7155 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7156 struct extent_map *em;
7160 read_lock(&map_tree->lock);
7161 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7162 read_unlock(&map_tree->lock);
7163 /* No chunk at all? Return false anyway */
7169 struct map_lookup *map;
7174 map = em->map_lookup;
7176 btrfs_get_num_tolerated_disk_barrier_failures(
7178 for (i = 0; i < map->num_stripes; i++) {
7179 struct btrfs_device *dev = map->stripes[i].dev;
7181 if (!dev || !dev->bdev ||
7182 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7183 dev->last_flush_error)
7185 else if (failing_dev && failing_dev == dev)
7188 if (missing > max_tolerated) {
7191 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7192 em->start, missing, max_tolerated);
7193 free_extent_map(em);
7197 next_start = extent_map_end(em);
7198 free_extent_map(em);
7200 read_lock(&map_tree->lock);
7201 em = lookup_extent_mapping(map_tree, next_start,
7202 (u64)(-1) - next_start);
7203 read_unlock(&map_tree->lock);
7209 static void readahead_tree_node_children(struct extent_buffer *node)
7212 const int nr_items = btrfs_header_nritems(node);
7214 for (i = 0; i < nr_items; i++)
7215 btrfs_readahead_node_child(node, i);
7218 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7220 struct btrfs_root *root = fs_info->chunk_root;
7221 struct btrfs_path *path;
7222 struct extent_buffer *leaf;
7223 struct btrfs_key key;
7224 struct btrfs_key found_key;
7229 u64 last_ra_node = 0;
7231 path = btrfs_alloc_path();
7236 * uuid_mutex is needed only if we are mounting a sprout FS
7237 * otherwise we don't need it.
7239 mutex_lock(&uuid_mutex);
7242 * It is possible for mount and umount to race in such a way that
7243 * we execute this code path, but open_fs_devices failed to clear
7244 * total_rw_bytes. We certainly want it cleared before reading the
7245 * device items, so clear it here.
7247 fs_info->fs_devices->total_rw_bytes = 0;
7250 * Lockdep complains about possible circular locking dependency between
7251 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7252 * used for freeze procection of a fs (struct super_block.s_writers),
7253 * which we take when starting a transaction, and extent buffers of the
7254 * chunk tree if we call read_one_dev() while holding a lock on an
7255 * extent buffer of the chunk tree. Since we are mounting the filesystem
7256 * and at this point there can't be any concurrent task modifying the
7257 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7259 ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
7260 path->skip_locking = 1;
7263 * Read all device items, and then all the chunk items. All
7264 * device items are found before any chunk item (their object id
7265 * is smaller than the lowest possible object id for a chunk
7266 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7268 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7271 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
7272 struct extent_buffer *node = path->nodes[1];
7274 leaf = path->nodes[0];
7275 slot = path->slots[0];
7278 if (last_ra_node != node->start) {
7279 readahead_tree_node_children(node);
7280 last_ra_node = node->start;
7283 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7284 struct btrfs_dev_item *dev_item;
7285 dev_item = btrfs_item_ptr(leaf, slot,
7286 struct btrfs_dev_item);
7287 ret = read_one_dev(leaf, dev_item);
7291 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7292 struct btrfs_chunk *chunk;
7295 * We are only called at mount time, so no need to take
7296 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7297 * we always lock first fs_info->chunk_mutex before
7298 * acquiring any locks on the chunk tree. This is a
7299 * requirement for chunk allocation, see the comment on
7300 * top of btrfs_chunk_alloc() for details.
7302 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7303 ret = read_one_chunk(&found_key, leaf, chunk);
7308 /* Catch error found during iteration */
7315 * After loading chunk tree, we've got all device information,
7316 * do another round of validation checks.
7318 if (total_dev != fs_info->fs_devices->total_devices) {
7320 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7321 btrfs_super_num_devices(fs_info->super_copy),
7323 fs_info->fs_devices->total_devices = total_dev;
7324 btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
7326 if (btrfs_super_total_bytes(fs_info->super_copy) <
7327 fs_info->fs_devices->total_rw_bytes) {
7329 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7330 btrfs_super_total_bytes(fs_info->super_copy),
7331 fs_info->fs_devices->total_rw_bytes);
7337 mutex_unlock(&uuid_mutex);
7339 btrfs_free_path(path);
7343 int btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7345 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7346 struct btrfs_device *device;
7349 fs_devices->fs_info = fs_info;
7351 mutex_lock(&fs_devices->device_list_mutex);
7352 list_for_each_entry(device, &fs_devices->devices, dev_list)
7353 device->fs_info = fs_info;
7355 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7356 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7357 device->fs_info = fs_info;
7358 ret = btrfs_get_dev_zone_info(device, false);
7363 seed_devs->fs_info = fs_info;
7365 mutex_unlock(&fs_devices->device_list_mutex);
7370 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7371 const struct btrfs_dev_stats_item *ptr,
7376 read_extent_buffer(eb, &val,
7377 offsetof(struct btrfs_dev_stats_item, values) +
7378 ((unsigned long)ptr) + (index * sizeof(u64)),
7383 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7384 struct btrfs_dev_stats_item *ptr,
7387 write_extent_buffer(eb, &val,
7388 offsetof(struct btrfs_dev_stats_item, values) +
7389 ((unsigned long)ptr) + (index * sizeof(u64)),
7393 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7394 struct btrfs_path *path)
7396 struct btrfs_dev_stats_item *ptr;
7397 struct extent_buffer *eb;
7398 struct btrfs_key key;
7402 if (!device->fs_info->dev_root)
7405 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7406 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7407 key.offset = device->devid;
7408 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7410 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7411 btrfs_dev_stat_set(device, i, 0);
7412 device->dev_stats_valid = 1;
7413 btrfs_release_path(path);
7414 return ret < 0 ? ret : 0;
7416 slot = path->slots[0];
7417 eb = path->nodes[0];
7418 item_size = btrfs_item_size(eb, slot);
7420 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7422 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7423 if (item_size >= (1 + i) * sizeof(__le64))
7424 btrfs_dev_stat_set(device, i,
7425 btrfs_dev_stats_value(eb, ptr, i));
7427 btrfs_dev_stat_set(device, i, 0);
7430 device->dev_stats_valid = 1;
7431 btrfs_dev_stat_print_on_load(device);
7432 btrfs_release_path(path);
7437 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7439 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7440 struct btrfs_device *device;
7441 struct btrfs_path *path = NULL;
7444 path = btrfs_alloc_path();
7448 mutex_lock(&fs_devices->device_list_mutex);
7449 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7450 ret = btrfs_device_init_dev_stats(device, path);
7454 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7455 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7456 ret = btrfs_device_init_dev_stats(device, path);
7462 mutex_unlock(&fs_devices->device_list_mutex);
7464 btrfs_free_path(path);
7468 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7469 struct btrfs_device *device)
7471 struct btrfs_fs_info *fs_info = trans->fs_info;
7472 struct btrfs_root *dev_root = fs_info->dev_root;
7473 struct btrfs_path *path;
7474 struct btrfs_key key;
7475 struct extent_buffer *eb;
7476 struct btrfs_dev_stats_item *ptr;
7480 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7481 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7482 key.offset = device->devid;
7484 path = btrfs_alloc_path();
7487 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7489 btrfs_warn_in_rcu(fs_info,
7490 "error %d while searching for dev_stats item for device %s",
7491 ret, btrfs_dev_name(device));
7496 btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7497 /* need to delete old one and insert a new one */
7498 ret = btrfs_del_item(trans, dev_root, path);
7500 btrfs_warn_in_rcu(fs_info,
7501 "delete too small dev_stats item for device %s failed %d",
7502 btrfs_dev_name(device), ret);
7509 /* need to insert a new item */
7510 btrfs_release_path(path);
7511 ret = btrfs_insert_empty_item(trans, dev_root, path,
7512 &key, sizeof(*ptr));
7514 btrfs_warn_in_rcu(fs_info,
7515 "insert dev_stats item for device %s failed %d",
7516 btrfs_dev_name(device), ret);
7521 eb = path->nodes[0];
7522 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7523 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7524 btrfs_set_dev_stats_value(eb, ptr, i,
7525 btrfs_dev_stat_read(device, i));
7526 btrfs_mark_buffer_dirty(trans, eb);
7529 btrfs_free_path(path);
7534 * called from commit_transaction. Writes all changed device stats to disk.
7536 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7538 struct btrfs_fs_info *fs_info = trans->fs_info;
7539 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7540 struct btrfs_device *device;
7544 mutex_lock(&fs_devices->device_list_mutex);
7545 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7546 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7547 if (!device->dev_stats_valid || stats_cnt == 0)
7552 * There is a LOAD-LOAD control dependency between the value of
7553 * dev_stats_ccnt and updating the on-disk values which requires
7554 * reading the in-memory counters. Such control dependencies
7555 * require explicit read memory barriers.
7557 * This memory barriers pairs with smp_mb__before_atomic in
7558 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7559 * barrier implied by atomic_xchg in
7560 * btrfs_dev_stats_read_and_reset
7564 ret = update_dev_stat_item(trans, device);
7566 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7568 mutex_unlock(&fs_devices->device_list_mutex);
7573 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7575 btrfs_dev_stat_inc(dev, index);
7577 if (!dev->dev_stats_valid)
7579 btrfs_err_rl_in_rcu(dev->fs_info,
7580 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7581 btrfs_dev_name(dev),
7582 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7583 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7584 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7585 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7586 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7589 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7593 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7594 if (btrfs_dev_stat_read(dev, i) != 0)
7596 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7597 return; /* all values == 0, suppress message */
7599 btrfs_info_in_rcu(dev->fs_info,
7600 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7601 btrfs_dev_name(dev),
7602 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7603 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7604 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7605 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7606 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7609 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7610 struct btrfs_ioctl_get_dev_stats *stats)
7612 BTRFS_DEV_LOOKUP_ARGS(args);
7613 struct btrfs_device *dev;
7614 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7617 mutex_lock(&fs_devices->device_list_mutex);
7618 args.devid = stats->devid;
7619 dev = btrfs_find_device(fs_info->fs_devices, &args);
7620 mutex_unlock(&fs_devices->device_list_mutex);
7623 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7625 } else if (!dev->dev_stats_valid) {
7626 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7628 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7629 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7630 if (stats->nr_items > i)
7632 btrfs_dev_stat_read_and_reset(dev, i);
7634 btrfs_dev_stat_set(dev, i, 0);
7636 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7637 current->comm, task_pid_nr(current));
7639 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7640 if (stats->nr_items > i)
7641 stats->values[i] = btrfs_dev_stat_read(dev, i);
7643 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7644 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7649 * Update the size and bytes used for each device where it changed. This is
7650 * delayed since we would otherwise get errors while writing out the
7653 * Must be invoked during transaction commit.
7655 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7657 struct btrfs_device *curr, *next;
7659 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7661 if (list_empty(&trans->dev_update_list))
7665 * We don't need the device_list_mutex here. This list is owned by the
7666 * transaction and the transaction must complete before the device is
7669 mutex_lock(&trans->fs_info->chunk_mutex);
7670 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7672 list_del_init(&curr->post_commit_list);
7673 curr->commit_total_bytes = curr->disk_total_bytes;
7674 curr->commit_bytes_used = curr->bytes_used;
7676 mutex_unlock(&trans->fs_info->chunk_mutex);
7680 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7682 int btrfs_bg_type_to_factor(u64 flags)
7684 const int index = btrfs_bg_flags_to_raid_index(flags);
7686 return btrfs_raid_array[index].ncopies;
7691 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7692 u64 chunk_offset, u64 devid,
7693 u64 physical_offset, u64 physical_len)
7695 struct btrfs_dev_lookup_args args = { .devid = devid };
7696 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7697 struct extent_map *em;
7698 struct map_lookup *map;
7699 struct btrfs_device *dev;
7705 read_lock(&em_tree->lock);
7706 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7707 read_unlock(&em_tree->lock);
7711 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7712 physical_offset, devid);
7717 map = em->map_lookup;
7718 stripe_len = btrfs_calc_stripe_length(em);
7719 if (physical_len != stripe_len) {
7721 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7722 physical_offset, devid, em->start, physical_len,
7729 * Very old mkfs.btrfs (before v4.1) will not respect the reserved
7730 * space. Although kernel can handle it without problem, better to warn
7733 if (physical_offset < BTRFS_DEVICE_RANGE_RESERVED)
7735 "devid %llu physical %llu len %llu inside the reserved space",
7736 devid, physical_offset, physical_len);
7738 for (i = 0; i < map->num_stripes; i++) {
7739 if (map->stripes[i].dev->devid == devid &&
7740 map->stripes[i].physical == physical_offset) {
7742 if (map->verified_stripes >= map->num_stripes) {
7744 "too many dev extents for chunk %llu found",
7749 map->verified_stripes++;
7755 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7756 physical_offset, devid);
7760 /* Make sure no dev extent is beyond device boundary */
7761 dev = btrfs_find_device(fs_info->fs_devices, &args);
7763 btrfs_err(fs_info, "failed to find devid %llu", devid);
7768 if (physical_offset + physical_len > dev->disk_total_bytes) {
7770 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7771 devid, physical_offset, physical_len,
7772 dev->disk_total_bytes);
7777 if (dev->zone_info) {
7778 u64 zone_size = dev->zone_info->zone_size;
7780 if (!IS_ALIGNED(physical_offset, zone_size) ||
7781 !IS_ALIGNED(physical_len, zone_size)) {
7783 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
7784 devid, physical_offset, physical_len);
7791 free_extent_map(em);
7795 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7797 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7798 struct extent_map *em;
7799 struct rb_node *node;
7802 read_lock(&em_tree->lock);
7803 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7804 em = rb_entry(node, struct extent_map, rb_node);
7805 if (em->map_lookup->num_stripes !=
7806 em->map_lookup->verified_stripes) {
7808 "chunk %llu has missing dev extent, have %d expect %d",
7809 em->start, em->map_lookup->verified_stripes,
7810 em->map_lookup->num_stripes);
7816 read_unlock(&em_tree->lock);
7821 * Ensure that all dev extents are mapped to correct chunk, otherwise
7822 * later chunk allocation/free would cause unexpected behavior.
7824 * NOTE: This will iterate through the whole device tree, which should be of
7825 * the same size level as the chunk tree. This slightly increases mount time.
7827 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7829 struct btrfs_path *path;
7830 struct btrfs_root *root = fs_info->dev_root;
7831 struct btrfs_key key;
7833 u64 prev_dev_ext_end = 0;
7837 * We don't have a dev_root because we mounted with ignorebadroots and
7838 * failed to load the root, so we want to skip the verification in this
7841 * However if the dev root is fine, but the tree itself is corrupted
7842 * we'd still fail to mount. This verification is only to make sure
7843 * writes can happen safely, so instead just bypass this check
7844 * completely in the case of IGNOREBADROOTS.
7846 if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
7850 key.type = BTRFS_DEV_EXTENT_KEY;
7853 path = btrfs_alloc_path();
7857 path->reada = READA_FORWARD;
7858 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7862 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7863 ret = btrfs_next_leaf(root, path);
7866 /* No dev extents at all? Not good */
7873 struct extent_buffer *leaf = path->nodes[0];
7874 struct btrfs_dev_extent *dext;
7875 int slot = path->slots[0];
7877 u64 physical_offset;
7881 btrfs_item_key_to_cpu(leaf, &key, slot);
7882 if (key.type != BTRFS_DEV_EXTENT_KEY)
7884 devid = key.objectid;
7885 physical_offset = key.offset;
7887 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7888 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7889 physical_len = btrfs_dev_extent_length(leaf, dext);
7891 /* Check if this dev extent overlaps with the previous one */
7892 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7894 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7895 devid, physical_offset, prev_dev_ext_end);
7900 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7901 physical_offset, physical_len);
7905 prev_dev_ext_end = physical_offset + physical_len;
7907 ret = btrfs_next_item(root, path);
7916 /* Ensure all chunks have corresponding dev extents */
7917 ret = verify_chunk_dev_extent_mapping(fs_info);
7919 btrfs_free_path(path);
7924 * Check whether the given block group or device is pinned by any inode being
7925 * used as a swapfile.
7927 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7929 struct btrfs_swapfile_pin *sp;
7930 struct rb_node *node;
7932 spin_lock(&fs_info->swapfile_pins_lock);
7933 node = fs_info->swapfile_pins.rb_node;
7935 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7937 node = node->rb_left;
7938 else if (ptr > sp->ptr)
7939 node = node->rb_right;
7943 spin_unlock(&fs_info->swapfile_pins_lock);
7944 return node != NULL;
7947 static int relocating_repair_kthread(void *data)
7949 struct btrfs_block_group *cache = data;
7950 struct btrfs_fs_info *fs_info = cache->fs_info;
7954 target = cache->start;
7955 btrfs_put_block_group(cache);
7957 sb_start_write(fs_info->sb);
7958 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
7960 "zoned: skip relocating block group %llu to repair: EBUSY",
7962 sb_end_write(fs_info->sb);
7966 mutex_lock(&fs_info->reclaim_bgs_lock);
7968 /* Ensure block group still exists */
7969 cache = btrfs_lookup_block_group(fs_info, target);
7973 if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags))
7976 ret = btrfs_may_alloc_data_chunk(fs_info, target);
7981 "zoned: relocating block group %llu to repair IO failure",
7983 ret = btrfs_relocate_chunk(fs_info, target);
7987 btrfs_put_block_group(cache);
7988 mutex_unlock(&fs_info->reclaim_bgs_lock);
7989 btrfs_exclop_finish(fs_info);
7990 sb_end_write(fs_info->sb);
7995 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
7997 struct btrfs_block_group *cache;
7999 if (!btrfs_is_zoned(fs_info))
8002 /* Do not attempt to repair in degraded state */
8003 if (btrfs_test_opt(fs_info, DEGRADED))
8006 cache = btrfs_lookup_block_group(fs_info, logical);
8010 if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) {
8011 btrfs_put_block_group(cache);
8015 kthread_run(relocating_repair_kthread, cache,
8016 "btrfs-relocating-repair");
8021 static void map_raid56_repair_block(struct btrfs_io_context *bioc,
8022 struct btrfs_io_stripe *smap,
8025 int data_stripes = nr_bioc_data_stripes(bioc);
8028 for (i = 0; i < data_stripes; i++) {
8029 u64 stripe_start = bioc->full_stripe_logical +
8030 btrfs_stripe_nr_to_offset(i);
8032 if (logical >= stripe_start &&
8033 logical < stripe_start + BTRFS_STRIPE_LEN)
8036 ASSERT(i < data_stripes);
8037 smap->dev = bioc->stripes[i].dev;
8038 smap->physical = bioc->stripes[i].physical +
8039 ((logical - bioc->full_stripe_logical) &
8040 BTRFS_STRIPE_LEN_MASK);
8044 * Map a repair write into a single device.
8046 * A repair write is triggered by read time repair or scrub, which would only
8047 * update the contents of a single device.
8048 * Not update any other mirrors nor go through RMW path.
8050 * Callers should ensure:
8052 * - Call btrfs_bio_counter_inc_blocked() first
8053 * - The range does not cross stripe boundary
8054 * - Has a valid @mirror_num passed in.
8056 int btrfs_map_repair_block(struct btrfs_fs_info *fs_info,
8057 struct btrfs_io_stripe *smap, u64 logical,
8058 u32 length, int mirror_num)
8060 struct btrfs_io_context *bioc = NULL;
8061 u64 map_length = length;
8062 int mirror_ret = mirror_num;
8065 ASSERT(mirror_num > 0);
8067 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical, &map_length,
8068 &bioc, smap, &mirror_ret);
8072 /* The map range should not cross stripe boundary. */
8073 ASSERT(map_length >= length);
8075 /* Already mapped to single stripe. */
8079 /* Map the RAID56 multi-stripe writes to a single one. */
8080 if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
8081 map_raid56_repair_block(bioc, smap, logical);
8085 ASSERT(mirror_num <= bioc->num_stripes);
8086 smap->dev = bioc->stripes[mirror_num - 1].dev;
8087 smap->physical = bioc->stripes[mirror_num - 1].physical;
8089 btrfs_put_bioc(bioc);