1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/mm.h>
9 #include <linux/slab.h>
10 #include <linux/blkdev.h>
11 #include <linux/ratelimit.h>
12 #include <linux/kthread.h>
13 #include <linux/raid/pq.h>
14 #include <linux/semaphore.h>
15 #include <linux/uuid.h>
16 #include <linux/list_sort.h>
17 #include <linux/namei.h>
20 #include "extent_map.h"
22 #include "transaction.h"
23 #include "print-tree.h"
26 #include "async-thread.h"
27 #include "check-integrity.h"
28 #include "rcu-string.h"
29 #include "dev-replace.h"
31 #include "tree-checker.h"
32 #include "space-info.h"
33 #include "block-group.h"
37 static struct bio_set btrfs_bioset;
39 #define BTRFS_BLOCK_GROUP_STRIPE_MASK (BTRFS_BLOCK_GROUP_RAID0 | \
40 BTRFS_BLOCK_GROUP_RAID10 | \
41 BTRFS_BLOCK_GROUP_RAID56_MASK)
43 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
44 [BTRFS_RAID_RAID10] = {
47 .devs_max = 0, /* 0 == as many as possible */
49 .tolerated_failures = 1,
53 .raid_name = "raid10",
54 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
55 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
57 [BTRFS_RAID_RAID1] = {
62 .tolerated_failures = 1,
67 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
68 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
70 [BTRFS_RAID_RAID1C3] = {
75 .tolerated_failures = 2,
79 .raid_name = "raid1c3",
80 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
81 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
83 [BTRFS_RAID_RAID1C4] = {
88 .tolerated_failures = 3,
92 .raid_name = "raid1c4",
93 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
94 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
101 .tolerated_failures = 0,
106 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
109 [BTRFS_RAID_RAID0] = {
114 .tolerated_failures = 0,
118 .raid_name = "raid0",
119 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
122 [BTRFS_RAID_SINGLE] = {
127 .tolerated_failures = 0,
131 .raid_name = "single",
135 [BTRFS_RAID_RAID5] = {
140 .tolerated_failures = 1,
144 .raid_name = "raid5",
145 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
146 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
148 [BTRFS_RAID_RAID6] = {
153 .tolerated_failures = 2,
157 .raid_name = "raid6",
158 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
159 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
164 * Convert block group flags (BTRFS_BLOCK_GROUP_*) to btrfs_raid_types, which
165 * can be used as index to access btrfs_raid_array[].
167 enum btrfs_raid_types __attribute_const__ btrfs_bg_flags_to_raid_index(u64 flags)
169 const u64 profile = (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK);
172 return BTRFS_RAID_SINGLE;
174 return BTRFS_BG_FLAG_TO_INDEX(profile);
177 const char *btrfs_bg_type_to_raid_name(u64 flags)
179 const int index = btrfs_bg_flags_to_raid_index(flags);
181 if (index >= BTRFS_NR_RAID_TYPES)
184 return btrfs_raid_array[index].raid_name;
187 int btrfs_nr_parity_stripes(u64 type)
189 enum btrfs_raid_types index = btrfs_bg_flags_to_raid_index(type);
191 return btrfs_raid_array[index].nparity;
195 * Fill @buf with textual description of @bg_flags, no more than @size_buf
196 * bytes including terminating null byte.
198 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
203 u64 flags = bg_flags;
204 u32 size_bp = size_buf;
211 #define DESCRIBE_FLAG(flag, desc) \
213 if (flags & (flag)) { \
214 ret = snprintf(bp, size_bp, "%s|", (desc)); \
215 if (ret < 0 || ret >= size_bp) \
223 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
224 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
225 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
227 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
228 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
229 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
230 btrfs_raid_array[i].raid_name);
234 ret = snprintf(bp, size_bp, "0x%llx|", flags);
238 if (size_bp < size_buf)
239 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
242 * The text is trimmed, it's up to the caller to provide sufficiently
248 static int init_first_rw_device(struct btrfs_trans_handle *trans);
249 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
250 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
251 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
252 enum btrfs_map_op op, u64 logical, u64 *length,
253 struct btrfs_io_context **bioc_ret,
254 struct btrfs_io_stripe *smap,
255 int *mirror_num_ret, int need_raid_map);
261 * There are several mutexes that protect manipulation of devices and low-level
262 * structures like chunks but not block groups, extents or files
264 * uuid_mutex (global lock)
265 * ------------------------
266 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
267 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
268 * device) or requested by the device= mount option
270 * the mutex can be very coarse and can cover long-running operations
272 * protects: updates to fs_devices counters like missing devices, rw devices,
273 * seeding, structure cloning, opening/closing devices at mount/umount time
275 * global::fs_devs - add, remove, updates to the global list
277 * does not protect: manipulation of the fs_devices::devices list in general
278 * but in mount context it could be used to exclude list modifications by eg.
281 * btrfs_device::name - renames (write side), read is RCU
283 * fs_devices::device_list_mutex (per-fs, with RCU)
284 * ------------------------------------------------
285 * protects updates to fs_devices::devices, ie. adding and deleting
287 * simple list traversal with read-only actions can be done with RCU protection
289 * may be used to exclude some operations from running concurrently without any
290 * modifications to the list (see write_all_supers)
292 * Is not required at mount and close times, because our device list is
293 * protected by the uuid_mutex at that point.
297 * protects balance structures (status, state) and context accessed from
298 * several places (internally, ioctl)
302 * protects chunks, adding or removing during allocation, trim or when a new
303 * device is added/removed. Additionally it also protects post_commit_list of
304 * individual devices, since they can be added to the transaction's
305 * post_commit_list only with chunk_mutex held.
309 * a big lock that is held by the cleaner thread and prevents running subvolume
310 * cleaning together with relocation or delayed iputs
322 * Exclusive operations
323 * ====================
325 * Maintains the exclusivity of the following operations that apply to the
326 * whole filesystem and cannot run in parallel.
331 * - Device replace (*)
334 * The device operations (as above) can be in one of the following states:
340 * Only device operations marked with (*) can go into the Paused state for the
343 * - ioctl (only Balance can be Paused through ioctl)
344 * - filesystem remounted as read-only
345 * - filesystem unmounted and mounted as read-only
346 * - system power-cycle and filesystem mounted as read-only
347 * - filesystem or device errors leading to forced read-only
349 * The status of exclusive operation is set and cleared atomically.
350 * During the course of Paused state, fs_info::exclusive_operation remains set.
351 * A device operation in Paused or Running state can be canceled or resumed
352 * either by ioctl (Balance only) or when remounted as read-write.
353 * The exclusive status is cleared when the device operation is canceled or
357 DEFINE_MUTEX(uuid_mutex);
358 static LIST_HEAD(fs_uuids);
359 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
365 * alloc_fs_devices - allocate struct btrfs_fs_devices
366 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
367 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
369 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
370 * The returned struct is not linked onto any lists and can be destroyed with
371 * kfree() right away.
373 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
374 const u8 *metadata_fsid)
376 struct btrfs_fs_devices *fs_devs;
378 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
380 return ERR_PTR(-ENOMEM);
382 mutex_init(&fs_devs->device_list_mutex);
384 INIT_LIST_HEAD(&fs_devs->devices);
385 INIT_LIST_HEAD(&fs_devs->alloc_list);
386 INIT_LIST_HEAD(&fs_devs->fs_list);
387 INIT_LIST_HEAD(&fs_devs->seed_list);
389 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
392 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
394 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
399 void btrfs_free_device(struct btrfs_device *device)
401 WARN_ON(!list_empty(&device->post_commit_list));
402 rcu_string_free(device->name);
403 extent_io_tree_release(&device->alloc_state);
404 btrfs_destroy_dev_zone_info(device);
408 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
410 struct btrfs_device *device;
412 WARN_ON(fs_devices->opened);
413 while (!list_empty(&fs_devices->devices)) {
414 device = list_entry(fs_devices->devices.next,
415 struct btrfs_device, dev_list);
416 list_del(&device->dev_list);
417 btrfs_free_device(device);
422 void __exit btrfs_cleanup_fs_uuids(void)
424 struct btrfs_fs_devices *fs_devices;
426 while (!list_empty(&fs_uuids)) {
427 fs_devices = list_entry(fs_uuids.next,
428 struct btrfs_fs_devices, fs_list);
429 list_del(&fs_devices->fs_list);
430 free_fs_devices(fs_devices);
434 static noinline struct btrfs_fs_devices *find_fsid(
435 const u8 *fsid, const u8 *metadata_fsid)
437 struct btrfs_fs_devices *fs_devices;
441 /* Handle non-split brain cases */
442 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
444 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
445 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
446 BTRFS_FSID_SIZE) == 0)
449 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
456 static struct btrfs_fs_devices *find_fsid_with_metadata_uuid(
457 struct btrfs_super_block *disk_super)
460 struct btrfs_fs_devices *fs_devices;
463 * Handle scanned device having completed its fsid change but
464 * belonging to a fs_devices that was created by first scanning
465 * a device which didn't have its fsid/metadata_uuid changed
466 * at all and the CHANGING_FSID_V2 flag set.
468 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
469 if (fs_devices->fsid_change &&
470 memcmp(disk_super->metadata_uuid, fs_devices->fsid,
471 BTRFS_FSID_SIZE) == 0 &&
472 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
473 BTRFS_FSID_SIZE) == 0) {
478 * Handle scanned device having completed its fsid change but
479 * belonging to a fs_devices that was created by a device that
480 * has an outdated pair of fsid/metadata_uuid and
481 * CHANGING_FSID_V2 flag set.
483 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
484 if (fs_devices->fsid_change &&
485 memcmp(fs_devices->metadata_uuid,
486 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
487 memcmp(disk_super->metadata_uuid, fs_devices->metadata_uuid,
488 BTRFS_FSID_SIZE) == 0) {
493 return find_fsid(disk_super->fsid, disk_super->metadata_uuid);
498 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
499 int flush, struct block_device **bdev,
500 struct btrfs_super_block **disk_super)
504 *bdev = blkdev_get_by_path(device_path, flags, holder);
507 ret = PTR_ERR(*bdev);
512 sync_blockdev(*bdev);
513 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
515 blkdev_put(*bdev, flags);
518 invalidate_bdev(*bdev);
519 *disk_super = btrfs_read_dev_super(*bdev);
520 if (IS_ERR(*disk_super)) {
521 ret = PTR_ERR(*disk_super);
522 blkdev_put(*bdev, flags);
534 * Search and remove all stale devices (which are not mounted).
535 * When both inputs are NULL, it will search and release all stale devices.
537 * @devt: Optional. When provided will it release all unmounted devices
538 * matching this devt only.
539 * @skip_device: Optional. Will skip this device when searching for the stale
542 * Return: 0 for success or if @devt is 0.
543 * -EBUSY if @devt is a mounted device.
544 * -ENOENT if @devt does not match any device in the list.
546 static int btrfs_free_stale_devices(dev_t devt, struct btrfs_device *skip_device)
548 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
549 struct btrfs_device *device, *tmp_device;
552 lockdep_assert_held(&uuid_mutex);
557 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
559 mutex_lock(&fs_devices->device_list_mutex);
560 list_for_each_entry_safe(device, tmp_device,
561 &fs_devices->devices, dev_list) {
562 if (skip_device && skip_device == device)
564 if (devt && devt != device->devt)
566 if (fs_devices->opened) {
567 /* for an already deleted device return 0 */
568 if (devt && ret != 0)
573 /* delete the stale device */
574 fs_devices->num_devices--;
575 list_del(&device->dev_list);
576 btrfs_free_device(device);
580 mutex_unlock(&fs_devices->device_list_mutex);
582 if (fs_devices->num_devices == 0) {
583 btrfs_sysfs_remove_fsid(fs_devices);
584 list_del(&fs_devices->fs_list);
585 free_fs_devices(fs_devices);
593 * This is only used on mount, and we are protected from competing things
594 * messing with our fs_devices by the uuid_mutex, thus we do not need the
595 * fs_devices->device_list_mutex here.
597 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
598 struct btrfs_device *device, fmode_t flags,
601 struct block_device *bdev;
602 struct btrfs_super_block *disk_super;
611 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
616 devid = btrfs_stack_device_id(&disk_super->dev_item);
617 if (devid != device->devid)
618 goto error_free_page;
620 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
621 goto error_free_page;
623 device->generation = btrfs_super_generation(disk_super);
625 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
626 if (btrfs_super_incompat_flags(disk_super) &
627 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
629 "BTRFS: Invalid seeding and uuid-changed device detected\n");
630 goto error_free_page;
633 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
634 fs_devices->seeding = true;
636 if (bdev_read_only(bdev))
637 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
639 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
642 if (!bdev_nonrot(bdev))
643 fs_devices->rotating = true;
646 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
647 device->mode = flags;
649 fs_devices->open_devices++;
650 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
651 device->devid != BTRFS_DEV_REPLACE_DEVID) {
652 fs_devices->rw_devices++;
653 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
655 btrfs_release_disk_super(disk_super);
660 btrfs_release_disk_super(disk_super);
661 blkdev_put(bdev, flags);
666 u8 *btrfs_sb_fsid_ptr(struct btrfs_super_block *sb)
668 bool has_metadata_uuid = (btrfs_super_incompat_flags(sb) &
669 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
671 return has_metadata_uuid ? sb->metadata_uuid : sb->fsid;
675 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
676 * being created with a disk that has already completed its fsid change. Such
677 * disk can belong to an fs which has its FSID changed or to one which doesn't.
678 * Handle both cases here.
680 static struct btrfs_fs_devices *find_fsid_inprogress(
681 struct btrfs_super_block *disk_super)
683 struct btrfs_fs_devices *fs_devices;
685 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
686 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
687 BTRFS_FSID_SIZE) != 0 &&
688 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
689 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
694 return find_fsid(disk_super->fsid, NULL);
698 static struct btrfs_fs_devices *find_fsid_changed(
699 struct btrfs_super_block *disk_super)
701 struct btrfs_fs_devices *fs_devices;
704 * Handles the case where scanned device is part of an fs that had
705 * multiple successful changes of FSID but currently device didn't
706 * observe it. Meaning our fsid will be different than theirs. We need
707 * to handle two subcases :
708 * 1 - The fs still continues to have different METADATA/FSID uuids.
709 * 2 - The fs is switched back to its original FSID (METADATA/FSID
712 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
714 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
715 BTRFS_FSID_SIZE) != 0 &&
716 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
717 BTRFS_FSID_SIZE) == 0 &&
718 memcmp(fs_devices->fsid, disk_super->fsid,
719 BTRFS_FSID_SIZE) != 0)
722 /* Unchanged UUIDs */
723 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
724 BTRFS_FSID_SIZE) == 0 &&
725 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
726 BTRFS_FSID_SIZE) == 0)
733 static struct btrfs_fs_devices *find_fsid_reverted_metadata(
734 struct btrfs_super_block *disk_super)
736 struct btrfs_fs_devices *fs_devices;
739 * Handle the case where the scanned device is part of an fs whose last
740 * metadata UUID change reverted it to the original FSID. At the same
741 * time * fs_devices was first created by another constitutent device
742 * which didn't fully observe the operation. This results in an
743 * btrfs_fs_devices created with metadata/fsid different AND
744 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
745 * fs_devices equal to the FSID of the disk.
747 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
748 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
749 BTRFS_FSID_SIZE) != 0 &&
750 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
751 BTRFS_FSID_SIZE) == 0 &&
752 fs_devices->fsid_change)
759 * Add new device to list of registered devices
762 * device pointer which was just added or updated when successful
763 * error pointer when failed
765 static noinline struct btrfs_device *device_list_add(const char *path,
766 struct btrfs_super_block *disk_super,
767 bool *new_device_added)
769 struct btrfs_device *device;
770 struct btrfs_fs_devices *fs_devices = NULL;
771 struct rcu_string *name;
772 u64 found_transid = btrfs_super_generation(disk_super);
773 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
776 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
777 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
778 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
779 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
781 error = lookup_bdev(path, &path_devt);
783 btrfs_err(NULL, "failed to lookup block device for path %s: %d",
785 return ERR_PTR(error);
788 if (fsid_change_in_progress) {
789 if (!has_metadata_uuid)
790 fs_devices = find_fsid_inprogress(disk_super);
792 fs_devices = find_fsid_changed(disk_super);
793 } else if (has_metadata_uuid) {
794 fs_devices = find_fsid_with_metadata_uuid(disk_super);
796 fs_devices = find_fsid_reverted_metadata(disk_super);
798 fs_devices = find_fsid(disk_super->fsid, NULL);
803 if (has_metadata_uuid)
804 fs_devices = alloc_fs_devices(disk_super->fsid,
805 disk_super->metadata_uuid);
807 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
809 if (IS_ERR(fs_devices))
810 return ERR_CAST(fs_devices);
812 fs_devices->fsid_change = fsid_change_in_progress;
814 mutex_lock(&fs_devices->device_list_mutex);
815 list_add(&fs_devices->fs_list, &fs_uuids);
819 struct btrfs_dev_lookup_args args = {
821 .uuid = disk_super->dev_item.uuid,
824 mutex_lock(&fs_devices->device_list_mutex);
825 device = btrfs_find_device(fs_devices, &args);
828 * If this disk has been pulled into an fs devices created by
829 * a device which had the CHANGING_FSID_V2 flag then replace the
830 * metadata_uuid/fsid values of the fs_devices.
832 if (fs_devices->fsid_change &&
833 found_transid > fs_devices->latest_generation) {
834 memcpy(fs_devices->fsid, disk_super->fsid,
837 if (has_metadata_uuid)
838 memcpy(fs_devices->metadata_uuid,
839 disk_super->metadata_uuid,
842 memcpy(fs_devices->metadata_uuid,
843 disk_super->fsid, BTRFS_FSID_SIZE);
845 fs_devices->fsid_change = false;
850 if (fs_devices->opened) {
852 "device %s belongs to fsid %pU, and the fs is already mounted",
853 path, fs_devices->fsid);
854 mutex_unlock(&fs_devices->device_list_mutex);
855 return ERR_PTR(-EBUSY);
858 device = btrfs_alloc_device(NULL, &devid,
859 disk_super->dev_item.uuid);
860 if (IS_ERR(device)) {
861 mutex_unlock(&fs_devices->device_list_mutex);
862 /* we can safely leave the fs_devices entry around */
866 name = rcu_string_strdup(path, GFP_NOFS);
868 btrfs_free_device(device);
869 mutex_unlock(&fs_devices->device_list_mutex);
870 return ERR_PTR(-ENOMEM);
872 rcu_assign_pointer(device->name, name);
873 device->devt = path_devt;
875 list_add_rcu(&device->dev_list, &fs_devices->devices);
876 fs_devices->num_devices++;
878 device->fs_devices = fs_devices;
879 *new_device_added = true;
881 if (disk_super->label[0])
883 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
884 disk_super->label, devid, found_transid, path,
885 current->comm, task_pid_nr(current));
888 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
889 disk_super->fsid, devid, found_transid, path,
890 current->comm, task_pid_nr(current));
892 } else if (!device->name || strcmp(device->name->str, path)) {
894 * When FS is already mounted.
895 * 1. If you are here and if the device->name is NULL that
896 * means this device was missing at time of FS mount.
897 * 2. If you are here and if the device->name is different
898 * from 'path' that means either
899 * a. The same device disappeared and reappeared with
901 * b. The missing-disk-which-was-replaced, has
904 * We must allow 1 and 2a above. But 2b would be a spurious
907 * Further in case of 1 and 2a above, the disk at 'path'
908 * would have missed some transaction when it was away and
909 * in case of 2a the stale bdev has to be updated as well.
910 * 2b must not be allowed at all time.
914 * For now, we do allow update to btrfs_fs_device through the
915 * btrfs dev scan cli after FS has been mounted. We're still
916 * tracking a problem where systems fail mount by subvolume id
917 * when we reject replacement on a mounted FS.
919 if (!fs_devices->opened && found_transid < device->generation) {
921 * That is if the FS is _not_ mounted and if you
922 * are here, that means there is more than one
923 * disk with same uuid and devid.We keep the one
924 * with larger generation number or the last-in if
925 * generation are equal.
927 mutex_unlock(&fs_devices->device_list_mutex);
929 "device %s already registered with a higher generation, found %llu expect %llu",
930 path, found_transid, device->generation);
931 return ERR_PTR(-EEXIST);
935 * We are going to replace the device path for a given devid,
936 * make sure it's the same device if the device is mounted
938 * NOTE: the device->fs_info may not be reliable here so pass
939 * in a NULL to message helpers instead. This avoids a possible
940 * use-after-free when the fs_info and fs_info->sb are already
944 if (device->devt != path_devt) {
945 mutex_unlock(&fs_devices->device_list_mutex);
946 btrfs_warn_in_rcu(NULL,
947 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
948 path, devid, found_transid,
950 task_pid_nr(current));
951 return ERR_PTR(-EEXIST);
953 btrfs_info_in_rcu(NULL,
954 "devid %llu device path %s changed to %s scanned by %s (%d)",
955 devid, rcu_str_deref(device->name),
957 task_pid_nr(current));
960 name = rcu_string_strdup(path, GFP_NOFS);
962 mutex_unlock(&fs_devices->device_list_mutex);
963 return ERR_PTR(-ENOMEM);
965 rcu_string_free(device->name);
966 rcu_assign_pointer(device->name, name);
967 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
968 fs_devices->missing_devices--;
969 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
971 device->devt = path_devt;
975 * Unmount does not free the btrfs_device struct but would zero
976 * generation along with most of the other members. So just update
977 * it back. We need it to pick the disk with largest generation
980 if (!fs_devices->opened) {
981 device->generation = found_transid;
982 fs_devices->latest_generation = max_t(u64, found_transid,
983 fs_devices->latest_generation);
986 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
988 mutex_unlock(&fs_devices->device_list_mutex);
992 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
994 struct btrfs_fs_devices *fs_devices;
995 struct btrfs_device *device;
996 struct btrfs_device *orig_dev;
999 lockdep_assert_held(&uuid_mutex);
1001 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1002 if (IS_ERR(fs_devices))
1005 fs_devices->total_devices = orig->total_devices;
1007 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1008 struct rcu_string *name;
1010 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1012 if (IS_ERR(device)) {
1013 ret = PTR_ERR(device);
1018 * This is ok to do without rcu read locked because we hold the
1019 * uuid mutex so nothing we touch in here is going to disappear.
1021 if (orig_dev->name) {
1022 name = rcu_string_strdup(orig_dev->name->str,
1025 btrfs_free_device(device);
1029 rcu_assign_pointer(device->name, name);
1032 if (orig_dev->zone_info) {
1033 struct btrfs_zoned_device_info *zone_info;
1035 zone_info = btrfs_clone_dev_zone_info(orig_dev);
1037 btrfs_free_device(device);
1041 device->zone_info = zone_info;
1044 list_add(&device->dev_list, &fs_devices->devices);
1045 device->fs_devices = fs_devices;
1046 fs_devices->num_devices++;
1050 free_fs_devices(fs_devices);
1051 return ERR_PTR(ret);
1054 static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
1055 struct btrfs_device **latest_dev)
1057 struct btrfs_device *device, *next;
1059 /* This is the initialized path, it is safe to release the devices. */
1060 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1061 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
1062 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1063 &device->dev_state) &&
1064 !test_bit(BTRFS_DEV_STATE_MISSING,
1065 &device->dev_state) &&
1067 device->generation > (*latest_dev)->generation)) {
1068 *latest_dev = device;
1074 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1075 * in btrfs_init_dev_replace() so just continue.
1077 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1081 blkdev_put(device->bdev, device->mode);
1082 device->bdev = NULL;
1083 fs_devices->open_devices--;
1085 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1086 list_del_init(&device->dev_alloc_list);
1087 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1088 fs_devices->rw_devices--;
1090 list_del_init(&device->dev_list);
1091 fs_devices->num_devices--;
1092 btrfs_free_device(device);
1098 * After we have read the system tree and know devids belonging to this
1099 * filesystem, remove the device which does not belong there.
1101 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices)
1103 struct btrfs_device *latest_dev = NULL;
1104 struct btrfs_fs_devices *seed_dev;
1106 mutex_lock(&uuid_mutex);
1107 __btrfs_free_extra_devids(fs_devices, &latest_dev);
1109 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1110 __btrfs_free_extra_devids(seed_dev, &latest_dev);
1112 fs_devices->latest_dev = latest_dev;
1114 mutex_unlock(&uuid_mutex);
1117 static void btrfs_close_bdev(struct btrfs_device *device)
1122 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1123 sync_blockdev(device->bdev);
1124 invalidate_bdev(device->bdev);
1127 blkdev_put(device->bdev, device->mode);
1130 static void btrfs_close_one_device(struct btrfs_device *device)
1132 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1134 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1135 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1136 list_del_init(&device->dev_alloc_list);
1137 fs_devices->rw_devices--;
1140 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1141 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
1143 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1144 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1145 fs_devices->missing_devices--;
1148 btrfs_close_bdev(device);
1150 fs_devices->open_devices--;
1151 device->bdev = NULL;
1153 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1154 btrfs_destroy_dev_zone_info(device);
1156 device->fs_info = NULL;
1157 atomic_set(&device->dev_stats_ccnt, 0);
1158 extent_io_tree_release(&device->alloc_state);
1161 * Reset the flush error record. We might have a transient flush error
1162 * in this mount, and if so we aborted the current transaction and set
1163 * the fs to an error state, guaranteeing no super blocks can be further
1164 * committed. However that error might be transient and if we unmount the
1165 * filesystem and mount it again, we should allow the mount to succeed
1166 * (btrfs_check_rw_degradable() should not fail) - if after mounting the
1167 * filesystem again we still get flush errors, then we will again abort
1168 * any transaction and set the error state, guaranteeing no commits of
1169 * unsafe super blocks.
1171 device->last_flush_error = 0;
1173 /* Verify the device is back in a pristine state */
1174 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1175 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1176 ASSERT(list_empty(&device->dev_alloc_list));
1177 ASSERT(list_empty(&device->post_commit_list));
1180 static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
1182 struct btrfs_device *device, *tmp;
1184 lockdep_assert_held(&uuid_mutex);
1186 if (--fs_devices->opened > 0)
1189 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
1190 btrfs_close_one_device(device);
1192 WARN_ON(fs_devices->open_devices);
1193 WARN_ON(fs_devices->rw_devices);
1194 fs_devices->opened = 0;
1195 fs_devices->seeding = false;
1196 fs_devices->fs_info = NULL;
1199 void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1202 struct btrfs_fs_devices *tmp;
1204 mutex_lock(&uuid_mutex);
1205 close_fs_devices(fs_devices);
1206 if (!fs_devices->opened) {
1207 list_splice_init(&fs_devices->seed_list, &list);
1210 * If the struct btrfs_fs_devices is not assembled with any
1211 * other device, it can be re-initialized during the next mount
1212 * without the needing device-scan step. Therefore, it can be
1215 if (fs_devices->num_devices == 1) {
1216 list_del(&fs_devices->fs_list);
1217 free_fs_devices(fs_devices);
1222 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
1223 close_fs_devices(fs_devices);
1224 list_del(&fs_devices->seed_list);
1225 free_fs_devices(fs_devices);
1227 mutex_unlock(&uuid_mutex);
1230 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1231 fmode_t flags, void *holder)
1233 struct btrfs_device *device;
1234 struct btrfs_device *latest_dev = NULL;
1235 struct btrfs_device *tmp_device;
1237 flags |= FMODE_EXCL;
1239 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1243 ret = btrfs_open_one_device(fs_devices, device, flags, holder);
1245 (!latest_dev || device->generation > latest_dev->generation)) {
1246 latest_dev = device;
1247 } else if (ret == -ENODATA) {
1248 fs_devices->num_devices--;
1249 list_del(&device->dev_list);
1250 btrfs_free_device(device);
1253 if (fs_devices->open_devices == 0)
1256 fs_devices->opened = 1;
1257 fs_devices->latest_dev = latest_dev;
1258 fs_devices->total_rw_bytes = 0;
1259 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1260 fs_devices->read_policy = BTRFS_READ_POLICY_PID;
1265 static int devid_cmp(void *priv, const struct list_head *a,
1266 const struct list_head *b)
1268 const struct btrfs_device *dev1, *dev2;
1270 dev1 = list_entry(a, struct btrfs_device, dev_list);
1271 dev2 = list_entry(b, struct btrfs_device, dev_list);
1273 if (dev1->devid < dev2->devid)
1275 else if (dev1->devid > dev2->devid)
1280 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1281 fmode_t flags, void *holder)
1285 lockdep_assert_held(&uuid_mutex);
1287 * The device_list_mutex cannot be taken here in case opening the
1288 * underlying device takes further locks like open_mutex.
1290 * We also don't need the lock here as this is called during mount and
1291 * exclusion is provided by uuid_mutex
1294 if (fs_devices->opened) {
1295 fs_devices->opened++;
1298 list_sort(NULL, &fs_devices->devices, devid_cmp);
1299 ret = open_fs_devices(fs_devices, flags, holder);
1305 void btrfs_release_disk_super(struct btrfs_super_block *super)
1307 struct page *page = virt_to_page(super);
1312 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1313 u64 bytenr, u64 bytenr_orig)
1315 struct btrfs_super_block *disk_super;
1320 /* make sure our super fits in the device */
1321 if (bytenr + PAGE_SIZE >= bdev_nr_bytes(bdev))
1322 return ERR_PTR(-EINVAL);
1324 /* make sure our super fits in the page */
1325 if (sizeof(*disk_super) > PAGE_SIZE)
1326 return ERR_PTR(-EINVAL);
1328 /* make sure our super doesn't straddle pages on disk */
1329 index = bytenr >> PAGE_SHIFT;
1330 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1331 return ERR_PTR(-EINVAL);
1333 /* pull in the page with our super */
1334 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1337 return ERR_CAST(page);
1339 p = page_address(page);
1341 /* align our pointer to the offset of the super block */
1342 disk_super = p + offset_in_page(bytenr);
1344 if (btrfs_super_bytenr(disk_super) != bytenr_orig ||
1345 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1346 btrfs_release_disk_super(p);
1347 return ERR_PTR(-EINVAL);
1350 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1351 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1356 int btrfs_forget_devices(dev_t devt)
1360 mutex_lock(&uuid_mutex);
1361 ret = btrfs_free_stale_devices(devt, NULL);
1362 mutex_unlock(&uuid_mutex);
1368 * Look for a btrfs signature on a device. This may be called out of the mount path
1369 * and we are not allowed to call set_blocksize during the scan. The superblock
1370 * is read via pagecache
1372 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1375 struct btrfs_super_block *disk_super;
1376 bool new_device_added = false;
1377 struct btrfs_device *device = NULL;
1378 struct block_device *bdev;
1379 u64 bytenr, bytenr_orig;
1382 lockdep_assert_held(&uuid_mutex);
1385 * we would like to check all the supers, but that would make
1386 * a btrfs mount succeed after a mkfs from a different FS.
1387 * So, we need to add a special mount option to scan for
1388 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1392 * Avoid using flag |= FMODE_EXCL here, as the systemd-udev may
1393 * initiate the device scan which may race with the user's mount
1394 * or mkfs command, resulting in failure.
1395 * Since the device scan is solely for reading purposes, there is
1396 * no need for FMODE_EXCL. Additionally, the devices are read again
1397 * during the mount process. It is ok to get some inconsistent
1398 * values temporarily, as the device paths of the fsid are the only
1399 * required information for assembling the volume.
1401 bdev = blkdev_get_by_path(path, flags, holder);
1403 return ERR_CAST(bdev);
1405 bytenr_orig = btrfs_sb_offset(0);
1406 ret = btrfs_sb_log_location_bdev(bdev, 0, READ, &bytenr);
1408 device = ERR_PTR(ret);
1409 goto error_bdev_put;
1412 disk_super = btrfs_read_disk_super(bdev, bytenr, bytenr_orig);
1413 if (IS_ERR(disk_super)) {
1414 device = ERR_CAST(disk_super);
1415 goto error_bdev_put;
1418 device = device_list_add(path, disk_super, &new_device_added);
1419 if (!IS_ERR(device) && new_device_added)
1420 btrfs_free_stale_devices(device->devt, device);
1422 btrfs_release_disk_super(disk_super);
1425 blkdev_put(bdev, flags);
1431 * Try to find a chunk that intersects [start, start + len] range and when one
1432 * such is found, record the end of it in *start
1434 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1437 u64 physical_start, physical_end;
1439 lockdep_assert_held(&device->fs_info->chunk_mutex);
1441 if (!find_first_extent_bit(&device->alloc_state, *start,
1442 &physical_start, &physical_end,
1443 CHUNK_ALLOCATED, NULL)) {
1445 if (in_range(physical_start, *start, len) ||
1446 in_range(*start, physical_start,
1447 physical_end + 1 - physical_start)) {
1448 *start = physical_end + 1;
1455 static u64 dev_extent_search_start(struct btrfs_device *device, u64 start)
1457 switch (device->fs_devices->chunk_alloc_policy) {
1458 case BTRFS_CHUNK_ALLOC_REGULAR:
1459 return max_t(u64, start, BTRFS_DEVICE_RANGE_RESERVED);
1460 case BTRFS_CHUNK_ALLOC_ZONED:
1462 * We don't care about the starting region like regular
1463 * allocator, because we anyway use/reserve the first two zones
1464 * for superblock logging.
1466 return ALIGN(start, device->zone_info->zone_size);
1472 static bool dev_extent_hole_check_zoned(struct btrfs_device *device,
1473 u64 *hole_start, u64 *hole_size,
1476 u64 zone_size = device->zone_info->zone_size;
1479 bool changed = false;
1481 ASSERT(IS_ALIGNED(*hole_start, zone_size));
1483 while (*hole_size > 0) {
1484 pos = btrfs_find_allocatable_zones(device, *hole_start,
1485 *hole_start + *hole_size,
1487 if (pos != *hole_start) {
1488 *hole_size = *hole_start + *hole_size - pos;
1491 if (*hole_size < num_bytes)
1495 ret = btrfs_ensure_empty_zones(device, pos, num_bytes);
1497 /* Range is ensured to be empty */
1501 /* Given hole range was invalid (outside of device) */
1502 if (ret == -ERANGE) {
1503 *hole_start += *hole_size;
1508 *hole_start += zone_size;
1509 *hole_size -= zone_size;
1517 * dev_extent_hole_check - check if specified hole is suitable for allocation
1518 * @device: the device which we have the hole
1519 * @hole_start: starting position of the hole
1520 * @hole_size: the size of the hole
1521 * @num_bytes: the size of the free space that we need
1523 * This function may modify @hole_start and @hole_size to reflect the suitable
1524 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1526 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1527 u64 *hole_size, u64 num_bytes)
1529 bool changed = false;
1530 u64 hole_end = *hole_start + *hole_size;
1534 * Check before we set max_hole_start, otherwise we could end up
1535 * sending back this offset anyway.
1537 if (contains_pending_extent(device, hole_start, *hole_size)) {
1538 if (hole_end >= *hole_start)
1539 *hole_size = hole_end - *hole_start;
1545 switch (device->fs_devices->chunk_alloc_policy) {
1546 case BTRFS_CHUNK_ALLOC_REGULAR:
1547 /* No extra check */
1549 case BTRFS_CHUNK_ALLOC_ZONED:
1550 if (dev_extent_hole_check_zoned(device, hole_start,
1551 hole_size, num_bytes)) {
1554 * The changed hole can contain pending extent.
1555 * Loop again to check that.
1571 * find_free_dev_extent_start - find free space in the specified device
1572 * @device: the device which we search the free space in
1573 * @num_bytes: the size of the free space that we need
1574 * @search_start: the position from which to begin the search
1575 * @start: store the start of the free space.
1576 * @len: the size of the free space. that we find, or the size
1577 * of the max free space if we don't find suitable free space
1579 * this uses a pretty simple search, the expectation is that it is
1580 * called very infrequently and that a given device has a small number
1583 * @start is used to store the start of the free space if we find. But if we
1584 * don't find suitable free space, it will be used to store the start position
1585 * of the max free space.
1587 * @len is used to store the size of the free space that we find.
1588 * But if we don't find suitable free space, it is used to store the size of
1589 * the max free space.
1591 * NOTE: This function will search *commit* root of device tree, and does extra
1592 * check to ensure dev extents are not double allocated.
1593 * This makes the function safe to allocate dev extents but may not report
1594 * correct usable device space, as device extent freed in current transaction
1595 * is not reported as available.
1597 static int find_free_dev_extent_start(struct btrfs_device *device,
1598 u64 num_bytes, u64 search_start, u64 *start,
1601 struct btrfs_fs_info *fs_info = device->fs_info;
1602 struct btrfs_root *root = fs_info->dev_root;
1603 struct btrfs_key key;
1604 struct btrfs_dev_extent *dev_extent;
1605 struct btrfs_path *path;
1610 u64 search_end = device->total_bytes;
1613 struct extent_buffer *l;
1615 search_start = dev_extent_search_start(device, search_start);
1617 WARN_ON(device->zone_info &&
1618 !IS_ALIGNED(num_bytes, device->zone_info->zone_size));
1620 path = btrfs_alloc_path();
1624 max_hole_start = search_start;
1628 if (search_start >= search_end ||
1629 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1634 path->reada = READA_FORWARD;
1635 path->search_commit_root = 1;
1636 path->skip_locking = 1;
1638 key.objectid = device->devid;
1639 key.offset = search_start;
1640 key.type = BTRFS_DEV_EXTENT_KEY;
1642 ret = btrfs_search_backwards(root, &key, path);
1646 while (search_start < search_end) {
1648 slot = path->slots[0];
1649 if (slot >= btrfs_header_nritems(l)) {
1650 ret = btrfs_next_leaf(root, path);
1658 btrfs_item_key_to_cpu(l, &key, slot);
1660 if (key.objectid < device->devid)
1663 if (key.objectid > device->devid)
1666 if (key.type != BTRFS_DEV_EXTENT_KEY)
1669 if (key.offset > search_end)
1672 if (key.offset > search_start) {
1673 hole_size = key.offset - search_start;
1674 dev_extent_hole_check(device, &search_start, &hole_size,
1677 if (hole_size > max_hole_size) {
1678 max_hole_start = search_start;
1679 max_hole_size = hole_size;
1683 * If this free space is greater than which we need,
1684 * it must be the max free space that we have found
1685 * until now, so max_hole_start must point to the start
1686 * of this free space and the length of this free space
1687 * is stored in max_hole_size. Thus, we return
1688 * max_hole_start and max_hole_size and go back to the
1691 if (hole_size >= num_bytes) {
1697 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1698 extent_end = key.offset + btrfs_dev_extent_length(l,
1700 if (extent_end > search_start)
1701 search_start = extent_end;
1708 * At this point, search_start should be the end of
1709 * allocated dev extents, and when shrinking the device,
1710 * search_end may be smaller than search_start.
1712 if (search_end > search_start) {
1713 hole_size = search_end - search_start;
1714 if (dev_extent_hole_check(device, &search_start, &hole_size,
1716 btrfs_release_path(path);
1720 if (hole_size > max_hole_size) {
1721 max_hole_start = search_start;
1722 max_hole_size = hole_size;
1727 if (max_hole_size < num_bytes)
1732 ASSERT(max_hole_start + max_hole_size <= search_end);
1734 btrfs_free_path(path);
1735 *start = max_hole_start;
1737 *len = max_hole_size;
1741 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1742 u64 *start, u64 *len)
1744 /* FIXME use last free of some kind */
1745 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1748 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1749 struct btrfs_device *device,
1750 u64 start, u64 *dev_extent_len)
1752 struct btrfs_fs_info *fs_info = device->fs_info;
1753 struct btrfs_root *root = fs_info->dev_root;
1755 struct btrfs_path *path;
1756 struct btrfs_key key;
1757 struct btrfs_key found_key;
1758 struct extent_buffer *leaf = NULL;
1759 struct btrfs_dev_extent *extent = NULL;
1761 path = btrfs_alloc_path();
1765 key.objectid = device->devid;
1767 key.type = BTRFS_DEV_EXTENT_KEY;
1769 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1771 ret = btrfs_previous_item(root, path, key.objectid,
1772 BTRFS_DEV_EXTENT_KEY);
1775 leaf = path->nodes[0];
1776 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1777 extent = btrfs_item_ptr(leaf, path->slots[0],
1778 struct btrfs_dev_extent);
1779 BUG_ON(found_key.offset > start || found_key.offset +
1780 btrfs_dev_extent_length(leaf, extent) < start);
1782 btrfs_release_path(path);
1784 } else if (ret == 0) {
1785 leaf = path->nodes[0];
1786 extent = btrfs_item_ptr(leaf, path->slots[0],
1787 struct btrfs_dev_extent);
1792 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1794 ret = btrfs_del_item(trans, root, path);
1796 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1798 btrfs_free_path(path);
1802 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1804 struct extent_map_tree *em_tree;
1805 struct extent_map *em;
1809 em_tree = &fs_info->mapping_tree;
1810 read_lock(&em_tree->lock);
1811 n = rb_last(&em_tree->map.rb_root);
1813 em = rb_entry(n, struct extent_map, rb_node);
1814 ret = em->start + em->len;
1816 read_unlock(&em_tree->lock);
1821 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1825 struct btrfs_key key;
1826 struct btrfs_key found_key;
1827 struct btrfs_path *path;
1829 path = btrfs_alloc_path();
1833 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1834 key.type = BTRFS_DEV_ITEM_KEY;
1835 key.offset = (u64)-1;
1837 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1843 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1848 ret = btrfs_previous_item(fs_info->chunk_root, path,
1849 BTRFS_DEV_ITEMS_OBJECTID,
1850 BTRFS_DEV_ITEM_KEY);
1854 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1856 *devid_ret = found_key.offset + 1;
1860 btrfs_free_path(path);
1865 * the device information is stored in the chunk root
1866 * the btrfs_device struct should be fully filled in
1868 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1869 struct btrfs_device *device)
1872 struct btrfs_path *path;
1873 struct btrfs_dev_item *dev_item;
1874 struct extent_buffer *leaf;
1875 struct btrfs_key key;
1878 path = btrfs_alloc_path();
1882 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1883 key.type = BTRFS_DEV_ITEM_KEY;
1884 key.offset = device->devid;
1886 btrfs_reserve_chunk_metadata(trans, true);
1887 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1888 &key, sizeof(*dev_item));
1889 btrfs_trans_release_chunk_metadata(trans);
1893 leaf = path->nodes[0];
1894 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1896 btrfs_set_device_id(leaf, dev_item, device->devid);
1897 btrfs_set_device_generation(leaf, dev_item, 0);
1898 btrfs_set_device_type(leaf, dev_item, device->type);
1899 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1900 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1901 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1902 btrfs_set_device_total_bytes(leaf, dev_item,
1903 btrfs_device_get_disk_total_bytes(device));
1904 btrfs_set_device_bytes_used(leaf, dev_item,
1905 btrfs_device_get_bytes_used(device));
1906 btrfs_set_device_group(leaf, dev_item, 0);
1907 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1908 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1909 btrfs_set_device_start_offset(leaf, dev_item, 0);
1911 ptr = btrfs_device_uuid(dev_item);
1912 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1913 ptr = btrfs_device_fsid(dev_item);
1914 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1915 ptr, BTRFS_FSID_SIZE);
1916 btrfs_mark_buffer_dirty(leaf);
1920 btrfs_free_path(path);
1925 * Function to update ctime/mtime for a given device path.
1926 * Mainly used for ctime/mtime based probe like libblkid.
1928 * We don't care about errors here, this is just to be kind to userspace.
1930 static void update_dev_time(const char *device_path)
1933 struct timespec64 now;
1936 ret = kern_path(device_path, LOOKUP_FOLLOW, &path);
1940 now = current_time(d_inode(path.dentry));
1941 inode_update_time(d_inode(path.dentry), &now, S_MTIME | S_CTIME);
1945 static int btrfs_rm_dev_item(struct btrfs_trans_handle *trans,
1946 struct btrfs_device *device)
1948 struct btrfs_root *root = device->fs_info->chunk_root;
1950 struct btrfs_path *path;
1951 struct btrfs_key key;
1953 path = btrfs_alloc_path();
1957 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1958 key.type = BTRFS_DEV_ITEM_KEY;
1959 key.offset = device->devid;
1961 btrfs_reserve_chunk_metadata(trans, false);
1962 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1963 btrfs_trans_release_chunk_metadata(trans);
1970 ret = btrfs_del_item(trans, root, path);
1972 btrfs_free_path(path);
1977 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1978 * filesystem. It's up to the caller to adjust that number regarding eg. device
1981 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1989 seq = read_seqbegin(&fs_info->profiles_lock);
1991 all_avail = fs_info->avail_data_alloc_bits |
1992 fs_info->avail_system_alloc_bits |
1993 fs_info->avail_metadata_alloc_bits;
1994 } while (read_seqretry(&fs_info->profiles_lock, seq));
1996 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1997 if (!(all_avail & btrfs_raid_array[i].bg_flag))
2000 if (num_devices < btrfs_raid_array[i].devs_min)
2001 return btrfs_raid_array[i].mindev_error;
2007 static struct btrfs_device * btrfs_find_next_active_device(
2008 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2010 struct btrfs_device *next_device;
2012 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2013 if (next_device != device &&
2014 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2015 && next_device->bdev)
2023 * Helper function to check if the given device is part of s_bdev / latest_dev
2024 * and replace it with the provided or the next active device, in the context
2025 * where this function called, there should be always be another device (or
2026 * this_dev) which is active.
2028 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
2029 struct btrfs_device *next_device)
2031 struct btrfs_fs_info *fs_info = device->fs_info;
2034 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2036 ASSERT(next_device);
2038 if (fs_info->sb->s_bdev &&
2039 (fs_info->sb->s_bdev == device->bdev))
2040 fs_info->sb->s_bdev = next_device->bdev;
2042 if (fs_info->fs_devices->latest_dev->bdev == device->bdev)
2043 fs_info->fs_devices->latest_dev = next_device;
2047 * Return btrfs_fs_devices::num_devices excluding the device that's being
2048 * currently replaced.
2050 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2052 u64 num_devices = fs_info->fs_devices->num_devices;
2054 down_read(&fs_info->dev_replace.rwsem);
2055 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2056 ASSERT(num_devices > 1);
2059 up_read(&fs_info->dev_replace.rwsem);
2064 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2065 struct block_device *bdev,
2066 const char *device_path)
2068 struct btrfs_super_block *disk_super;
2074 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2078 disk_super = btrfs_read_dev_one_super(bdev, copy_num, false);
2079 if (IS_ERR(disk_super))
2082 if (bdev_is_zoned(bdev)) {
2083 btrfs_reset_sb_log_zones(bdev, copy_num);
2087 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
2089 page = virt_to_page(disk_super);
2090 set_page_dirty(page);
2092 /* write_on_page() unlocks the page */
2093 ret = write_one_page(page);
2096 "error clearing superblock number %d (%d)",
2098 btrfs_release_disk_super(disk_super);
2102 /* Notify udev that device has changed */
2103 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2105 /* Update ctime/mtime for device path for libblkid */
2106 update_dev_time(device_path);
2109 int btrfs_rm_device(struct btrfs_fs_info *fs_info,
2110 struct btrfs_dev_lookup_args *args,
2111 struct block_device **bdev, fmode_t *mode)
2113 struct btrfs_trans_handle *trans;
2114 struct btrfs_device *device;
2115 struct btrfs_fs_devices *cur_devices;
2116 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2120 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2121 btrfs_err(fs_info, "device remove not supported on extent tree v2 yet");
2126 * The device list in fs_devices is accessed without locks (neither
2127 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2128 * filesystem and another device rm cannot run.
2130 num_devices = btrfs_num_devices(fs_info);
2132 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2136 device = btrfs_find_device(fs_info->fs_devices, args);
2139 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2145 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2146 btrfs_warn_in_rcu(fs_info,
2147 "cannot remove device %s (devid %llu) due to active swapfile",
2148 rcu_str_deref(device->name), device->devid);
2152 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
2153 return BTRFS_ERROR_DEV_TGT_REPLACE;
2155 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2156 fs_info->fs_devices->rw_devices == 1)
2157 return BTRFS_ERROR_DEV_ONLY_WRITABLE;
2159 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2160 mutex_lock(&fs_info->chunk_mutex);
2161 list_del_init(&device->dev_alloc_list);
2162 device->fs_devices->rw_devices--;
2163 mutex_unlock(&fs_info->chunk_mutex);
2166 ret = btrfs_shrink_device(device, 0);
2170 trans = btrfs_start_transaction(fs_info->chunk_root, 0);
2171 if (IS_ERR(trans)) {
2172 ret = PTR_ERR(trans);
2176 ret = btrfs_rm_dev_item(trans, device);
2178 /* Any error in dev item removal is critical */
2180 "failed to remove device item for devid %llu: %d",
2181 device->devid, ret);
2182 btrfs_abort_transaction(trans, ret);
2183 btrfs_end_transaction(trans);
2187 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2188 btrfs_scrub_cancel_dev(device);
2191 * the device list mutex makes sure that we don't change
2192 * the device list while someone else is writing out all
2193 * the device supers. Whoever is writing all supers, should
2194 * lock the device list mutex before getting the number of
2195 * devices in the super block (super_copy). Conversely,
2196 * whoever updates the number of devices in the super block
2197 * (super_copy) should hold the device list mutex.
2201 * In normal cases the cur_devices == fs_devices. But in case
2202 * of deleting a seed device, the cur_devices should point to
2203 * its own fs_devices listed under the fs_devices->seed_list.
2205 cur_devices = device->fs_devices;
2206 mutex_lock(&fs_devices->device_list_mutex);
2207 list_del_rcu(&device->dev_list);
2209 cur_devices->num_devices--;
2210 cur_devices->total_devices--;
2211 /* Update total_devices of the parent fs_devices if it's seed */
2212 if (cur_devices != fs_devices)
2213 fs_devices->total_devices--;
2215 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2216 cur_devices->missing_devices--;
2218 btrfs_assign_next_active_device(device, NULL);
2221 cur_devices->open_devices--;
2222 /* remove sysfs entry */
2223 btrfs_sysfs_remove_device(device);
2226 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2227 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2228 mutex_unlock(&fs_devices->device_list_mutex);
2231 * At this point, the device is zero sized and detached from the
2232 * devices list. All that's left is to zero out the old supers and
2235 * We cannot call btrfs_close_bdev() here because we're holding the sb
2236 * write lock, and blkdev_put() will pull in the ->open_mutex on the
2237 * block device and it's dependencies. Instead just flush the device
2238 * and let the caller do the final blkdev_put.
2240 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2241 btrfs_scratch_superblocks(fs_info, device->bdev,
2244 sync_blockdev(device->bdev);
2245 invalidate_bdev(device->bdev);
2249 *bdev = device->bdev;
2250 *mode = device->mode;
2252 btrfs_free_device(device);
2255 * This can happen if cur_devices is the private seed devices list. We
2256 * cannot call close_fs_devices() here because it expects the uuid_mutex
2257 * to be held, but in fact we don't need that for the private
2258 * seed_devices, we can simply decrement cur_devices->opened and then
2259 * remove it from our list and free the fs_devices.
2261 if (cur_devices->num_devices == 0) {
2262 list_del_init(&cur_devices->seed_list);
2263 ASSERT(cur_devices->opened == 1);
2264 cur_devices->opened--;
2265 free_fs_devices(cur_devices);
2268 ret = btrfs_commit_transaction(trans);
2273 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2274 mutex_lock(&fs_info->chunk_mutex);
2275 list_add(&device->dev_alloc_list,
2276 &fs_devices->alloc_list);
2277 device->fs_devices->rw_devices++;
2278 mutex_unlock(&fs_info->chunk_mutex);
2283 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2285 struct btrfs_fs_devices *fs_devices;
2287 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2290 * in case of fs with no seed, srcdev->fs_devices will point
2291 * to fs_devices of fs_info. However when the dev being replaced is
2292 * a seed dev it will point to the seed's local fs_devices. In short
2293 * srcdev will have its correct fs_devices in both the cases.
2295 fs_devices = srcdev->fs_devices;
2297 list_del_rcu(&srcdev->dev_list);
2298 list_del(&srcdev->dev_alloc_list);
2299 fs_devices->num_devices--;
2300 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2301 fs_devices->missing_devices--;
2303 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2304 fs_devices->rw_devices--;
2307 fs_devices->open_devices--;
2310 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2312 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2314 mutex_lock(&uuid_mutex);
2316 btrfs_close_bdev(srcdev);
2318 btrfs_free_device(srcdev);
2320 /* if this is no devs we rather delete the fs_devices */
2321 if (!fs_devices->num_devices) {
2323 * On a mounted FS, num_devices can't be zero unless it's a
2324 * seed. In case of a seed device being replaced, the replace
2325 * target added to the sprout FS, so there will be no more
2326 * device left under the seed FS.
2328 ASSERT(fs_devices->seeding);
2330 list_del_init(&fs_devices->seed_list);
2331 close_fs_devices(fs_devices);
2332 free_fs_devices(fs_devices);
2334 mutex_unlock(&uuid_mutex);
2337 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2339 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2341 mutex_lock(&fs_devices->device_list_mutex);
2343 btrfs_sysfs_remove_device(tgtdev);
2346 fs_devices->open_devices--;
2348 fs_devices->num_devices--;
2350 btrfs_assign_next_active_device(tgtdev, NULL);
2352 list_del_rcu(&tgtdev->dev_list);
2354 mutex_unlock(&fs_devices->device_list_mutex);
2356 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2359 btrfs_close_bdev(tgtdev);
2361 btrfs_free_device(tgtdev);
2365 * Populate args from device at path
2367 * @fs_info: the filesystem
2368 * @args: the args to populate
2369 * @path: the path to the device
2371 * This will read the super block of the device at @path and populate @args with
2372 * the devid, fsid, and uuid. This is meant to be used for ioctls that need to
2373 * lookup a device to operate on, but need to do it before we take any locks.
2374 * This properly handles the special case of "missing" that a user may pass in,
2375 * and does some basic sanity checks. The caller must make sure that @path is
2376 * properly NUL terminated before calling in, and must call
2377 * btrfs_put_dev_args_from_path() in order to free up the temporary fsid and
2380 * Return: 0 for success, -errno for failure
2382 int btrfs_get_dev_args_from_path(struct btrfs_fs_info *fs_info,
2383 struct btrfs_dev_lookup_args *args,
2386 struct btrfs_super_block *disk_super;
2387 struct block_device *bdev;
2390 if (!path || !path[0])
2392 if (!strcmp(path, "missing")) {
2393 args->missing = true;
2397 args->uuid = kzalloc(BTRFS_UUID_SIZE, GFP_KERNEL);
2398 args->fsid = kzalloc(BTRFS_FSID_SIZE, GFP_KERNEL);
2399 if (!args->uuid || !args->fsid) {
2400 btrfs_put_dev_args_from_path(args);
2404 ret = btrfs_get_bdev_and_sb(path, FMODE_READ, fs_info->bdev_holder, 0,
2405 &bdev, &disk_super);
2407 btrfs_put_dev_args_from_path(args);
2411 args->devid = btrfs_stack_device_id(&disk_super->dev_item);
2412 memcpy(args->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE);
2413 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2414 memcpy(args->fsid, disk_super->metadata_uuid, BTRFS_FSID_SIZE);
2416 memcpy(args->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
2417 btrfs_release_disk_super(disk_super);
2418 blkdev_put(bdev, FMODE_READ);
2423 * Only use this jointly with btrfs_get_dev_args_from_path() because we will
2424 * allocate our ->uuid and ->fsid pointers, everybody else uses local variables
2425 * that don't need to be freed.
2427 void btrfs_put_dev_args_from_path(struct btrfs_dev_lookup_args *args)
2435 struct btrfs_device *btrfs_find_device_by_devspec(
2436 struct btrfs_fs_info *fs_info, u64 devid,
2437 const char *device_path)
2439 BTRFS_DEV_LOOKUP_ARGS(args);
2440 struct btrfs_device *device;
2445 device = btrfs_find_device(fs_info->fs_devices, &args);
2447 return ERR_PTR(-ENOENT);
2451 ret = btrfs_get_dev_args_from_path(fs_info, &args, device_path);
2453 return ERR_PTR(ret);
2454 device = btrfs_find_device(fs_info->fs_devices, &args);
2455 btrfs_put_dev_args_from_path(&args);
2457 return ERR_PTR(-ENOENT);
2461 static struct btrfs_fs_devices *btrfs_init_sprout(struct btrfs_fs_info *fs_info)
2463 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2464 struct btrfs_fs_devices *old_devices;
2465 struct btrfs_fs_devices *seed_devices;
2467 lockdep_assert_held(&uuid_mutex);
2468 if (!fs_devices->seeding)
2469 return ERR_PTR(-EINVAL);
2472 * Private copy of the seed devices, anchored at
2473 * fs_info->fs_devices->seed_list
2475 seed_devices = alloc_fs_devices(NULL, NULL);
2476 if (IS_ERR(seed_devices))
2477 return seed_devices;
2480 * It's necessary to retain a copy of the original seed fs_devices in
2481 * fs_uuids so that filesystems which have been seeded can successfully
2482 * reference the seed device from open_seed_devices. This also supports
2485 old_devices = clone_fs_devices(fs_devices);
2486 if (IS_ERR(old_devices)) {
2487 kfree(seed_devices);
2491 list_add(&old_devices->fs_list, &fs_uuids);
2493 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2494 seed_devices->opened = 1;
2495 INIT_LIST_HEAD(&seed_devices->devices);
2496 INIT_LIST_HEAD(&seed_devices->alloc_list);
2497 mutex_init(&seed_devices->device_list_mutex);
2499 return seed_devices;
2503 * Splice seed devices into the sprout fs_devices.
2504 * Generate a new fsid for the sprouted read-write filesystem.
2506 static void btrfs_setup_sprout(struct btrfs_fs_info *fs_info,
2507 struct btrfs_fs_devices *seed_devices)
2509 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2510 struct btrfs_super_block *disk_super = fs_info->super_copy;
2511 struct btrfs_device *device;
2515 * We are updating the fsid, the thread leading to device_list_add()
2516 * could race, so uuid_mutex is needed.
2518 lockdep_assert_held(&uuid_mutex);
2521 * The threads listed below may traverse dev_list but can do that without
2522 * device_list_mutex:
2523 * - All device ops and balance - as we are in btrfs_exclop_start.
2524 * - Various dev_list readers - are using RCU.
2525 * - btrfs_ioctl_fitrim() - is using RCU.
2527 * For-read threads as below are using device_list_mutex:
2528 * - Readonly scrub btrfs_scrub_dev()
2529 * - Readonly scrub btrfs_scrub_progress()
2530 * - btrfs_get_dev_stats()
2532 lockdep_assert_held(&fs_devices->device_list_mutex);
2534 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2536 list_for_each_entry(device, &seed_devices->devices, dev_list)
2537 device->fs_devices = seed_devices;
2539 fs_devices->seeding = false;
2540 fs_devices->num_devices = 0;
2541 fs_devices->open_devices = 0;
2542 fs_devices->missing_devices = 0;
2543 fs_devices->rotating = false;
2544 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2546 generate_random_uuid(fs_devices->fsid);
2547 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2548 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2550 super_flags = btrfs_super_flags(disk_super) &
2551 ~BTRFS_SUPER_FLAG_SEEDING;
2552 btrfs_set_super_flags(disk_super, super_flags);
2556 * Store the expected generation for seed devices in device items.
2558 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2560 BTRFS_DEV_LOOKUP_ARGS(args);
2561 struct btrfs_fs_info *fs_info = trans->fs_info;
2562 struct btrfs_root *root = fs_info->chunk_root;
2563 struct btrfs_path *path;
2564 struct extent_buffer *leaf;
2565 struct btrfs_dev_item *dev_item;
2566 struct btrfs_device *device;
2567 struct btrfs_key key;
2568 u8 fs_uuid[BTRFS_FSID_SIZE];
2569 u8 dev_uuid[BTRFS_UUID_SIZE];
2572 path = btrfs_alloc_path();
2576 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2578 key.type = BTRFS_DEV_ITEM_KEY;
2581 btrfs_reserve_chunk_metadata(trans, false);
2582 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2583 btrfs_trans_release_chunk_metadata(trans);
2587 leaf = path->nodes[0];
2589 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2590 ret = btrfs_next_leaf(root, path);
2595 leaf = path->nodes[0];
2596 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2597 btrfs_release_path(path);
2601 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2602 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2603 key.type != BTRFS_DEV_ITEM_KEY)
2606 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2607 struct btrfs_dev_item);
2608 args.devid = btrfs_device_id(leaf, dev_item);
2609 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2611 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2613 args.uuid = dev_uuid;
2614 args.fsid = fs_uuid;
2615 device = btrfs_find_device(fs_info->fs_devices, &args);
2616 BUG_ON(!device); /* Logic error */
2618 if (device->fs_devices->seeding) {
2619 btrfs_set_device_generation(leaf, dev_item,
2620 device->generation);
2621 btrfs_mark_buffer_dirty(leaf);
2629 btrfs_free_path(path);
2633 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2635 struct btrfs_root *root = fs_info->dev_root;
2636 struct btrfs_trans_handle *trans;
2637 struct btrfs_device *device;
2638 struct block_device *bdev;
2639 struct super_block *sb = fs_info->sb;
2640 struct rcu_string *name;
2641 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2642 struct btrfs_fs_devices *seed_devices = NULL;
2643 u64 orig_super_total_bytes;
2644 u64 orig_super_num_devices;
2646 bool seeding_dev = false;
2647 bool locked = false;
2649 if (sb_rdonly(sb) && !fs_devices->seeding)
2652 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2653 fs_info->bdev_holder);
2655 return PTR_ERR(bdev);
2657 if (!btrfs_check_device_zone_type(fs_info, bdev)) {
2662 if (fs_devices->seeding) {
2664 down_write(&sb->s_umount);
2665 mutex_lock(&uuid_mutex);
2669 sync_blockdev(bdev);
2672 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2673 if (device->bdev == bdev) {
2681 device = btrfs_alloc_device(fs_info, NULL, NULL);
2682 if (IS_ERR(device)) {
2683 /* we can safely leave the fs_devices entry around */
2684 ret = PTR_ERR(device);
2688 name = rcu_string_strdup(device_path, GFP_KERNEL);
2691 goto error_free_device;
2693 rcu_assign_pointer(device->name, name);
2695 device->fs_info = fs_info;
2696 device->bdev = bdev;
2697 ret = lookup_bdev(device_path, &device->devt);
2699 goto error_free_device;
2701 ret = btrfs_get_dev_zone_info(device, false);
2703 goto error_free_device;
2705 trans = btrfs_start_transaction(root, 0);
2706 if (IS_ERR(trans)) {
2707 ret = PTR_ERR(trans);
2708 goto error_free_zone;
2711 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2712 device->generation = trans->transid;
2713 device->io_width = fs_info->sectorsize;
2714 device->io_align = fs_info->sectorsize;
2715 device->sector_size = fs_info->sectorsize;
2716 device->total_bytes =
2717 round_down(bdev_nr_bytes(bdev), fs_info->sectorsize);
2718 device->disk_total_bytes = device->total_bytes;
2719 device->commit_total_bytes = device->total_bytes;
2720 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2721 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2722 device->mode = FMODE_EXCL;
2723 device->dev_stats_valid = 1;
2724 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2727 btrfs_clear_sb_rdonly(sb);
2729 /* GFP_KERNEL allocation must not be under device_list_mutex */
2730 seed_devices = btrfs_init_sprout(fs_info);
2731 if (IS_ERR(seed_devices)) {
2732 ret = PTR_ERR(seed_devices);
2733 btrfs_abort_transaction(trans, ret);
2738 mutex_lock(&fs_devices->device_list_mutex);
2740 btrfs_setup_sprout(fs_info, seed_devices);
2741 btrfs_assign_next_active_device(fs_info->fs_devices->latest_dev,
2745 device->fs_devices = fs_devices;
2747 mutex_lock(&fs_info->chunk_mutex);
2748 list_add_rcu(&device->dev_list, &fs_devices->devices);
2749 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2750 fs_devices->num_devices++;
2751 fs_devices->open_devices++;
2752 fs_devices->rw_devices++;
2753 fs_devices->total_devices++;
2754 fs_devices->total_rw_bytes += device->total_bytes;
2756 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2758 if (!bdev_nonrot(bdev))
2759 fs_devices->rotating = true;
2761 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2762 btrfs_set_super_total_bytes(fs_info->super_copy,
2763 round_down(orig_super_total_bytes + device->total_bytes,
2764 fs_info->sectorsize));
2766 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2767 btrfs_set_super_num_devices(fs_info->super_copy,
2768 orig_super_num_devices + 1);
2771 * we've got more storage, clear any full flags on the space
2774 btrfs_clear_space_info_full(fs_info);
2776 mutex_unlock(&fs_info->chunk_mutex);
2778 /* Add sysfs device entry */
2779 btrfs_sysfs_add_device(device);
2781 mutex_unlock(&fs_devices->device_list_mutex);
2784 mutex_lock(&fs_info->chunk_mutex);
2785 ret = init_first_rw_device(trans);
2786 mutex_unlock(&fs_info->chunk_mutex);
2788 btrfs_abort_transaction(trans, ret);
2793 ret = btrfs_add_dev_item(trans, device);
2795 btrfs_abort_transaction(trans, ret);
2800 ret = btrfs_finish_sprout(trans);
2802 btrfs_abort_transaction(trans, ret);
2807 * fs_devices now represents the newly sprouted filesystem and
2808 * its fsid has been changed by btrfs_sprout_splice().
2810 btrfs_sysfs_update_sprout_fsid(fs_devices);
2813 ret = btrfs_commit_transaction(trans);
2816 mutex_unlock(&uuid_mutex);
2817 up_write(&sb->s_umount);
2820 if (ret) /* transaction commit */
2823 ret = btrfs_relocate_sys_chunks(fs_info);
2825 btrfs_handle_fs_error(fs_info, ret,
2826 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2827 trans = btrfs_attach_transaction(root);
2828 if (IS_ERR(trans)) {
2829 if (PTR_ERR(trans) == -ENOENT)
2831 ret = PTR_ERR(trans);
2835 ret = btrfs_commit_transaction(trans);
2839 * Now that we have written a new super block to this device, check all
2840 * other fs_devices list if device_path alienates any other scanned
2842 * We can ignore the return value as it typically returns -EINVAL and
2843 * only succeeds if the device was an alien.
2845 btrfs_forget_devices(device->devt);
2847 /* Update ctime/mtime for blkid or udev */
2848 update_dev_time(device_path);
2853 btrfs_sysfs_remove_device(device);
2854 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2855 mutex_lock(&fs_info->chunk_mutex);
2856 list_del_rcu(&device->dev_list);
2857 list_del(&device->dev_alloc_list);
2858 fs_info->fs_devices->num_devices--;
2859 fs_info->fs_devices->open_devices--;
2860 fs_info->fs_devices->rw_devices--;
2861 fs_info->fs_devices->total_devices--;
2862 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2863 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2864 btrfs_set_super_total_bytes(fs_info->super_copy,
2865 orig_super_total_bytes);
2866 btrfs_set_super_num_devices(fs_info->super_copy,
2867 orig_super_num_devices);
2868 mutex_unlock(&fs_info->chunk_mutex);
2869 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2872 btrfs_set_sb_rdonly(sb);
2874 btrfs_end_transaction(trans);
2876 btrfs_destroy_dev_zone_info(device);
2878 btrfs_free_device(device);
2880 blkdev_put(bdev, FMODE_EXCL);
2882 mutex_unlock(&uuid_mutex);
2883 up_write(&sb->s_umount);
2888 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2889 struct btrfs_device *device)
2892 struct btrfs_path *path;
2893 struct btrfs_root *root = device->fs_info->chunk_root;
2894 struct btrfs_dev_item *dev_item;
2895 struct extent_buffer *leaf;
2896 struct btrfs_key key;
2898 path = btrfs_alloc_path();
2902 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2903 key.type = BTRFS_DEV_ITEM_KEY;
2904 key.offset = device->devid;
2906 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2915 leaf = path->nodes[0];
2916 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2918 btrfs_set_device_id(leaf, dev_item, device->devid);
2919 btrfs_set_device_type(leaf, dev_item, device->type);
2920 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2921 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2922 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2923 btrfs_set_device_total_bytes(leaf, dev_item,
2924 btrfs_device_get_disk_total_bytes(device));
2925 btrfs_set_device_bytes_used(leaf, dev_item,
2926 btrfs_device_get_bytes_used(device));
2927 btrfs_mark_buffer_dirty(leaf);
2930 btrfs_free_path(path);
2934 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2935 struct btrfs_device *device, u64 new_size)
2937 struct btrfs_fs_info *fs_info = device->fs_info;
2938 struct btrfs_super_block *super_copy = fs_info->super_copy;
2943 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2946 new_size = round_down(new_size, fs_info->sectorsize);
2948 mutex_lock(&fs_info->chunk_mutex);
2949 old_total = btrfs_super_total_bytes(super_copy);
2950 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2952 if (new_size <= device->total_bytes ||
2953 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2954 mutex_unlock(&fs_info->chunk_mutex);
2958 btrfs_set_super_total_bytes(super_copy,
2959 round_down(old_total + diff, fs_info->sectorsize));
2960 device->fs_devices->total_rw_bytes += diff;
2962 btrfs_device_set_total_bytes(device, new_size);
2963 btrfs_device_set_disk_total_bytes(device, new_size);
2964 btrfs_clear_space_info_full(device->fs_info);
2965 if (list_empty(&device->post_commit_list))
2966 list_add_tail(&device->post_commit_list,
2967 &trans->transaction->dev_update_list);
2968 mutex_unlock(&fs_info->chunk_mutex);
2970 btrfs_reserve_chunk_metadata(trans, false);
2971 ret = btrfs_update_device(trans, device);
2972 btrfs_trans_release_chunk_metadata(trans);
2977 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2979 struct btrfs_fs_info *fs_info = trans->fs_info;
2980 struct btrfs_root *root = fs_info->chunk_root;
2982 struct btrfs_path *path;
2983 struct btrfs_key key;
2985 path = btrfs_alloc_path();
2989 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2990 key.offset = chunk_offset;
2991 key.type = BTRFS_CHUNK_ITEM_KEY;
2993 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2996 else if (ret > 0) { /* Logic error or corruption */
2997 btrfs_handle_fs_error(fs_info, -ENOENT,
2998 "Failed lookup while freeing chunk.");
3003 ret = btrfs_del_item(trans, root, path);
3005 btrfs_handle_fs_error(fs_info, ret,
3006 "Failed to delete chunk item.");
3008 btrfs_free_path(path);
3012 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3014 struct btrfs_super_block *super_copy = fs_info->super_copy;
3015 struct btrfs_disk_key *disk_key;
3016 struct btrfs_chunk *chunk;
3023 struct btrfs_key key;
3025 lockdep_assert_held(&fs_info->chunk_mutex);
3026 array_size = btrfs_super_sys_array_size(super_copy);
3028 ptr = super_copy->sys_chunk_array;
3031 while (cur < array_size) {
3032 disk_key = (struct btrfs_disk_key *)ptr;
3033 btrfs_disk_key_to_cpu(&key, disk_key);
3035 len = sizeof(*disk_key);
3037 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3038 chunk = (struct btrfs_chunk *)(ptr + len);
3039 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
3040 len += btrfs_chunk_item_size(num_stripes);
3045 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
3046 key.offset == chunk_offset) {
3047 memmove(ptr, ptr + len, array_size - (cur + len));
3049 btrfs_set_super_sys_array_size(super_copy, array_size);
3059 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
3060 * @logical: Logical block offset in bytes.
3061 * @length: Length of extent in bytes.
3063 * Return: Chunk mapping or ERR_PTR.
3065 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
3066 u64 logical, u64 length)
3068 struct extent_map_tree *em_tree;
3069 struct extent_map *em;
3071 em_tree = &fs_info->mapping_tree;
3072 read_lock(&em_tree->lock);
3073 em = lookup_extent_mapping(em_tree, logical, length);
3074 read_unlock(&em_tree->lock);
3078 "unable to find chunk map for logical %llu length %llu",
3080 return ERR_PTR(-EINVAL);
3083 if (em->start > logical || em->start + em->len <= logical) {
3085 "found a bad chunk map, wanted %llu-%llu, found %llu-%llu",
3086 logical, logical + length, em->start, em->start + em->len);
3087 free_extent_map(em);
3088 return ERR_PTR(-EINVAL);
3091 /* callers are responsible for dropping em's ref. */
3095 static int remove_chunk_item(struct btrfs_trans_handle *trans,
3096 struct map_lookup *map, u64 chunk_offset)
3101 * Removing chunk items and updating the device items in the chunks btree
3102 * requires holding the chunk_mutex.
3103 * See the comment at btrfs_chunk_alloc() for the details.
3105 lockdep_assert_held(&trans->fs_info->chunk_mutex);
3107 for (i = 0; i < map->num_stripes; i++) {
3110 ret = btrfs_update_device(trans, map->stripes[i].dev);
3115 return btrfs_free_chunk(trans, chunk_offset);
3118 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3120 struct btrfs_fs_info *fs_info = trans->fs_info;
3121 struct extent_map *em;
3122 struct map_lookup *map;
3123 u64 dev_extent_len = 0;
3125 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3127 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3130 * This is a logic error, but we don't want to just rely on the
3131 * user having built with ASSERT enabled, so if ASSERT doesn't
3132 * do anything we still error out.
3137 map = em->map_lookup;
3140 * First delete the device extent items from the devices btree.
3141 * We take the device_list_mutex to avoid racing with the finishing phase
3142 * of a device replace operation. See the comment below before acquiring
3143 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3144 * because that can result in a deadlock when deleting the device extent
3145 * items from the devices btree - COWing an extent buffer from the btree
3146 * may result in allocating a new metadata chunk, which would attempt to
3147 * lock again fs_info->chunk_mutex.
3149 mutex_lock(&fs_devices->device_list_mutex);
3150 for (i = 0; i < map->num_stripes; i++) {
3151 struct btrfs_device *device = map->stripes[i].dev;
3152 ret = btrfs_free_dev_extent(trans, device,
3153 map->stripes[i].physical,
3156 mutex_unlock(&fs_devices->device_list_mutex);
3157 btrfs_abort_transaction(trans, ret);
3161 if (device->bytes_used > 0) {
3162 mutex_lock(&fs_info->chunk_mutex);
3163 btrfs_device_set_bytes_used(device,
3164 device->bytes_used - dev_extent_len);
3165 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3166 btrfs_clear_space_info_full(fs_info);
3167 mutex_unlock(&fs_info->chunk_mutex);
3170 mutex_unlock(&fs_devices->device_list_mutex);
3173 * We acquire fs_info->chunk_mutex for 2 reasons:
3175 * 1) Just like with the first phase of the chunk allocation, we must
3176 * reserve system space, do all chunk btree updates and deletions, and
3177 * update the system chunk array in the superblock while holding this
3178 * mutex. This is for similar reasons as explained on the comment at
3179 * the top of btrfs_chunk_alloc();
3181 * 2) Prevent races with the final phase of a device replace operation
3182 * that replaces the device object associated with the map's stripes,
3183 * because the device object's id can change at any time during that
3184 * final phase of the device replace operation
3185 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3186 * replaced device and then see it with an ID of
3187 * BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3188 * the device item, which does not exists on the chunk btree.
3189 * The finishing phase of device replace acquires both the
3190 * device_list_mutex and the chunk_mutex, in that order, so we are
3191 * safe by just acquiring the chunk_mutex.
3193 trans->removing_chunk = true;
3194 mutex_lock(&fs_info->chunk_mutex);
3196 check_system_chunk(trans, map->type);
3198 ret = remove_chunk_item(trans, map, chunk_offset);
3200 * Normally we should not get -ENOSPC since we reserved space before
3201 * through the call to check_system_chunk().
3203 * Despite our system space_info having enough free space, we may not
3204 * be able to allocate extents from its block groups, because all have
3205 * an incompatible profile, which will force us to allocate a new system
3206 * block group with the right profile, or right after we called
3207 * check_system_space() above, a scrub turned the only system block group
3208 * with enough free space into RO mode.
3209 * This is explained with more detail at do_chunk_alloc().
3211 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3213 if (ret == -ENOSPC) {
3214 const u64 sys_flags = btrfs_system_alloc_profile(fs_info);
3215 struct btrfs_block_group *sys_bg;
3217 sys_bg = btrfs_create_chunk(trans, sys_flags);
3218 if (IS_ERR(sys_bg)) {
3219 ret = PTR_ERR(sys_bg);
3220 btrfs_abort_transaction(trans, ret);
3224 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3226 btrfs_abort_transaction(trans, ret);
3230 ret = remove_chunk_item(trans, map, chunk_offset);
3232 btrfs_abort_transaction(trans, ret);
3236 btrfs_abort_transaction(trans, ret);
3240 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3242 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3243 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3245 btrfs_abort_transaction(trans, ret);
3250 mutex_unlock(&fs_info->chunk_mutex);
3251 trans->removing_chunk = false;
3254 * We are done with chunk btree updates and deletions, so release the
3255 * system space we previously reserved (with check_system_chunk()).
3257 btrfs_trans_release_chunk_metadata(trans);
3259 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3261 btrfs_abort_transaction(trans, ret);
3266 if (trans->removing_chunk) {
3267 mutex_unlock(&fs_info->chunk_mutex);
3268 trans->removing_chunk = false;
3271 free_extent_map(em);
3275 int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3277 struct btrfs_root *root = fs_info->chunk_root;
3278 struct btrfs_trans_handle *trans;
3279 struct btrfs_block_group *block_group;
3283 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3285 "relocate: not supported on extent tree v2 yet");
3290 * Prevent races with automatic removal of unused block groups.
3291 * After we relocate and before we remove the chunk with offset
3292 * chunk_offset, automatic removal of the block group can kick in,
3293 * resulting in a failure when calling btrfs_remove_chunk() below.
3295 * Make sure to acquire this mutex before doing a tree search (dev
3296 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3297 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3298 * we release the path used to search the chunk/dev tree and before
3299 * the current task acquires this mutex and calls us.
3301 lockdep_assert_held(&fs_info->reclaim_bgs_lock);
3303 /* step one, relocate all the extents inside this chunk */
3304 btrfs_scrub_pause(fs_info);
3305 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3306 btrfs_scrub_continue(fs_info);
3309 * If we had a transaction abort, stop all running scrubs.
3310 * See transaction.c:cleanup_transaction() why we do it here.
3312 if (BTRFS_FS_ERROR(fs_info))
3313 btrfs_scrub_cancel(fs_info);
3317 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3320 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3321 length = block_group->length;
3322 btrfs_put_block_group(block_group);
3325 * On a zoned file system, discard the whole block group, this will
3326 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3327 * resetting the zone fails, don't treat it as a fatal problem from the
3328 * filesystem's point of view.
3330 if (btrfs_is_zoned(fs_info)) {
3331 ret = btrfs_discard_extent(fs_info, chunk_offset, length, NULL);
3334 "failed to reset zone %llu after relocation",
3338 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3340 if (IS_ERR(trans)) {
3341 ret = PTR_ERR(trans);
3342 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3347 * step two, delete the device extents and the
3348 * chunk tree entries
3350 ret = btrfs_remove_chunk(trans, chunk_offset);
3351 btrfs_end_transaction(trans);
3355 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3357 struct btrfs_root *chunk_root = fs_info->chunk_root;
3358 struct btrfs_path *path;
3359 struct extent_buffer *leaf;
3360 struct btrfs_chunk *chunk;
3361 struct btrfs_key key;
3362 struct btrfs_key found_key;
3364 bool retried = false;
3368 path = btrfs_alloc_path();
3373 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3374 key.offset = (u64)-1;
3375 key.type = BTRFS_CHUNK_ITEM_KEY;
3378 mutex_lock(&fs_info->reclaim_bgs_lock);
3379 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3381 mutex_unlock(&fs_info->reclaim_bgs_lock);
3386 * On the first search we would find chunk tree with
3387 * offset -1, which is not possible. On subsequent
3388 * loops this would find an existing item on an invalid
3389 * offset (one less than the previous one, wrong
3390 * alignment and size).
3396 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3399 mutex_unlock(&fs_info->reclaim_bgs_lock);
3405 leaf = path->nodes[0];
3406 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3408 chunk = btrfs_item_ptr(leaf, path->slots[0],
3409 struct btrfs_chunk);
3410 chunk_type = btrfs_chunk_type(leaf, chunk);
3411 btrfs_release_path(path);
3413 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3414 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3420 mutex_unlock(&fs_info->reclaim_bgs_lock);
3422 if (found_key.offset == 0)
3424 key.offset = found_key.offset - 1;
3427 if (failed && !retried) {
3431 } else if (WARN_ON(failed && retried)) {
3435 btrfs_free_path(path);
3440 * return 1 : allocate a data chunk successfully,
3441 * return <0: errors during allocating a data chunk,
3442 * return 0 : no need to allocate a data chunk.
3444 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3447 struct btrfs_block_group *cache;
3451 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3453 chunk_type = cache->flags;
3454 btrfs_put_block_group(cache);
3456 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3459 spin_lock(&fs_info->data_sinfo->lock);
3460 bytes_used = fs_info->data_sinfo->bytes_used;
3461 spin_unlock(&fs_info->data_sinfo->lock);
3464 struct btrfs_trans_handle *trans;
3467 trans = btrfs_join_transaction(fs_info->tree_root);
3469 return PTR_ERR(trans);
3471 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3472 btrfs_end_transaction(trans);
3481 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3482 struct btrfs_balance_control *bctl)
3484 struct btrfs_root *root = fs_info->tree_root;
3485 struct btrfs_trans_handle *trans;
3486 struct btrfs_balance_item *item;
3487 struct btrfs_disk_balance_args disk_bargs;
3488 struct btrfs_path *path;
3489 struct extent_buffer *leaf;
3490 struct btrfs_key key;
3493 path = btrfs_alloc_path();
3497 trans = btrfs_start_transaction(root, 0);
3498 if (IS_ERR(trans)) {
3499 btrfs_free_path(path);
3500 return PTR_ERR(trans);
3503 key.objectid = BTRFS_BALANCE_OBJECTID;
3504 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3507 ret = btrfs_insert_empty_item(trans, root, path, &key,
3512 leaf = path->nodes[0];
3513 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3515 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3517 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3518 btrfs_set_balance_data(leaf, item, &disk_bargs);
3519 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3520 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3521 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3522 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3524 btrfs_set_balance_flags(leaf, item, bctl->flags);
3526 btrfs_mark_buffer_dirty(leaf);
3528 btrfs_free_path(path);
3529 err = btrfs_commit_transaction(trans);
3535 static int del_balance_item(struct btrfs_fs_info *fs_info)
3537 struct btrfs_root *root = fs_info->tree_root;
3538 struct btrfs_trans_handle *trans;
3539 struct btrfs_path *path;
3540 struct btrfs_key key;
3543 path = btrfs_alloc_path();
3547 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3548 if (IS_ERR(trans)) {
3549 btrfs_free_path(path);
3550 return PTR_ERR(trans);
3553 key.objectid = BTRFS_BALANCE_OBJECTID;
3554 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3557 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3565 ret = btrfs_del_item(trans, root, path);
3567 btrfs_free_path(path);
3568 err = btrfs_commit_transaction(trans);
3575 * This is a heuristic used to reduce the number of chunks balanced on
3576 * resume after balance was interrupted.
3578 static void update_balance_args(struct btrfs_balance_control *bctl)
3581 * Turn on soft mode for chunk types that were being converted.
3583 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3584 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3585 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3586 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3587 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3588 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3591 * Turn on usage filter if is not already used. The idea is
3592 * that chunks that we have already balanced should be
3593 * reasonably full. Don't do it for chunks that are being
3594 * converted - that will keep us from relocating unconverted
3595 * (albeit full) chunks.
3597 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3598 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3599 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3600 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3601 bctl->data.usage = 90;
3603 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3604 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3605 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3606 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3607 bctl->sys.usage = 90;
3609 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3610 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3611 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3612 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3613 bctl->meta.usage = 90;
3618 * Clear the balance status in fs_info and delete the balance item from disk.
3620 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3622 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3625 BUG_ON(!fs_info->balance_ctl);
3627 spin_lock(&fs_info->balance_lock);
3628 fs_info->balance_ctl = NULL;
3629 spin_unlock(&fs_info->balance_lock);
3632 ret = del_balance_item(fs_info);
3634 btrfs_handle_fs_error(fs_info, ret, NULL);
3638 * Balance filters. Return 1 if chunk should be filtered out
3639 * (should not be balanced).
3641 static int chunk_profiles_filter(u64 chunk_type,
3642 struct btrfs_balance_args *bargs)
3644 chunk_type = chunk_to_extended(chunk_type) &
3645 BTRFS_EXTENDED_PROFILE_MASK;
3647 if (bargs->profiles & chunk_type)
3653 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3654 struct btrfs_balance_args *bargs)
3656 struct btrfs_block_group *cache;
3658 u64 user_thresh_min;
3659 u64 user_thresh_max;
3662 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3663 chunk_used = cache->used;
3665 if (bargs->usage_min == 0)
3666 user_thresh_min = 0;
3668 user_thresh_min = div_factor_fine(cache->length,
3671 if (bargs->usage_max == 0)
3672 user_thresh_max = 1;
3673 else if (bargs->usage_max > 100)
3674 user_thresh_max = cache->length;
3676 user_thresh_max = div_factor_fine(cache->length,
3679 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3682 btrfs_put_block_group(cache);
3686 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3687 u64 chunk_offset, struct btrfs_balance_args *bargs)
3689 struct btrfs_block_group *cache;
3690 u64 chunk_used, user_thresh;
3693 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3694 chunk_used = cache->used;
3696 if (bargs->usage_min == 0)
3698 else if (bargs->usage > 100)
3699 user_thresh = cache->length;
3701 user_thresh = div_factor_fine(cache->length, bargs->usage);
3703 if (chunk_used < user_thresh)
3706 btrfs_put_block_group(cache);
3710 static int chunk_devid_filter(struct extent_buffer *leaf,
3711 struct btrfs_chunk *chunk,
3712 struct btrfs_balance_args *bargs)
3714 struct btrfs_stripe *stripe;
3715 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3718 for (i = 0; i < num_stripes; i++) {
3719 stripe = btrfs_stripe_nr(chunk, i);
3720 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3727 static u64 calc_data_stripes(u64 type, int num_stripes)
3729 const int index = btrfs_bg_flags_to_raid_index(type);
3730 const int ncopies = btrfs_raid_array[index].ncopies;
3731 const int nparity = btrfs_raid_array[index].nparity;
3733 return (num_stripes - nparity) / ncopies;
3736 /* [pstart, pend) */
3737 static int chunk_drange_filter(struct extent_buffer *leaf,
3738 struct btrfs_chunk *chunk,
3739 struct btrfs_balance_args *bargs)
3741 struct btrfs_stripe *stripe;
3742 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3749 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3752 type = btrfs_chunk_type(leaf, chunk);
3753 factor = calc_data_stripes(type, num_stripes);
3755 for (i = 0; i < num_stripes; i++) {
3756 stripe = btrfs_stripe_nr(chunk, i);
3757 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3760 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3761 stripe_length = btrfs_chunk_length(leaf, chunk);
3762 stripe_length = div_u64(stripe_length, factor);
3764 if (stripe_offset < bargs->pend &&
3765 stripe_offset + stripe_length > bargs->pstart)
3772 /* [vstart, vend) */
3773 static int chunk_vrange_filter(struct extent_buffer *leaf,
3774 struct btrfs_chunk *chunk,
3776 struct btrfs_balance_args *bargs)
3778 if (chunk_offset < bargs->vend &&
3779 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3780 /* at least part of the chunk is inside this vrange */
3786 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3787 struct btrfs_chunk *chunk,
3788 struct btrfs_balance_args *bargs)
3790 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3792 if (bargs->stripes_min <= num_stripes
3793 && num_stripes <= bargs->stripes_max)
3799 static int chunk_soft_convert_filter(u64 chunk_type,
3800 struct btrfs_balance_args *bargs)
3802 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3805 chunk_type = chunk_to_extended(chunk_type) &
3806 BTRFS_EXTENDED_PROFILE_MASK;
3808 if (bargs->target == chunk_type)
3814 static int should_balance_chunk(struct extent_buffer *leaf,
3815 struct btrfs_chunk *chunk, u64 chunk_offset)
3817 struct btrfs_fs_info *fs_info = leaf->fs_info;
3818 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3819 struct btrfs_balance_args *bargs = NULL;
3820 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3823 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3824 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3828 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3829 bargs = &bctl->data;
3830 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3832 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3833 bargs = &bctl->meta;
3835 /* profiles filter */
3836 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3837 chunk_profiles_filter(chunk_type, bargs)) {
3842 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3843 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3845 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3846 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3851 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3852 chunk_devid_filter(leaf, chunk, bargs)) {
3856 /* drange filter, makes sense only with devid filter */
3857 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3858 chunk_drange_filter(leaf, chunk, bargs)) {
3863 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3864 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3868 /* stripes filter */
3869 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3870 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3874 /* soft profile changing mode */
3875 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3876 chunk_soft_convert_filter(chunk_type, bargs)) {
3881 * limited by count, must be the last filter
3883 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3884 if (bargs->limit == 0)
3888 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3890 * Same logic as the 'limit' filter; the minimum cannot be
3891 * determined here because we do not have the global information
3892 * about the count of all chunks that satisfy the filters.
3894 if (bargs->limit_max == 0)
3903 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3905 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3906 struct btrfs_root *chunk_root = fs_info->chunk_root;
3908 struct btrfs_chunk *chunk;
3909 struct btrfs_path *path = NULL;
3910 struct btrfs_key key;
3911 struct btrfs_key found_key;
3912 struct extent_buffer *leaf;
3915 int enospc_errors = 0;
3916 bool counting = true;
3917 /* The single value limit and min/max limits use the same bytes in the */
3918 u64 limit_data = bctl->data.limit;
3919 u64 limit_meta = bctl->meta.limit;
3920 u64 limit_sys = bctl->sys.limit;
3924 int chunk_reserved = 0;
3926 path = btrfs_alloc_path();
3932 /* zero out stat counters */
3933 spin_lock(&fs_info->balance_lock);
3934 memset(&bctl->stat, 0, sizeof(bctl->stat));
3935 spin_unlock(&fs_info->balance_lock);
3939 * The single value limit and min/max limits use the same bytes
3942 bctl->data.limit = limit_data;
3943 bctl->meta.limit = limit_meta;
3944 bctl->sys.limit = limit_sys;
3946 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3947 key.offset = (u64)-1;
3948 key.type = BTRFS_CHUNK_ITEM_KEY;
3951 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3952 atomic_read(&fs_info->balance_cancel_req)) {
3957 mutex_lock(&fs_info->reclaim_bgs_lock);
3958 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3960 mutex_unlock(&fs_info->reclaim_bgs_lock);
3965 * this shouldn't happen, it means the last relocate
3969 BUG(); /* FIXME break ? */
3971 ret = btrfs_previous_item(chunk_root, path, 0,
3972 BTRFS_CHUNK_ITEM_KEY);
3974 mutex_unlock(&fs_info->reclaim_bgs_lock);
3979 leaf = path->nodes[0];
3980 slot = path->slots[0];
3981 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3983 if (found_key.objectid != key.objectid) {
3984 mutex_unlock(&fs_info->reclaim_bgs_lock);
3988 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3989 chunk_type = btrfs_chunk_type(leaf, chunk);
3992 spin_lock(&fs_info->balance_lock);
3993 bctl->stat.considered++;
3994 spin_unlock(&fs_info->balance_lock);
3997 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3999 btrfs_release_path(path);
4001 mutex_unlock(&fs_info->reclaim_bgs_lock);
4006 mutex_unlock(&fs_info->reclaim_bgs_lock);
4007 spin_lock(&fs_info->balance_lock);
4008 bctl->stat.expected++;
4009 spin_unlock(&fs_info->balance_lock);
4011 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
4013 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
4015 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
4022 * Apply limit_min filter, no need to check if the LIMITS
4023 * filter is used, limit_min is 0 by default
4025 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
4026 count_data < bctl->data.limit_min)
4027 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
4028 count_meta < bctl->meta.limit_min)
4029 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
4030 count_sys < bctl->sys.limit_min)) {
4031 mutex_unlock(&fs_info->reclaim_bgs_lock);
4035 if (!chunk_reserved) {
4037 * We may be relocating the only data chunk we have,
4038 * which could potentially end up with losing data's
4039 * raid profile, so lets allocate an empty one in
4042 ret = btrfs_may_alloc_data_chunk(fs_info,
4045 mutex_unlock(&fs_info->reclaim_bgs_lock);
4047 } else if (ret == 1) {
4052 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
4053 mutex_unlock(&fs_info->reclaim_bgs_lock);
4054 if (ret == -ENOSPC) {
4056 } else if (ret == -ETXTBSY) {
4058 "skipping relocation of block group %llu due to active swapfile",
4064 spin_lock(&fs_info->balance_lock);
4065 bctl->stat.completed++;
4066 spin_unlock(&fs_info->balance_lock);
4069 if (found_key.offset == 0)
4071 key.offset = found_key.offset - 1;
4075 btrfs_release_path(path);
4080 btrfs_free_path(path);
4081 if (enospc_errors) {
4082 btrfs_info(fs_info, "%d enospc errors during balance",
4092 * alloc_profile_is_valid - see if a given profile is valid and reduced
4093 * @flags: profile to validate
4094 * @extended: if true @flags is treated as an extended profile
4096 static int alloc_profile_is_valid(u64 flags, int extended)
4098 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
4099 BTRFS_BLOCK_GROUP_PROFILE_MASK);
4101 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
4103 /* 1) check that all other bits are zeroed */
4107 /* 2) see if profile is reduced */
4109 return !extended; /* "0" is valid for usual profiles */
4111 return has_single_bit_set(flags);
4115 * Validate target profile against allowed profiles and return true if it's OK.
4116 * Otherwise print the error message and return false.
4118 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
4119 const struct btrfs_balance_args *bargs,
4120 u64 allowed, const char *type)
4122 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4125 /* Profile is valid and does not have bits outside of the allowed set */
4126 if (alloc_profile_is_valid(bargs->target, 1) &&
4127 (bargs->target & ~allowed) == 0)
4130 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
4131 type, btrfs_bg_type_to_raid_name(bargs->target));
4136 * Fill @buf with textual description of balance filter flags @bargs, up to
4137 * @size_buf including the terminating null. The output may be trimmed if it
4138 * does not fit into the provided buffer.
4140 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4144 u32 size_bp = size_buf;
4146 u64 flags = bargs->flags;
4147 char tmp_buf[128] = {'\0'};
4152 #define CHECK_APPEND_NOARG(a) \
4154 ret = snprintf(bp, size_bp, (a)); \
4155 if (ret < 0 || ret >= size_bp) \
4156 goto out_overflow; \
4161 #define CHECK_APPEND_1ARG(a, v1) \
4163 ret = snprintf(bp, size_bp, (a), (v1)); \
4164 if (ret < 0 || ret >= size_bp) \
4165 goto out_overflow; \
4170 #define CHECK_APPEND_2ARG(a, v1, v2) \
4172 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
4173 if (ret < 0 || ret >= size_bp) \
4174 goto out_overflow; \
4179 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4180 CHECK_APPEND_1ARG("convert=%s,",
4181 btrfs_bg_type_to_raid_name(bargs->target));
4183 if (flags & BTRFS_BALANCE_ARGS_SOFT)
4184 CHECK_APPEND_NOARG("soft,");
4186 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4187 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4189 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4192 if (flags & BTRFS_BALANCE_ARGS_USAGE)
4193 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4195 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4196 CHECK_APPEND_2ARG("usage=%u..%u,",
4197 bargs->usage_min, bargs->usage_max);
4199 if (flags & BTRFS_BALANCE_ARGS_DEVID)
4200 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4202 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4203 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4204 bargs->pstart, bargs->pend);
4206 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4207 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4208 bargs->vstart, bargs->vend);
4210 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4211 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4213 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4214 CHECK_APPEND_2ARG("limit=%u..%u,",
4215 bargs->limit_min, bargs->limit_max);
4217 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4218 CHECK_APPEND_2ARG("stripes=%u..%u,",
4219 bargs->stripes_min, bargs->stripes_max);
4221 #undef CHECK_APPEND_2ARG
4222 #undef CHECK_APPEND_1ARG
4223 #undef CHECK_APPEND_NOARG
4227 if (size_bp < size_buf)
4228 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4233 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4235 u32 size_buf = 1024;
4236 char tmp_buf[192] = {'\0'};
4239 u32 size_bp = size_buf;
4241 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4243 buf = kzalloc(size_buf, GFP_KERNEL);
4249 #define CHECK_APPEND_1ARG(a, v1) \
4251 ret = snprintf(bp, size_bp, (a), (v1)); \
4252 if (ret < 0 || ret >= size_bp) \
4253 goto out_overflow; \
4258 if (bctl->flags & BTRFS_BALANCE_FORCE)
4259 CHECK_APPEND_1ARG("%s", "-f ");
4261 if (bctl->flags & BTRFS_BALANCE_DATA) {
4262 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4263 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4266 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4267 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4268 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4271 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4272 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4273 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4276 #undef CHECK_APPEND_1ARG
4280 if (size_bp < size_buf)
4281 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4282 btrfs_info(fs_info, "balance: %s %s",
4283 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4284 "resume" : "start", buf);
4290 * Should be called with balance mutexe held
4292 int btrfs_balance(struct btrfs_fs_info *fs_info,
4293 struct btrfs_balance_control *bctl,
4294 struct btrfs_ioctl_balance_args *bargs)
4296 u64 meta_target, data_target;
4302 bool reducing_redundancy;
4303 bool paused = false;
4306 if (btrfs_fs_closing(fs_info) ||
4307 atomic_read(&fs_info->balance_pause_req) ||
4308 btrfs_should_cancel_balance(fs_info)) {
4313 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4314 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4318 * In case of mixed groups both data and meta should be picked,
4319 * and identical options should be given for both of them.
4321 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4322 if (mixed && (bctl->flags & allowed)) {
4323 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4324 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4325 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4327 "balance: mixed groups data and metadata options must be the same");
4334 * rw_devices will not change at the moment, device add/delete/replace
4337 num_devices = fs_info->fs_devices->rw_devices;
4340 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4341 * special bit for it, to make it easier to distinguish. Thus we need
4342 * to set it manually, or balance would refuse the profile.
4344 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4345 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4346 if (num_devices >= btrfs_raid_array[i].devs_min)
4347 allowed |= btrfs_raid_array[i].bg_flag;
4349 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4350 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4351 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
4357 * Allow to reduce metadata or system integrity only if force set for
4358 * profiles with redundancy (copies, parity)
4361 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4362 if (btrfs_raid_array[i].ncopies >= 2 ||
4363 btrfs_raid_array[i].tolerated_failures >= 1)
4364 allowed |= btrfs_raid_array[i].bg_flag;
4367 seq = read_seqbegin(&fs_info->profiles_lock);
4369 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4370 (fs_info->avail_system_alloc_bits & allowed) &&
4371 !(bctl->sys.target & allowed)) ||
4372 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4373 (fs_info->avail_metadata_alloc_bits & allowed) &&
4374 !(bctl->meta.target & allowed)))
4375 reducing_redundancy = true;
4377 reducing_redundancy = false;
4379 /* if we're not converting, the target field is uninitialized */
4380 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4381 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4382 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4383 bctl->data.target : fs_info->avail_data_alloc_bits;
4384 } while (read_seqretry(&fs_info->profiles_lock, seq));
4386 if (reducing_redundancy) {
4387 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4389 "balance: force reducing metadata redundancy");
4392 "balance: reduces metadata redundancy, use --force if you want this");
4398 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4399 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4401 "balance: metadata profile %s has lower redundancy than data profile %s",
4402 btrfs_bg_type_to_raid_name(meta_target),
4403 btrfs_bg_type_to_raid_name(data_target));
4406 ret = insert_balance_item(fs_info, bctl);
4407 if (ret && ret != -EEXIST)
4410 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4411 BUG_ON(ret == -EEXIST);
4412 BUG_ON(fs_info->balance_ctl);
4413 spin_lock(&fs_info->balance_lock);
4414 fs_info->balance_ctl = bctl;
4415 spin_unlock(&fs_info->balance_lock);
4417 BUG_ON(ret != -EEXIST);
4418 spin_lock(&fs_info->balance_lock);
4419 update_balance_args(bctl);
4420 spin_unlock(&fs_info->balance_lock);
4423 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4424 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4425 describe_balance_start_or_resume(fs_info);
4426 mutex_unlock(&fs_info->balance_mutex);
4428 ret = __btrfs_balance(fs_info);
4430 mutex_lock(&fs_info->balance_mutex);
4431 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req)) {
4432 btrfs_info(fs_info, "balance: paused");
4433 btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
4437 * Balance can be canceled by:
4439 * - Regular cancel request
4440 * Then ret == -ECANCELED and balance_cancel_req > 0
4442 * - Fatal signal to "btrfs" process
4443 * Either the signal caught by wait_reserve_ticket() and callers
4444 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4446 * Either way, in this case balance_cancel_req = 0, and
4447 * ret == -EINTR or ret == -ECANCELED.
4449 * So here we only check the return value to catch canceled balance.
4451 else if (ret == -ECANCELED || ret == -EINTR)
4452 btrfs_info(fs_info, "balance: canceled");
4454 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4456 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4459 memset(bargs, 0, sizeof(*bargs));
4460 btrfs_update_ioctl_balance_args(fs_info, bargs);
4463 /* We didn't pause, we can clean everything up. */
4465 reset_balance_state(fs_info);
4466 btrfs_exclop_finish(fs_info);
4469 wake_up(&fs_info->balance_wait_q);
4473 if (bctl->flags & BTRFS_BALANCE_RESUME)
4474 reset_balance_state(fs_info);
4477 btrfs_exclop_finish(fs_info);
4482 static int balance_kthread(void *data)
4484 struct btrfs_fs_info *fs_info = data;
4487 sb_start_write(fs_info->sb);
4488 mutex_lock(&fs_info->balance_mutex);
4489 if (fs_info->balance_ctl)
4490 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4491 mutex_unlock(&fs_info->balance_mutex);
4492 sb_end_write(fs_info->sb);
4497 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4499 struct task_struct *tsk;
4501 mutex_lock(&fs_info->balance_mutex);
4502 if (!fs_info->balance_ctl) {
4503 mutex_unlock(&fs_info->balance_mutex);
4506 mutex_unlock(&fs_info->balance_mutex);
4508 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4509 btrfs_info(fs_info, "balance: resume skipped");
4513 spin_lock(&fs_info->super_lock);
4514 ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED);
4515 fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
4516 spin_unlock(&fs_info->super_lock);
4518 * A ro->rw remount sequence should continue with the paused balance
4519 * regardless of who pauses it, system or the user as of now, so set
4522 spin_lock(&fs_info->balance_lock);
4523 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4524 spin_unlock(&fs_info->balance_lock);
4526 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4527 return PTR_ERR_OR_ZERO(tsk);
4530 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4532 struct btrfs_balance_control *bctl;
4533 struct btrfs_balance_item *item;
4534 struct btrfs_disk_balance_args disk_bargs;
4535 struct btrfs_path *path;
4536 struct extent_buffer *leaf;
4537 struct btrfs_key key;
4540 path = btrfs_alloc_path();
4544 key.objectid = BTRFS_BALANCE_OBJECTID;
4545 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4548 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4551 if (ret > 0) { /* ret = -ENOENT; */
4556 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4562 leaf = path->nodes[0];
4563 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4565 bctl->flags = btrfs_balance_flags(leaf, item);
4566 bctl->flags |= BTRFS_BALANCE_RESUME;
4568 btrfs_balance_data(leaf, item, &disk_bargs);
4569 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4570 btrfs_balance_meta(leaf, item, &disk_bargs);
4571 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4572 btrfs_balance_sys(leaf, item, &disk_bargs);
4573 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4576 * This should never happen, as the paused balance state is recovered
4577 * during mount without any chance of other exclusive ops to collide.
4579 * This gives the exclusive op status to balance and keeps in paused
4580 * state until user intervention (cancel or umount). If the ownership
4581 * cannot be assigned, show a message but do not fail. The balance
4582 * is in a paused state and must have fs_info::balance_ctl properly
4585 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED))
4587 "balance: cannot set exclusive op status, resume manually");
4589 btrfs_release_path(path);
4591 mutex_lock(&fs_info->balance_mutex);
4592 BUG_ON(fs_info->balance_ctl);
4593 spin_lock(&fs_info->balance_lock);
4594 fs_info->balance_ctl = bctl;
4595 spin_unlock(&fs_info->balance_lock);
4596 mutex_unlock(&fs_info->balance_mutex);
4598 btrfs_free_path(path);
4602 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4606 mutex_lock(&fs_info->balance_mutex);
4607 if (!fs_info->balance_ctl) {
4608 mutex_unlock(&fs_info->balance_mutex);
4612 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4613 atomic_inc(&fs_info->balance_pause_req);
4614 mutex_unlock(&fs_info->balance_mutex);
4616 wait_event(fs_info->balance_wait_q,
4617 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4619 mutex_lock(&fs_info->balance_mutex);
4620 /* we are good with balance_ctl ripped off from under us */
4621 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4622 atomic_dec(&fs_info->balance_pause_req);
4627 mutex_unlock(&fs_info->balance_mutex);
4631 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4633 mutex_lock(&fs_info->balance_mutex);
4634 if (!fs_info->balance_ctl) {
4635 mutex_unlock(&fs_info->balance_mutex);
4640 * A paused balance with the item stored on disk can be resumed at
4641 * mount time if the mount is read-write. Otherwise it's still paused
4642 * and we must not allow cancelling as it deletes the item.
4644 if (sb_rdonly(fs_info->sb)) {
4645 mutex_unlock(&fs_info->balance_mutex);
4649 atomic_inc(&fs_info->balance_cancel_req);
4651 * if we are running just wait and return, balance item is
4652 * deleted in btrfs_balance in this case
4654 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4655 mutex_unlock(&fs_info->balance_mutex);
4656 wait_event(fs_info->balance_wait_q,
4657 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4658 mutex_lock(&fs_info->balance_mutex);
4660 mutex_unlock(&fs_info->balance_mutex);
4662 * Lock released to allow other waiters to continue, we'll
4663 * reexamine the status again.
4665 mutex_lock(&fs_info->balance_mutex);
4667 if (fs_info->balance_ctl) {
4668 reset_balance_state(fs_info);
4669 btrfs_exclop_finish(fs_info);
4670 btrfs_info(fs_info, "balance: canceled");
4674 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4675 atomic_dec(&fs_info->balance_cancel_req);
4676 mutex_unlock(&fs_info->balance_mutex);
4680 int btrfs_uuid_scan_kthread(void *data)
4682 struct btrfs_fs_info *fs_info = data;
4683 struct btrfs_root *root = fs_info->tree_root;
4684 struct btrfs_key key;
4685 struct btrfs_path *path = NULL;
4687 struct extent_buffer *eb;
4689 struct btrfs_root_item root_item;
4691 struct btrfs_trans_handle *trans = NULL;
4692 bool closing = false;
4694 path = btrfs_alloc_path();
4701 key.type = BTRFS_ROOT_ITEM_KEY;
4705 if (btrfs_fs_closing(fs_info)) {
4709 ret = btrfs_search_forward(root, &key, path,
4710 BTRFS_OLDEST_GENERATION);
4717 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4718 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4719 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4720 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4723 eb = path->nodes[0];
4724 slot = path->slots[0];
4725 item_size = btrfs_item_size(eb, slot);
4726 if (item_size < sizeof(root_item))
4729 read_extent_buffer(eb, &root_item,
4730 btrfs_item_ptr_offset(eb, slot),
4731 (int)sizeof(root_item));
4732 if (btrfs_root_refs(&root_item) == 0)
4735 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4736 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4740 btrfs_release_path(path);
4742 * 1 - subvol uuid item
4743 * 1 - received_subvol uuid item
4745 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4746 if (IS_ERR(trans)) {
4747 ret = PTR_ERR(trans);
4755 btrfs_release_path(path);
4756 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4757 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4758 BTRFS_UUID_KEY_SUBVOL,
4761 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4767 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4768 ret = btrfs_uuid_tree_add(trans,
4769 root_item.received_uuid,
4770 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4773 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4780 btrfs_release_path(path);
4782 ret = btrfs_end_transaction(trans);
4788 if (key.offset < (u64)-1) {
4790 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4792 key.type = BTRFS_ROOT_ITEM_KEY;
4793 } else if (key.objectid < (u64)-1) {
4795 key.type = BTRFS_ROOT_ITEM_KEY;
4804 btrfs_free_path(path);
4805 if (trans && !IS_ERR(trans))
4806 btrfs_end_transaction(trans);
4808 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4810 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4811 up(&fs_info->uuid_tree_rescan_sem);
4815 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4817 struct btrfs_trans_handle *trans;
4818 struct btrfs_root *tree_root = fs_info->tree_root;
4819 struct btrfs_root *uuid_root;
4820 struct task_struct *task;
4827 trans = btrfs_start_transaction(tree_root, 2);
4829 return PTR_ERR(trans);
4831 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4832 if (IS_ERR(uuid_root)) {
4833 ret = PTR_ERR(uuid_root);
4834 btrfs_abort_transaction(trans, ret);
4835 btrfs_end_transaction(trans);
4839 fs_info->uuid_root = uuid_root;
4841 ret = btrfs_commit_transaction(trans);
4845 down(&fs_info->uuid_tree_rescan_sem);
4846 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4848 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4849 btrfs_warn(fs_info, "failed to start uuid_scan task");
4850 up(&fs_info->uuid_tree_rescan_sem);
4851 return PTR_ERR(task);
4858 * shrinking a device means finding all of the device extents past
4859 * the new size, and then following the back refs to the chunks.
4860 * The chunk relocation code actually frees the device extent
4862 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4864 struct btrfs_fs_info *fs_info = device->fs_info;
4865 struct btrfs_root *root = fs_info->dev_root;
4866 struct btrfs_trans_handle *trans;
4867 struct btrfs_dev_extent *dev_extent = NULL;
4868 struct btrfs_path *path;
4874 bool retried = false;
4875 struct extent_buffer *l;
4876 struct btrfs_key key;
4877 struct btrfs_super_block *super_copy = fs_info->super_copy;
4878 u64 old_total = btrfs_super_total_bytes(super_copy);
4879 u64 old_size = btrfs_device_get_total_bytes(device);
4883 new_size = round_down(new_size, fs_info->sectorsize);
4885 diff = round_down(old_size - new_size, fs_info->sectorsize);
4887 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4890 path = btrfs_alloc_path();
4894 path->reada = READA_BACK;
4896 trans = btrfs_start_transaction(root, 0);
4897 if (IS_ERR(trans)) {
4898 btrfs_free_path(path);
4899 return PTR_ERR(trans);
4902 mutex_lock(&fs_info->chunk_mutex);
4904 btrfs_device_set_total_bytes(device, new_size);
4905 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4906 device->fs_devices->total_rw_bytes -= diff;
4907 atomic64_sub(diff, &fs_info->free_chunk_space);
4911 * Once the device's size has been set to the new size, ensure all
4912 * in-memory chunks are synced to disk so that the loop below sees them
4913 * and relocates them accordingly.
4915 if (contains_pending_extent(device, &start, diff)) {
4916 mutex_unlock(&fs_info->chunk_mutex);
4917 ret = btrfs_commit_transaction(trans);
4921 mutex_unlock(&fs_info->chunk_mutex);
4922 btrfs_end_transaction(trans);
4926 key.objectid = device->devid;
4927 key.offset = (u64)-1;
4928 key.type = BTRFS_DEV_EXTENT_KEY;
4931 mutex_lock(&fs_info->reclaim_bgs_lock);
4932 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4934 mutex_unlock(&fs_info->reclaim_bgs_lock);
4938 ret = btrfs_previous_item(root, path, 0, key.type);
4940 mutex_unlock(&fs_info->reclaim_bgs_lock);
4944 btrfs_release_path(path);
4949 slot = path->slots[0];
4950 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4952 if (key.objectid != device->devid) {
4953 mutex_unlock(&fs_info->reclaim_bgs_lock);
4954 btrfs_release_path(path);
4958 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4959 length = btrfs_dev_extent_length(l, dev_extent);
4961 if (key.offset + length <= new_size) {
4962 mutex_unlock(&fs_info->reclaim_bgs_lock);
4963 btrfs_release_path(path);
4967 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4968 btrfs_release_path(path);
4971 * We may be relocating the only data chunk we have,
4972 * which could potentially end up with losing data's
4973 * raid profile, so lets allocate an empty one in
4976 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4978 mutex_unlock(&fs_info->reclaim_bgs_lock);
4982 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4983 mutex_unlock(&fs_info->reclaim_bgs_lock);
4984 if (ret == -ENOSPC) {
4987 if (ret == -ETXTBSY) {
4989 "could not shrink block group %llu due to active swapfile",
4994 } while (key.offset-- > 0);
4996 if (failed && !retried) {
5000 } else if (failed && retried) {
5005 /* Shrinking succeeded, else we would be at "done". */
5006 trans = btrfs_start_transaction(root, 0);
5007 if (IS_ERR(trans)) {
5008 ret = PTR_ERR(trans);
5012 mutex_lock(&fs_info->chunk_mutex);
5013 /* Clear all state bits beyond the shrunk device size */
5014 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
5017 btrfs_device_set_disk_total_bytes(device, new_size);
5018 if (list_empty(&device->post_commit_list))
5019 list_add_tail(&device->post_commit_list,
5020 &trans->transaction->dev_update_list);
5022 WARN_ON(diff > old_total);
5023 btrfs_set_super_total_bytes(super_copy,
5024 round_down(old_total - diff, fs_info->sectorsize));
5025 mutex_unlock(&fs_info->chunk_mutex);
5027 btrfs_reserve_chunk_metadata(trans, false);
5028 /* Now btrfs_update_device() will change the on-disk size. */
5029 ret = btrfs_update_device(trans, device);
5030 btrfs_trans_release_chunk_metadata(trans);
5032 btrfs_abort_transaction(trans, ret);
5033 btrfs_end_transaction(trans);
5035 ret = btrfs_commit_transaction(trans);
5038 btrfs_free_path(path);
5040 mutex_lock(&fs_info->chunk_mutex);
5041 btrfs_device_set_total_bytes(device, old_size);
5042 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
5043 device->fs_devices->total_rw_bytes += diff;
5044 atomic64_add(diff, &fs_info->free_chunk_space);
5045 mutex_unlock(&fs_info->chunk_mutex);
5050 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
5051 struct btrfs_key *key,
5052 struct btrfs_chunk *chunk, int item_size)
5054 struct btrfs_super_block *super_copy = fs_info->super_copy;
5055 struct btrfs_disk_key disk_key;
5059 lockdep_assert_held(&fs_info->chunk_mutex);
5061 array_size = btrfs_super_sys_array_size(super_copy);
5062 if (array_size + item_size + sizeof(disk_key)
5063 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
5066 ptr = super_copy->sys_chunk_array + array_size;
5067 btrfs_cpu_key_to_disk(&disk_key, key);
5068 memcpy(ptr, &disk_key, sizeof(disk_key));
5069 ptr += sizeof(disk_key);
5070 memcpy(ptr, chunk, item_size);
5071 item_size += sizeof(disk_key);
5072 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
5078 * sort the devices in descending order by max_avail, total_avail
5080 static int btrfs_cmp_device_info(const void *a, const void *b)
5082 const struct btrfs_device_info *di_a = a;
5083 const struct btrfs_device_info *di_b = b;
5085 if (di_a->max_avail > di_b->max_avail)
5087 if (di_a->max_avail < di_b->max_avail)
5089 if (di_a->total_avail > di_b->total_avail)
5091 if (di_a->total_avail < di_b->total_avail)
5096 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
5098 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5101 btrfs_set_fs_incompat(info, RAID56);
5104 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
5106 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
5109 btrfs_set_fs_incompat(info, RAID1C34);
5113 * Structure used internally for btrfs_create_chunk() function.
5114 * Wraps needed parameters.
5116 struct alloc_chunk_ctl {
5119 /* Total number of stripes to allocate */
5121 /* sub_stripes info for map */
5123 /* Stripes per device */
5125 /* Maximum number of devices to use */
5127 /* Minimum number of devices to use */
5129 /* ndevs has to be a multiple of this */
5131 /* Number of copies */
5133 /* Number of stripes worth of bytes to store parity information */
5135 u64 max_stripe_size;
5143 static void init_alloc_chunk_ctl_policy_regular(
5144 struct btrfs_fs_devices *fs_devices,
5145 struct alloc_chunk_ctl *ctl)
5147 struct btrfs_space_info *space_info;
5149 space_info = btrfs_find_space_info(fs_devices->fs_info, ctl->type);
5152 ctl->max_chunk_size = READ_ONCE(space_info->chunk_size);
5153 ctl->max_stripe_size = min_t(u64, ctl->max_chunk_size, SZ_1G);
5155 if (ctl->type & BTRFS_BLOCK_GROUP_SYSTEM)
5156 ctl->devs_max = min_t(int, ctl->devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
5158 /* We don't want a chunk larger than 10% of writable space */
5159 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
5160 ctl->max_chunk_size);
5161 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
5164 static void init_alloc_chunk_ctl_policy_zoned(
5165 struct btrfs_fs_devices *fs_devices,
5166 struct alloc_chunk_ctl *ctl)
5168 u64 zone_size = fs_devices->fs_info->zone_size;
5170 int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5171 int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5172 u64 min_chunk_size = min_data_stripes * zone_size;
5173 u64 type = ctl->type;
5175 ctl->max_stripe_size = zone_size;
5176 if (type & BTRFS_BLOCK_GROUP_DATA) {
5177 ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5179 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5180 ctl->max_chunk_size = ctl->max_stripe_size;
5181 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5182 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5183 ctl->devs_max = min_t(int, ctl->devs_max,
5184 BTRFS_MAX_DEVS_SYS_CHUNK);
5189 /* We don't want a chunk larger than 10% of writable space */
5190 limit = max(round_down(div_factor(fs_devices->total_rw_bytes, 1),
5193 ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5194 ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5197 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5198 struct alloc_chunk_ctl *ctl)
5200 int index = btrfs_bg_flags_to_raid_index(ctl->type);
5202 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5203 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5204 ctl->devs_max = btrfs_raid_array[index].devs_max;
5206 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5207 ctl->devs_min = btrfs_raid_array[index].devs_min;
5208 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5209 ctl->ncopies = btrfs_raid_array[index].ncopies;
5210 ctl->nparity = btrfs_raid_array[index].nparity;
5213 switch (fs_devices->chunk_alloc_policy) {
5214 case BTRFS_CHUNK_ALLOC_REGULAR:
5215 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5217 case BTRFS_CHUNK_ALLOC_ZONED:
5218 init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5225 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5226 struct alloc_chunk_ctl *ctl,
5227 struct btrfs_device_info *devices_info)
5229 struct btrfs_fs_info *info = fs_devices->fs_info;
5230 struct btrfs_device *device;
5232 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5239 * in the first pass through the devices list, we gather information
5240 * about the available holes on each device.
5242 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5243 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5245 "BTRFS: read-only device in alloc_list\n");
5249 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5250 &device->dev_state) ||
5251 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5254 if (device->total_bytes > device->bytes_used)
5255 total_avail = device->total_bytes - device->bytes_used;
5259 /* If there is no space on this device, skip it. */
5260 if (total_avail < ctl->dev_extent_min)
5263 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5265 if (ret && ret != -ENOSPC)
5269 max_avail = dev_extent_want;
5271 if (max_avail < ctl->dev_extent_min) {
5272 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5274 "%s: devid %llu has no free space, have=%llu want=%llu",
5275 __func__, device->devid, max_avail,
5276 ctl->dev_extent_min);
5280 if (ndevs == fs_devices->rw_devices) {
5281 WARN(1, "%s: found more than %llu devices\n",
5282 __func__, fs_devices->rw_devices);
5285 devices_info[ndevs].dev_offset = dev_offset;
5286 devices_info[ndevs].max_avail = max_avail;
5287 devices_info[ndevs].total_avail = total_avail;
5288 devices_info[ndevs].dev = device;
5294 * now sort the devices by hole size / available space
5296 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5297 btrfs_cmp_device_info, NULL);
5302 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5303 struct btrfs_device_info *devices_info)
5305 /* Number of stripes that count for block group size */
5309 * The primary goal is to maximize the number of stripes, so use as
5310 * many devices as possible, even if the stripes are not maximum sized.
5312 * The DUP profile stores more than one stripe per device, the
5313 * max_avail is the total size so we have to adjust.
5315 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5317 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5319 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5320 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5323 * Use the number of data stripes to figure out how big this chunk is
5324 * really going to be in terms of logical address space, and compare
5325 * that answer with the max chunk size. If it's higher, we try to
5326 * reduce stripe_size.
5328 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5330 * Reduce stripe_size, round it up to a 16MB boundary again and
5331 * then use it, unless it ends up being even bigger than the
5332 * previous value we had already.
5334 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5335 data_stripes), SZ_16M),
5339 /* Stripe size should not go beyond 1G. */
5340 ctl->stripe_size = min_t(u64, ctl->stripe_size, SZ_1G);
5342 /* Align to BTRFS_STRIPE_LEN */
5343 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5344 ctl->chunk_size = ctl->stripe_size * data_stripes;
5349 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5350 struct btrfs_device_info *devices_info)
5352 u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5353 /* Number of stripes that count for block group size */
5357 * It should hold because:
5358 * dev_extent_min == dev_extent_want == zone_size * dev_stripes
5360 ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min);
5362 ctl->stripe_size = zone_size;
5363 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5364 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5366 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */
5367 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5368 ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5369 ctl->stripe_size) + ctl->nparity,
5371 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5372 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5373 ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size);
5376 ctl->chunk_size = ctl->stripe_size * data_stripes;
5381 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5382 struct alloc_chunk_ctl *ctl,
5383 struct btrfs_device_info *devices_info)
5385 struct btrfs_fs_info *info = fs_devices->fs_info;
5388 * Round down to number of usable stripes, devs_increment can be any
5389 * number so we can't use round_down() that requires power of 2, while
5390 * rounddown is safe.
5392 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5394 if (ctl->ndevs < ctl->devs_min) {
5395 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5397 "%s: not enough devices with free space: have=%d minimum required=%d",
5398 __func__, ctl->ndevs, ctl->devs_min);
5403 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5405 switch (fs_devices->chunk_alloc_policy) {
5406 case BTRFS_CHUNK_ALLOC_REGULAR:
5407 return decide_stripe_size_regular(ctl, devices_info);
5408 case BTRFS_CHUNK_ALLOC_ZONED:
5409 return decide_stripe_size_zoned(ctl, devices_info);
5415 static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
5416 struct alloc_chunk_ctl *ctl,
5417 struct btrfs_device_info *devices_info)
5419 struct btrfs_fs_info *info = trans->fs_info;
5420 struct map_lookup *map = NULL;
5421 struct extent_map_tree *em_tree;
5422 struct btrfs_block_group *block_group;
5423 struct extent_map *em;
5424 u64 start = ctl->start;
5425 u64 type = ctl->type;
5430 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5432 return ERR_PTR(-ENOMEM);
5433 map->num_stripes = ctl->num_stripes;
5435 for (i = 0; i < ctl->ndevs; ++i) {
5436 for (j = 0; j < ctl->dev_stripes; ++j) {
5437 int s = i * ctl->dev_stripes + j;
5438 map->stripes[s].dev = devices_info[i].dev;
5439 map->stripes[s].physical = devices_info[i].dev_offset +
5440 j * ctl->stripe_size;
5443 map->stripe_len = BTRFS_STRIPE_LEN;
5444 map->io_align = BTRFS_STRIPE_LEN;
5445 map->io_width = BTRFS_STRIPE_LEN;
5447 map->sub_stripes = ctl->sub_stripes;
5449 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5451 em = alloc_extent_map();
5454 return ERR_PTR(-ENOMEM);
5456 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5457 em->map_lookup = map;
5459 em->len = ctl->chunk_size;
5460 em->block_start = 0;
5461 em->block_len = em->len;
5462 em->orig_block_len = ctl->stripe_size;
5464 em_tree = &info->mapping_tree;
5465 write_lock(&em_tree->lock);
5466 ret = add_extent_mapping(em_tree, em, 0);
5468 write_unlock(&em_tree->lock);
5469 free_extent_map(em);
5470 return ERR_PTR(ret);
5472 write_unlock(&em_tree->lock);
5474 block_group = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5475 if (IS_ERR(block_group))
5476 goto error_del_extent;
5478 for (i = 0; i < map->num_stripes; i++) {
5479 struct btrfs_device *dev = map->stripes[i].dev;
5481 btrfs_device_set_bytes_used(dev,
5482 dev->bytes_used + ctl->stripe_size);
5483 if (list_empty(&dev->post_commit_list))
5484 list_add_tail(&dev->post_commit_list,
5485 &trans->transaction->dev_update_list);
5488 atomic64_sub(ctl->stripe_size * map->num_stripes,
5489 &info->free_chunk_space);
5491 free_extent_map(em);
5492 check_raid56_incompat_flag(info, type);
5493 check_raid1c34_incompat_flag(info, type);
5498 write_lock(&em_tree->lock);
5499 remove_extent_mapping(em_tree, em);
5500 write_unlock(&em_tree->lock);
5502 /* One for our allocation */
5503 free_extent_map(em);
5504 /* One for the tree reference */
5505 free_extent_map(em);
5510 struct btrfs_block_group *btrfs_create_chunk(struct btrfs_trans_handle *trans,
5513 struct btrfs_fs_info *info = trans->fs_info;
5514 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5515 struct btrfs_device_info *devices_info = NULL;
5516 struct alloc_chunk_ctl ctl;
5517 struct btrfs_block_group *block_group;
5520 lockdep_assert_held(&info->chunk_mutex);
5522 if (!alloc_profile_is_valid(type, 0)) {
5524 return ERR_PTR(-EINVAL);
5527 if (list_empty(&fs_devices->alloc_list)) {
5528 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5529 btrfs_debug(info, "%s: no writable device", __func__);
5530 return ERR_PTR(-ENOSPC);
5533 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5534 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5536 return ERR_PTR(-EINVAL);
5539 ctl.start = find_next_chunk(info);
5541 init_alloc_chunk_ctl(fs_devices, &ctl);
5543 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5546 return ERR_PTR(-ENOMEM);
5548 ret = gather_device_info(fs_devices, &ctl, devices_info);
5550 block_group = ERR_PTR(ret);
5554 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5556 block_group = ERR_PTR(ret);
5560 block_group = create_chunk(trans, &ctl, devices_info);
5563 kfree(devices_info);
5568 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5569 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5572 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5575 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
5576 struct btrfs_block_group *bg)
5578 struct btrfs_fs_info *fs_info = trans->fs_info;
5579 struct btrfs_root *chunk_root = fs_info->chunk_root;
5580 struct btrfs_key key;
5581 struct btrfs_chunk *chunk;
5582 struct btrfs_stripe *stripe;
5583 struct extent_map *em;
5584 struct map_lookup *map;
5590 * We take the chunk_mutex for 2 reasons:
5592 * 1) Updates and insertions in the chunk btree must be done while holding
5593 * the chunk_mutex, as well as updating the system chunk array in the
5594 * superblock. See the comment on top of btrfs_chunk_alloc() for the
5597 * 2) To prevent races with the final phase of a device replace operation
5598 * that replaces the device object associated with the map's stripes,
5599 * because the device object's id can change at any time during that
5600 * final phase of the device replace operation
5601 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5602 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5603 * which would cause a failure when updating the device item, which does
5604 * not exists, or persisting a stripe of the chunk item with such ID.
5605 * Here we can't use the device_list_mutex because our caller already
5606 * has locked the chunk_mutex, and the final phase of device replace
5607 * acquires both mutexes - first the device_list_mutex and then the
5608 * chunk_mutex. Using any of those two mutexes protects us from a
5609 * concurrent device replace.
5611 lockdep_assert_held(&fs_info->chunk_mutex);
5613 em = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
5616 btrfs_abort_transaction(trans, ret);
5620 map = em->map_lookup;
5621 item_size = btrfs_chunk_item_size(map->num_stripes);
5623 chunk = kzalloc(item_size, GFP_NOFS);
5626 btrfs_abort_transaction(trans, ret);
5630 for (i = 0; i < map->num_stripes; i++) {
5631 struct btrfs_device *device = map->stripes[i].dev;
5633 ret = btrfs_update_device(trans, device);
5638 stripe = &chunk->stripe;
5639 for (i = 0; i < map->num_stripes; i++) {
5640 struct btrfs_device *device = map->stripes[i].dev;
5641 const u64 dev_offset = map->stripes[i].physical;
5643 btrfs_set_stack_stripe_devid(stripe, device->devid);
5644 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5645 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5649 btrfs_set_stack_chunk_length(chunk, bg->length);
5650 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
5651 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5652 btrfs_set_stack_chunk_type(chunk, map->type);
5653 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5654 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5655 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5656 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5657 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5659 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5660 key.type = BTRFS_CHUNK_ITEM_KEY;
5661 key.offset = bg->start;
5663 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5667 set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED, &bg->runtime_flags);
5669 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5670 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5677 free_extent_map(em);
5681 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5683 struct btrfs_fs_info *fs_info = trans->fs_info;
5685 struct btrfs_block_group *meta_bg;
5686 struct btrfs_block_group *sys_bg;
5689 * When adding a new device for sprouting, the seed device is read-only
5690 * so we must first allocate a metadata and a system chunk. But before
5691 * adding the block group items to the extent, device and chunk btrees,
5694 * 1) Create both chunks without doing any changes to the btrees, as
5695 * otherwise we would get -ENOSPC since the block groups from the
5696 * seed device are read-only;
5698 * 2) Add the device item for the new sprout device - finishing the setup
5699 * of a new block group requires updating the device item in the chunk
5700 * btree, so it must exist when we attempt to do it. The previous step
5701 * ensures this does not fail with -ENOSPC.
5703 * After that we can add the block group items to their btrees:
5704 * update existing device item in the chunk btree, add a new block group
5705 * item to the extent btree, add a new chunk item to the chunk btree and
5706 * finally add the new device extent items to the devices btree.
5709 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5710 meta_bg = btrfs_create_chunk(trans, alloc_profile);
5711 if (IS_ERR(meta_bg))
5712 return PTR_ERR(meta_bg);
5714 alloc_profile = btrfs_system_alloc_profile(fs_info);
5715 sys_bg = btrfs_create_chunk(trans, alloc_profile);
5717 return PTR_ERR(sys_bg);
5722 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5724 const int index = btrfs_bg_flags_to_raid_index(map->type);
5726 return btrfs_raid_array[index].tolerated_failures;
5729 bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5731 struct extent_map *em;
5732 struct map_lookup *map;
5737 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5741 map = em->map_lookup;
5742 for (i = 0; i < map->num_stripes; i++) {
5743 if (test_bit(BTRFS_DEV_STATE_MISSING,
5744 &map->stripes[i].dev->dev_state)) {
5748 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5749 &map->stripes[i].dev->dev_state)) {
5756 * If the number of missing devices is larger than max errors, we can
5757 * not write the data into that chunk successfully.
5759 if (miss_ndevs > btrfs_chunk_max_errors(map))
5762 free_extent_map(em);
5766 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5768 struct extent_map *em;
5771 write_lock(&tree->lock);
5772 em = lookup_extent_mapping(tree, 0, (u64)-1);
5774 remove_extent_mapping(tree, em);
5775 write_unlock(&tree->lock);
5779 free_extent_map(em);
5780 /* once for the tree */
5781 free_extent_map(em);
5785 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5787 struct extent_map *em;
5788 struct map_lookup *map;
5789 enum btrfs_raid_types index;
5792 em = btrfs_get_chunk_map(fs_info, logical, len);
5795 * We could return errors for these cases, but that could get
5796 * ugly and we'd probably do the same thing which is just not do
5797 * anything else and exit, so return 1 so the callers don't try
5798 * to use other copies.
5802 map = em->map_lookup;
5803 index = btrfs_bg_flags_to_raid_index(map->type);
5805 /* Non-RAID56, use their ncopies from btrfs_raid_array. */
5806 if (!(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5807 ret = btrfs_raid_array[index].ncopies;
5808 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5810 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5812 * There could be two corrupted data stripes, we need
5813 * to loop retry in order to rebuild the correct data.
5815 * Fail a stripe at a time on every retry except the
5816 * stripe under reconstruction.
5818 ret = map->num_stripes;
5819 free_extent_map(em);
5821 down_read(&fs_info->dev_replace.rwsem);
5822 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5823 fs_info->dev_replace.tgtdev)
5825 up_read(&fs_info->dev_replace.rwsem);
5830 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5833 struct extent_map *em;
5834 struct map_lookup *map;
5835 unsigned long len = fs_info->sectorsize;
5837 if (!btrfs_fs_incompat(fs_info, RAID56))
5840 em = btrfs_get_chunk_map(fs_info, logical, len);
5842 if (!WARN_ON(IS_ERR(em))) {
5843 map = em->map_lookup;
5844 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5845 len = map->stripe_len * nr_data_stripes(map);
5846 free_extent_map(em);
5851 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5853 struct extent_map *em;
5854 struct map_lookup *map;
5857 if (!btrfs_fs_incompat(fs_info, RAID56))
5860 em = btrfs_get_chunk_map(fs_info, logical, len);
5862 if(!WARN_ON(IS_ERR(em))) {
5863 map = em->map_lookup;
5864 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5866 free_extent_map(em);
5871 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5872 struct map_lookup *map, int first,
5873 int dev_replace_is_ongoing)
5877 int preferred_mirror;
5879 struct btrfs_device *srcdev;
5882 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5884 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5885 num_stripes = map->sub_stripes;
5887 num_stripes = map->num_stripes;
5889 switch (fs_info->fs_devices->read_policy) {
5891 /* Shouldn't happen, just warn and use pid instead of failing */
5892 btrfs_warn_rl(fs_info,
5893 "unknown read_policy type %u, reset to pid",
5894 fs_info->fs_devices->read_policy);
5895 fs_info->fs_devices->read_policy = BTRFS_READ_POLICY_PID;
5897 case BTRFS_READ_POLICY_PID:
5898 preferred_mirror = first + (current->pid % num_stripes);
5902 if (dev_replace_is_ongoing &&
5903 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5904 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5905 srcdev = fs_info->dev_replace.srcdev;
5910 * try to avoid the drive that is the source drive for a
5911 * dev-replace procedure, only choose it if no other non-missing
5912 * mirror is available
5914 for (tolerance = 0; tolerance < 2; tolerance++) {
5915 if (map->stripes[preferred_mirror].dev->bdev &&
5916 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5917 return preferred_mirror;
5918 for (i = first; i < first + num_stripes; i++) {
5919 if (map->stripes[i].dev->bdev &&
5920 (tolerance || map->stripes[i].dev != srcdev))
5925 /* we couldn't find one that doesn't fail. Just return something
5926 * and the io error handling code will clean up eventually
5928 return preferred_mirror;
5931 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5932 static void sort_parity_stripes(struct btrfs_io_context *bioc, int num_stripes)
5939 for (i = 0; i < num_stripes - 1; i++) {
5940 /* Swap if parity is on a smaller index */
5941 if (bioc->raid_map[i] > bioc->raid_map[i + 1]) {
5942 swap(bioc->stripes[i], bioc->stripes[i + 1]);
5943 swap(bioc->raid_map[i], bioc->raid_map[i + 1]);
5950 static struct btrfs_io_context *alloc_btrfs_io_context(struct btrfs_fs_info *fs_info,
5954 struct btrfs_io_context *bioc = kzalloc(
5955 /* The size of btrfs_io_context */
5956 sizeof(struct btrfs_io_context) +
5957 /* Plus the variable array for the stripes */
5958 sizeof(struct btrfs_io_stripe) * (total_stripes) +
5959 /* Plus the variable array for the tgt dev */
5960 sizeof(int) * (real_stripes) +
5962 * Plus the raid_map, which includes both the tgt dev
5965 sizeof(u64) * (total_stripes),
5966 GFP_NOFS|__GFP_NOFAIL);
5968 refcount_set(&bioc->refs, 1);
5970 bioc->fs_info = fs_info;
5971 bioc->tgtdev_map = (int *)(bioc->stripes + total_stripes);
5972 bioc->raid_map = (u64 *)(bioc->tgtdev_map + real_stripes);
5977 void btrfs_get_bioc(struct btrfs_io_context *bioc)
5979 WARN_ON(!refcount_read(&bioc->refs));
5980 refcount_inc(&bioc->refs);
5983 void btrfs_put_bioc(struct btrfs_io_context *bioc)
5987 if (refcount_dec_and_test(&bioc->refs))
5992 * Please note that, discard won't be sent to target device of device
5995 struct btrfs_discard_stripe *btrfs_map_discard(struct btrfs_fs_info *fs_info,
5996 u64 logical, u64 *length_ret,
5999 struct extent_map *em;
6000 struct map_lookup *map;
6001 struct btrfs_discard_stripe *stripes;
6002 u64 length = *length_ret;
6006 u64 stripe_end_offset;
6012 u32 sub_stripes = 0;
6013 u64 stripes_per_dev = 0;
6014 u32 remaining_stripes = 0;
6015 u32 last_stripe = 0;
6019 em = btrfs_get_chunk_map(fs_info, logical, length);
6021 return ERR_CAST(em);
6023 map = em->map_lookup;
6025 /* we don't discard raid56 yet */
6026 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6031 offset = logical - em->start;
6032 length = min_t(u64, em->start + em->len - logical, length);
6033 *length_ret = length;
6035 stripe_len = map->stripe_len;
6037 * stripe_nr counts the total number of stripes we have to stride
6038 * to get to this block
6040 stripe_nr = div64_u64(offset, stripe_len);
6042 /* stripe_offset is the offset of this block in its stripe */
6043 stripe_offset = offset - stripe_nr * stripe_len;
6045 stripe_nr_end = round_up(offset + length, map->stripe_len);
6046 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
6047 stripe_cnt = stripe_nr_end - stripe_nr;
6048 stripe_end_offset = stripe_nr_end * map->stripe_len -
6051 * after this, stripe_nr is the number of stripes on this
6052 * device we have to walk to find the data, and stripe_index is
6053 * the number of our device in the stripe array
6057 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6058 BTRFS_BLOCK_GROUP_RAID10)) {
6059 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6062 sub_stripes = map->sub_stripes;
6064 factor = map->num_stripes / sub_stripes;
6065 *num_stripes = min_t(u64, map->num_stripes,
6066 sub_stripes * stripe_cnt);
6067 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6068 stripe_index *= sub_stripes;
6069 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
6070 &remaining_stripes);
6071 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
6072 last_stripe *= sub_stripes;
6073 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
6074 BTRFS_BLOCK_GROUP_DUP)) {
6075 *num_stripes = map->num_stripes;
6077 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6081 stripes = kcalloc(*num_stripes, sizeof(*stripes), GFP_NOFS);
6087 for (i = 0; i < *num_stripes; i++) {
6088 stripes[i].physical =
6089 map->stripes[stripe_index].physical +
6090 stripe_offset + stripe_nr * map->stripe_len;
6091 stripes[i].dev = map->stripes[stripe_index].dev;
6093 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6094 BTRFS_BLOCK_GROUP_RAID10)) {
6095 stripes[i].length = stripes_per_dev * map->stripe_len;
6097 if (i / sub_stripes < remaining_stripes)
6098 stripes[i].length += map->stripe_len;
6101 * Special for the first stripe and
6104 * |-------|...|-------|
6108 if (i < sub_stripes)
6109 stripes[i].length -= stripe_offset;
6111 if (stripe_index >= last_stripe &&
6112 stripe_index <= (last_stripe +
6114 stripes[i].length -= stripe_end_offset;
6116 if (i == sub_stripes - 1)
6119 stripes[i].length = length;
6123 if (stripe_index == map->num_stripes) {
6129 free_extent_map(em);
6132 free_extent_map(em);
6133 return ERR_PTR(ret);
6137 * In dev-replace case, for repair case (that's the only case where the mirror
6138 * is selected explicitly when calling btrfs_map_block), blocks left of the
6139 * left cursor can also be read from the target drive.
6141 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
6143 * For READ, it also needs to be supported using the same mirror number.
6145 * If the requested block is not left of the left cursor, EIO is returned. This
6146 * can happen because btrfs_num_copies() returns one more in the dev-replace
6149 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
6150 u64 logical, u64 length,
6151 u64 srcdev_devid, int *mirror_num,
6154 struct btrfs_io_context *bioc = NULL;
6156 int index_srcdev = 0;
6158 u64 physical_of_found = 0;
6162 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
6163 logical, &length, &bioc, NULL, NULL, 0);
6165 ASSERT(bioc == NULL);
6169 num_stripes = bioc->num_stripes;
6170 if (*mirror_num > num_stripes) {
6172 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
6173 * that means that the requested area is not left of the left
6176 btrfs_put_bioc(bioc);
6181 * process the rest of the function using the mirror_num of the source
6182 * drive. Therefore look it up first. At the end, patch the device
6183 * pointer to the one of the target drive.
6185 for (i = 0; i < num_stripes; i++) {
6186 if (bioc->stripes[i].dev->devid != srcdev_devid)
6190 * In case of DUP, in order to keep it simple, only add the
6191 * mirror with the lowest physical address
6194 physical_of_found <= bioc->stripes[i].physical)
6199 physical_of_found = bioc->stripes[i].physical;
6202 btrfs_put_bioc(bioc);
6208 *mirror_num = index_srcdev + 1;
6209 *physical = physical_of_found;
6213 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6215 struct btrfs_block_group *cache;
6218 /* Non zoned filesystem does not use "to_copy" flag */
6219 if (!btrfs_is_zoned(fs_info))
6222 cache = btrfs_lookup_block_group(fs_info, logical);
6224 ret = test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
6226 btrfs_put_block_group(cache);
6230 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
6231 struct btrfs_io_context **bioc_ret,
6232 struct btrfs_dev_replace *dev_replace,
6234 int *num_stripes_ret, int *max_errors_ret)
6236 struct btrfs_io_context *bioc = *bioc_ret;
6237 u64 srcdev_devid = dev_replace->srcdev->devid;
6238 int tgtdev_indexes = 0;
6239 int num_stripes = *num_stripes_ret;
6240 int max_errors = *max_errors_ret;
6243 if (op == BTRFS_MAP_WRITE) {
6244 int index_where_to_add;
6247 * A block group which have "to_copy" set will eventually
6248 * copied by dev-replace process. We can avoid cloning IO here.
6250 if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6254 * duplicate the write operations while the dev replace
6255 * procedure is running. Since the copying of the old disk to
6256 * the new disk takes place at run time while the filesystem is
6257 * mounted writable, the regular write operations to the old
6258 * disk have to be duplicated to go to the new disk as well.
6260 * Note that device->missing is handled by the caller, and that
6261 * the write to the old disk is already set up in the stripes
6264 index_where_to_add = num_stripes;
6265 for (i = 0; i < num_stripes; i++) {
6266 if (bioc->stripes[i].dev->devid == srcdev_devid) {
6267 /* write to new disk, too */
6268 struct btrfs_io_stripe *new =
6269 bioc->stripes + index_where_to_add;
6270 struct btrfs_io_stripe *old =
6273 new->physical = old->physical;
6274 new->dev = dev_replace->tgtdev;
6275 bioc->tgtdev_map[i] = index_where_to_add;
6276 index_where_to_add++;
6281 num_stripes = index_where_to_add;
6282 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
6283 int index_srcdev = 0;
6285 u64 physical_of_found = 0;
6288 * During the dev-replace procedure, the target drive can also
6289 * be used to read data in case it is needed to repair a corrupt
6290 * block elsewhere. This is possible if the requested area is
6291 * left of the left cursor. In this area, the target drive is a
6292 * full copy of the source drive.
6294 for (i = 0; i < num_stripes; i++) {
6295 if (bioc->stripes[i].dev->devid == srcdev_devid) {
6297 * In case of DUP, in order to keep it simple,
6298 * only add the mirror with the lowest physical
6302 physical_of_found <= bioc->stripes[i].physical)
6306 physical_of_found = bioc->stripes[i].physical;
6310 struct btrfs_io_stripe *tgtdev_stripe =
6311 bioc->stripes + num_stripes;
6313 tgtdev_stripe->physical = physical_of_found;
6314 tgtdev_stripe->dev = dev_replace->tgtdev;
6315 bioc->tgtdev_map[index_srcdev] = num_stripes;
6322 *num_stripes_ret = num_stripes;
6323 *max_errors_ret = max_errors;
6324 bioc->num_tgtdevs = tgtdev_indexes;
6328 static bool need_full_stripe(enum btrfs_map_op op)
6330 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
6334 * Calculate the geometry of a particular (address, len) tuple. This
6335 * information is used to calculate how big a particular bio can get before it
6336 * straddles a stripe.
6338 * @fs_info: the filesystem
6339 * @em: mapping containing the logical extent
6340 * @op: type of operation - write or read
6341 * @logical: address that we want to figure out the geometry of
6342 * @io_geom: pointer used to return values
6344 * Returns < 0 in case a chunk for the given logical address cannot be found,
6345 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
6347 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, struct extent_map *em,
6348 enum btrfs_map_op op, u64 logical,
6349 struct btrfs_io_geometry *io_geom)
6351 struct map_lookup *map;
6357 u64 raid56_full_stripe_start = (u64)-1;
6360 ASSERT(op != BTRFS_MAP_DISCARD);
6362 map = em->map_lookup;
6363 /* Offset of this logical address in the chunk */
6364 offset = logical - em->start;
6365 /* Len of a stripe in a chunk */
6366 stripe_len = map->stripe_len;
6368 * Stripe_nr is where this block falls in
6369 * stripe_offset is the offset of this block in its stripe.
6371 stripe_nr = div64_u64_rem(offset, stripe_len, &stripe_offset);
6372 ASSERT(stripe_offset < U32_MAX);
6374 data_stripes = nr_data_stripes(map);
6376 /* Only stripe based profiles needs to check against stripe length. */
6377 if (map->type & BTRFS_BLOCK_GROUP_STRIPE_MASK) {
6378 u64 max_len = stripe_len - stripe_offset;
6381 * In case of raid56, we need to know the stripe aligned start
6383 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6384 unsigned long full_stripe_len = stripe_len * data_stripes;
6385 raid56_full_stripe_start = offset;
6388 * Allow a write of a full stripe, but make sure we
6389 * don't allow straddling of stripes
6391 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6393 raid56_full_stripe_start *= full_stripe_len;
6396 * For writes to RAID[56], allow a full stripeset across
6397 * all disks. For other RAID types and for RAID[56]
6398 * reads, just allow a single stripe (on a single disk).
6400 if (op == BTRFS_MAP_WRITE) {
6401 max_len = stripe_len * data_stripes -
6402 (offset - raid56_full_stripe_start);
6405 len = min_t(u64, em->len - offset, max_len);
6407 len = em->len - offset;
6411 io_geom->offset = offset;
6412 io_geom->stripe_len = stripe_len;
6413 io_geom->stripe_nr = stripe_nr;
6414 io_geom->stripe_offset = stripe_offset;
6415 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6420 static void set_io_stripe(struct btrfs_io_stripe *dst, const struct map_lookup *map,
6421 u32 stripe_index, u64 stripe_offset, u64 stripe_nr)
6423 dst->dev = map->stripes[stripe_index].dev;
6424 dst->physical = map->stripes[stripe_index].physical +
6425 stripe_offset + stripe_nr * map->stripe_len;
6428 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6429 enum btrfs_map_op op, u64 logical, u64 *length,
6430 struct btrfs_io_context **bioc_ret,
6431 struct btrfs_io_stripe *smap,
6432 int *mirror_num_ret, int need_raid_map)
6434 struct extent_map *em;
6435 struct map_lookup *map;
6443 int mirror_num = (mirror_num_ret ? *mirror_num_ret : 0);
6446 int tgtdev_indexes = 0;
6447 struct btrfs_io_context *bioc = NULL;
6448 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6449 int dev_replace_is_ongoing = 0;
6450 int num_alloc_stripes;
6451 int patch_the_first_stripe_for_dev_replace = 0;
6452 u64 physical_to_patch_in_first_stripe = 0;
6453 u64 raid56_full_stripe_start = (u64)-1;
6454 struct btrfs_io_geometry geom;
6457 ASSERT(op != BTRFS_MAP_DISCARD);
6459 em = btrfs_get_chunk_map(fs_info, logical, *length);
6460 ASSERT(!IS_ERR(em));
6462 ret = btrfs_get_io_geometry(fs_info, em, op, logical, &geom);
6466 map = em->map_lookup;
6469 stripe_len = geom.stripe_len;
6470 stripe_nr = geom.stripe_nr;
6471 stripe_offset = geom.stripe_offset;
6472 raid56_full_stripe_start = geom.raid56_stripe_offset;
6473 data_stripes = nr_data_stripes(map);
6475 down_read(&dev_replace->rwsem);
6476 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6478 * Hold the semaphore for read during the whole operation, write is
6479 * requested at commit time but must wait.
6481 if (!dev_replace_is_ongoing)
6482 up_read(&dev_replace->rwsem);
6484 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6485 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6486 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6487 dev_replace->srcdev->devid,
6489 &physical_to_patch_in_first_stripe);
6493 patch_the_first_stripe_for_dev_replace = 1;
6494 } else if (mirror_num > map->num_stripes) {
6500 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6501 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6503 if (!need_full_stripe(op))
6505 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6506 if (need_full_stripe(op))
6507 num_stripes = map->num_stripes;
6508 else if (mirror_num)
6509 stripe_index = mirror_num - 1;
6511 stripe_index = find_live_mirror(fs_info, map, 0,
6512 dev_replace_is_ongoing);
6513 mirror_num = stripe_index + 1;
6516 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6517 if (need_full_stripe(op)) {
6518 num_stripes = map->num_stripes;
6519 } else if (mirror_num) {
6520 stripe_index = mirror_num - 1;
6525 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6526 u32 factor = map->num_stripes / map->sub_stripes;
6528 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6529 stripe_index *= map->sub_stripes;
6531 if (need_full_stripe(op))
6532 num_stripes = map->sub_stripes;
6533 else if (mirror_num)
6534 stripe_index += mirror_num - 1;
6536 int old_stripe_index = stripe_index;
6537 stripe_index = find_live_mirror(fs_info, map,
6539 dev_replace_is_ongoing);
6540 mirror_num = stripe_index - old_stripe_index + 1;
6543 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6544 ASSERT(map->stripe_len == BTRFS_STRIPE_LEN);
6545 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6546 /* push stripe_nr back to the start of the full stripe */
6547 stripe_nr = div64_u64(raid56_full_stripe_start,
6548 stripe_len * data_stripes);
6550 /* RAID[56] write or recovery. Return all stripes */
6551 num_stripes = map->num_stripes;
6552 max_errors = btrfs_chunk_max_errors(map);
6554 /* Return the length to the full stripe end */
6555 *length = min(logical + *length,
6556 raid56_full_stripe_start + em->start +
6557 data_stripes * stripe_len) - logical;
6562 * Mirror #0 or #1 means the original data block.
6563 * Mirror #2 is RAID5 parity block.
6564 * Mirror #3 is RAID6 Q block.
6566 stripe_nr = div_u64_rem(stripe_nr,
6567 data_stripes, &stripe_index);
6569 stripe_index = data_stripes + mirror_num - 2;
6571 /* We distribute the parity blocks across stripes */
6572 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6574 if (!need_full_stripe(op) && mirror_num <= 1)
6579 * after this, stripe_nr is the number of stripes on this
6580 * device we have to walk to find the data, and stripe_index is
6581 * the number of our device in the stripe array
6583 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6585 mirror_num = stripe_index + 1;
6587 if (stripe_index >= map->num_stripes) {
6589 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6590 stripe_index, map->num_stripes);
6595 num_alloc_stripes = num_stripes;
6596 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6597 if (op == BTRFS_MAP_WRITE)
6598 num_alloc_stripes <<= 1;
6599 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6600 num_alloc_stripes++;
6601 tgtdev_indexes = num_stripes;
6605 * If this I/O maps to a single device, try to return the device and
6606 * physical block information on the stack instead of allocating an
6607 * I/O context structure.
6609 if (smap && num_alloc_stripes == 1 &&
6610 !((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) && mirror_num > 1) &&
6611 (!need_full_stripe(op) || !dev_replace_is_ongoing ||
6612 !dev_replace->tgtdev)) {
6613 if (patch_the_first_stripe_for_dev_replace) {
6614 smap->dev = dev_replace->tgtdev;
6615 smap->physical = physical_to_patch_in_first_stripe;
6617 *mirror_num_ret = map->num_stripes + 1;
6619 set_io_stripe(smap, map, stripe_index, stripe_offset,
6622 *mirror_num_ret = mirror_num;
6629 bioc = alloc_btrfs_io_context(fs_info, num_alloc_stripes, tgtdev_indexes);
6635 for (i = 0; i < num_stripes; i++) {
6636 set_io_stripe(&bioc->stripes[i], map, stripe_index, stripe_offset,
6641 /* Build raid_map */
6642 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6643 (need_full_stripe(op) || mirror_num > 1)) {
6647 /* Work out the disk rotation on this stripe-set */
6648 div_u64_rem(stripe_nr, num_stripes, &rot);
6650 /* Fill in the logical address of each stripe */
6651 tmp = stripe_nr * data_stripes;
6652 for (i = 0; i < data_stripes; i++)
6653 bioc->raid_map[(i + rot) % num_stripes] =
6654 em->start + (tmp + i) * map->stripe_len;
6656 bioc->raid_map[(i + rot) % map->num_stripes] = RAID5_P_STRIPE;
6657 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6658 bioc->raid_map[(i + rot + 1) % num_stripes] =
6661 sort_parity_stripes(bioc, num_stripes);
6664 if (need_full_stripe(op))
6665 max_errors = btrfs_chunk_max_errors(map);
6667 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6668 need_full_stripe(op)) {
6669 handle_ops_on_dev_replace(op, &bioc, dev_replace, logical,
6670 &num_stripes, &max_errors);
6674 bioc->map_type = map->type;
6675 bioc->num_stripes = num_stripes;
6676 bioc->max_errors = max_errors;
6677 bioc->mirror_num = mirror_num;
6680 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6681 * mirror_num == num_stripes + 1 && dev_replace target drive is
6682 * available as a mirror
6684 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6685 WARN_ON(num_stripes > 1);
6686 bioc->stripes[0].dev = dev_replace->tgtdev;
6687 bioc->stripes[0].physical = physical_to_patch_in_first_stripe;
6688 bioc->mirror_num = map->num_stripes + 1;
6691 if (dev_replace_is_ongoing) {
6692 lockdep_assert_held(&dev_replace->rwsem);
6693 /* Unlock and let waiting writers proceed */
6694 up_read(&dev_replace->rwsem);
6696 free_extent_map(em);
6700 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6701 u64 logical, u64 *length,
6702 struct btrfs_io_context **bioc_ret, int mirror_num)
6704 return __btrfs_map_block(fs_info, op, logical, length, bioc_ret,
6705 NULL, &mirror_num, 0);
6708 /* For Scrub/replace */
6709 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6710 u64 logical, u64 *length,
6711 struct btrfs_io_context **bioc_ret)
6713 return __btrfs_map_block(fs_info, op, logical, length, bioc_ret,
6718 * Initialize a btrfs_bio structure. This skips the embedded bio itself as it
6719 * is already initialized by the block layer.
6721 static inline void btrfs_bio_init(struct btrfs_bio *bbio,
6722 btrfs_bio_end_io_t end_io, void *private)
6724 memset(bbio, 0, offsetof(struct btrfs_bio, bio));
6725 bbio->end_io = end_io;
6726 bbio->private = private;
6730 * Allocate a btrfs_bio structure. The btrfs_bio is the main I/O container for
6731 * btrfs, and is used for all I/O submitted through btrfs_submit_bio.
6733 * Just like the underlying bio_alloc_bioset it will not fail as it is backed by
6736 struct bio *btrfs_bio_alloc(unsigned int nr_vecs, blk_opf_t opf,
6737 btrfs_bio_end_io_t end_io, void *private)
6741 bio = bio_alloc_bioset(NULL, nr_vecs, opf, GFP_NOFS, &btrfs_bioset);
6742 btrfs_bio_init(btrfs_bio(bio), end_io, private);
6746 struct bio *btrfs_bio_clone_partial(struct bio *orig, u64 offset, u64 size,
6747 btrfs_bio_end_io_t end_io, void *private)
6750 struct btrfs_bio *bbio;
6752 ASSERT(offset <= UINT_MAX && size <= UINT_MAX);
6754 bio = bio_alloc_clone(orig->bi_bdev, orig, GFP_NOFS, &btrfs_bioset);
6755 bbio = btrfs_bio(bio);
6756 btrfs_bio_init(bbio, end_io, private);
6758 bio_trim(bio, offset >> 9, size >> 9);
6759 bbio->iter = bio->bi_iter;
6763 static void btrfs_log_dev_io_error(struct bio *bio, struct btrfs_device *dev)
6765 if (!dev || !dev->bdev)
6767 if (bio->bi_status != BLK_STS_IOERR && bio->bi_status != BLK_STS_TARGET)
6770 if (btrfs_op(bio) == BTRFS_MAP_WRITE)
6771 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
6772 else if (!(bio->bi_opf & REQ_RAHEAD))
6773 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS);
6774 if (bio->bi_opf & REQ_PREFLUSH)
6775 btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_FLUSH_ERRS);
6778 static struct workqueue_struct *btrfs_end_io_wq(struct btrfs_fs_info *fs_info,
6781 if (bio->bi_opf & REQ_META)
6782 return fs_info->endio_meta_workers;
6783 return fs_info->endio_workers;
6786 static void btrfs_end_bio_work(struct work_struct *work)
6788 struct btrfs_bio *bbio =
6789 container_of(work, struct btrfs_bio, end_io_work);
6794 static void btrfs_simple_end_io(struct bio *bio)
6796 struct btrfs_fs_info *fs_info = bio->bi_private;
6797 struct btrfs_bio *bbio = btrfs_bio(bio);
6799 btrfs_bio_counter_dec(fs_info);
6802 btrfs_log_dev_io_error(bio, bbio->device);
6804 if (bio_op(bio) == REQ_OP_READ) {
6805 INIT_WORK(&bbio->end_io_work, btrfs_end_bio_work);
6806 queue_work(btrfs_end_io_wq(fs_info, bio), &bbio->end_io_work);
6812 static void btrfs_raid56_end_io(struct bio *bio)
6814 struct btrfs_io_context *bioc = bio->bi_private;
6815 struct btrfs_bio *bbio = btrfs_bio(bio);
6817 btrfs_bio_counter_dec(bioc->fs_info);
6818 bbio->mirror_num = bioc->mirror_num;
6821 btrfs_put_bioc(bioc);
6824 static void btrfs_orig_write_end_io(struct bio *bio)
6826 struct btrfs_io_stripe *stripe = bio->bi_private;
6827 struct btrfs_io_context *bioc = stripe->bioc;
6828 struct btrfs_bio *bbio = btrfs_bio(bio);
6830 btrfs_bio_counter_dec(bioc->fs_info);
6832 if (bio->bi_status) {
6833 atomic_inc(&bioc->error);
6834 btrfs_log_dev_io_error(bio, stripe->dev);
6838 * Only send an error to the higher layers if it is beyond the tolerance
6841 if (atomic_read(&bioc->error) > bioc->max_errors)
6842 bio->bi_status = BLK_STS_IOERR;
6844 bio->bi_status = BLK_STS_OK;
6847 btrfs_put_bioc(bioc);
6850 static void btrfs_clone_write_end_io(struct bio *bio)
6852 struct btrfs_io_stripe *stripe = bio->bi_private;
6854 if (bio->bi_status) {
6855 atomic_inc(&stripe->bioc->error);
6856 btrfs_log_dev_io_error(bio, stripe->dev);
6859 /* Pass on control to the original bio this one was cloned from */
6860 bio_endio(stripe->bioc->orig_bio);
6864 static void btrfs_submit_dev_bio(struct btrfs_device *dev, struct bio *bio)
6866 if (!dev || !dev->bdev ||
6867 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6868 (btrfs_op(bio) == BTRFS_MAP_WRITE &&
6869 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6874 bio_set_dev(bio, dev->bdev);
6877 * For zone append writing, bi_sector must point the beginning of the
6880 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
6881 u64 physical = bio->bi_iter.bi_sector << SECTOR_SHIFT;
6883 if (btrfs_dev_is_sequential(dev, physical)) {
6884 u64 zone_start = round_down(physical,
6885 dev->fs_info->zone_size);
6887 bio->bi_iter.bi_sector = zone_start >> SECTOR_SHIFT;
6889 bio->bi_opf &= ~REQ_OP_ZONE_APPEND;
6890 bio->bi_opf |= REQ_OP_WRITE;
6893 btrfs_debug_in_rcu(dev->fs_info,
6894 "%s: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6895 __func__, bio_op(bio), bio->bi_opf, bio->bi_iter.bi_sector,
6896 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6897 dev->devid, bio->bi_iter.bi_size);
6899 btrfsic_check_bio(bio);
6903 static void btrfs_submit_mirrored_bio(struct btrfs_io_context *bioc, int dev_nr)
6905 struct bio *orig_bio = bioc->orig_bio, *bio;
6907 ASSERT(bio_op(orig_bio) != REQ_OP_READ);
6909 /* Reuse the bio embedded into the btrfs_bio for the last mirror */
6910 if (dev_nr == bioc->num_stripes - 1) {
6912 bio->bi_end_io = btrfs_orig_write_end_io;
6914 bio = bio_alloc_clone(NULL, orig_bio, GFP_NOFS, &fs_bio_set);
6915 bio_inc_remaining(orig_bio);
6916 bio->bi_end_io = btrfs_clone_write_end_io;
6919 bio->bi_private = &bioc->stripes[dev_nr];
6920 bio->bi_iter.bi_sector = bioc->stripes[dev_nr].physical >> SECTOR_SHIFT;
6921 bioc->stripes[dev_nr].bioc = bioc;
6922 btrfs_submit_dev_bio(bioc->stripes[dev_nr].dev, bio);
6925 void btrfs_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio, int mirror_num)
6927 u64 logical = bio->bi_iter.bi_sector << 9;
6928 u64 length = bio->bi_iter.bi_size;
6929 u64 map_length = length;
6930 struct btrfs_io_context *bioc = NULL;
6931 struct btrfs_io_stripe smap;
6934 btrfs_bio_counter_inc_blocked(fs_info);
6935 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
6936 &bioc, &smap, &mirror_num, 1);
6938 btrfs_bio_counter_dec(fs_info);
6939 btrfs_bio_end_io(btrfs_bio(bio), errno_to_blk_status(ret));
6943 if (map_length < length) {
6945 "mapping failed logical %llu bio len %llu len %llu",
6946 logical, length, map_length);
6951 /* Single mirror read/write fast path */
6952 btrfs_bio(bio)->mirror_num = mirror_num;
6953 btrfs_bio(bio)->device = smap.dev;
6954 bio->bi_iter.bi_sector = smap.physical >> SECTOR_SHIFT;
6955 bio->bi_private = fs_info;
6956 bio->bi_end_io = btrfs_simple_end_io;
6957 btrfs_submit_dev_bio(smap.dev, bio);
6958 } else if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6959 /* Parity RAID write or read recovery */
6960 bio->bi_private = bioc;
6961 bio->bi_end_io = btrfs_raid56_end_io;
6962 if (bio_op(bio) == REQ_OP_READ)
6963 raid56_parity_recover(bio, bioc, mirror_num);
6965 raid56_parity_write(bio, bioc);
6967 /* Write to multiple mirrors */
6968 int total_devs = bioc->num_stripes;
6971 bioc->orig_bio = bio;
6972 for (dev_nr = 0; dev_nr < total_devs; dev_nr++)
6973 btrfs_submit_mirrored_bio(bioc, dev_nr);
6977 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args *args,
6978 const struct btrfs_fs_devices *fs_devices)
6980 if (args->fsid == NULL)
6982 if (memcmp(fs_devices->metadata_uuid, args->fsid, BTRFS_FSID_SIZE) == 0)
6987 static bool dev_args_match_device(const struct btrfs_dev_lookup_args *args,
6988 const struct btrfs_device *device)
6990 if (args->missing) {
6991 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) &&
6997 if (device->devid != args->devid)
6999 if (args->uuid && memcmp(device->uuid, args->uuid, BTRFS_UUID_SIZE) != 0)
7005 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
7008 * If devid and uuid are both specified, the match must be exact, otherwise
7009 * only devid is used.
7011 struct btrfs_device *btrfs_find_device(const struct btrfs_fs_devices *fs_devices,
7012 const struct btrfs_dev_lookup_args *args)
7014 struct btrfs_device *device;
7015 struct btrfs_fs_devices *seed_devs;
7017 if (dev_args_match_fs_devices(args, fs_devices)) {
7018 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7019 if (dev_args_match_device(args, device))
7024 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7025 if (!dev_args_match_fs_devices(args, seed_devs))
7027 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7028 if (dev_args_match_device(args, device))
7036 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
7037 u64 devid, u8 *dev_uuid)
7039 struct btrfs_device *device;
7040 unsigned int nofs_flag;
7043 * We call this under the chunk_mutex, so we want to use NOFS for this
7044 * allocation, however we don't want to change btrfs_alloc_device() to
7045 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
7048 nofs_flag = memalloc_nofs_save();
7049 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
7050 memalloc_nofs_restore(nofs_flag);
7054 list_add(&device->dev_list, &fs_devices->devices);
7055 device->fs_devices = fs_devices;
7056 fs_devices->num_devices++;
7058 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7059 fs_devices->missing_devices++;
7065 * btrfs_alloc_device - allocate struct btrfs_device
7066 * @fs_info: used only for generating a new devid, can be NULL if
7067 * devid is provided (i.e. @devid != NULL).
7068 * @devid: a pointer to devid for this device. If NULL a new devid
7070 * @uuid: a pointer to UUID for this device. If NULL a new UUID
7073 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
7074 * on error. Returned struct is not linked onto any lists and must be
7075 * destroyed with btrfs_free_device.
7077 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
7081 struct btrfs_device *dev;
7084 if (WARN_ON(!devid && !fs_info))
7085 return ERR_PTR(-EINVAL);
7087 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
7089 return ERR_PTR(-ENOMEM);
7091 INIT_LIST_HEAD(&dev->dev_list);
7092 INIT_LIST_HEAD(&dev->dev_alloc_list);
7093 INIT_LIST_HEAD(&dev->post_commit_list);
7095 atomic_set(&dev->dev_stats_ccnt, 0);
7096 btrfs_device_data_ordered_init(dev);
7097 extent_io_tree_init(fs_info, &dev->alloc_state,
7098 IO_TREE_DEVICE_ALLOC_STATE, NULL);
7105 ret = find_next_devid(fs_info, &tmp);
7107 btrfs_free_device(dev);
7108 return ERR_PTR(ret);
7114 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
7116 generate_random_uuid(dev->uuid);
7121 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
7122 u64 devid, u8 *uuid, bool error)
7125 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
7128 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
7132 u64 btrfs_calc_stripe_length(const struct extent_map *em)
7134 const struct map_lookup *map = em->map_lookup;
7135 const int data_stripes = calc_data_stripes(map->type, map->num_stripes);
7137 return div_u64(em->len, data_stripes);
7140 #if BITS_PER_LONG == 32
7142 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
7143 * can't be accessed on 32bit systems.
7145 * This function do mount time check to reject the fs if it already has
7146 * metadata chunk beyond that limit.
7148 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
7149 u64 logical, u64 length, u64 type)
7151 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7154 if (logical + length < MAX_LFS_FILESIZE)
7157 btrfs_err_32bit_limit(fs_info);
7162 * This is to give early warning for any metadata chunk reaching
7163 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
7164 * Although we can still access the metadata, it's not going to be possible
7165 * once the limit is reached.
7167 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
7168 u64 logical, u64 length, u64 type)
7170 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7173 if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
7176 btrfs_warn_32bit_limit(fs_info);
7180 static struct btrfs_device *handle_missing_device(struct btrfs_fs_info *fs_info,
7181 u64 devid, u8 *uuid)
7183 struct btrfs_device *dev;
7185 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7186 btrfs_report_missing_device(fs_info, devid, uuid, true);
7187 return ERR_PTR(-ENOENT);
7190 dev = add_missing_dev(fs_info->fs_devices, devid, uuid);
7192 btrfs_err(fs_info, "failed to init missing device %llu: %ld",
7193 devid, PTR_ERR(dev));
7196 btrfs_report_missing_device(fs_info, devid, uuid, false);
7201 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
7202 struct btrfs_chunk *chunk)
7204 BTRFS_DEV_LOOKUP_ARGS(args);
7205 struct btrfs_fs_info *fs_info = leaf->fs_info;
7206 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7207 struct map_lookup *map;
7208 struct extent_map *em;
7213 u8 uuid[BTRFS_UUID_SIZE];
7219 logical = key->offset;
7220 length = btrfs_chunk_length(leaf, chunk);
7221 type = btrfs_chunk_type(leaf, chunk);
7222 index = btrfs_bg_flags_to_raid_index(type);
7223 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
7225 #if BITS_PER_LONG == 32
7226 ret = check_32bit_meta_chunk(fs_info, logical, length, type);
7229 warn_32bit_meta_chunk(fs_info, logical, length, type);
7233 * Only need to verify chunk item if we're reading from sys chunk array,
7234 * as chunk item in tree block is already verified by tree-checker.
7236 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
7237 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
7242 read_lock(&map_tree->lock);
7243 em = lookup_extent_mapping(map_tree, logical, 1);
7244 read_unlock(&map_tree->lock);
7246 /* already mapped? */
7247 if (em && em->start <= logical && em->start + em->len > logical) {
7248 free_extent_map(em);
7251 free_extent_map(em);
7254 em = alloc_extent_map();
7257 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
7259 free_extent_map(em);
7263 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
7264 em->map_lookup = map;
7265 em->start = logical;
7268 em->block_start = 0;
7269 em->block_len = em->len;
7271 map->num_stripes = num_stripes;
7272 map->io_width = btrfs_chunk_io_width(leaf, chunk);
7273 map->io_align = btrfs_chunk_io_align(leaf, chunk);
7274 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
7277 * We can't use the sub_stripes value, as for profiles other than
7278 * RAID10, they may have 0 as sub_stripes for filesystems created by
7279 * older mkfs (<v5.4).
7280 * In that case, it can cause divide-by-zero errors later.
7281 * Since currently sub_stripes is fixed for each profile, let's
7282 * use the trusted value instead.
7284 map->sub_stripes = btrfs_raid_array[index].sub_stripes;
7285 map->verified_stripes = 0;
7286 em->orig_block_len = btrfs_calc_stripe_length(em);
7287 for (i = 0; i < num_stripes; i++) {
7288 map->stripes[i].physical =
7289 btrfs_stripe_offset_nr(leaf, chunk, i);
7290 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
7292 read_extent_buffer(leaf, uuid, (unsigned long)
7293 btrfs_stripe_dev_uuid_nr(chunk, i),
7296 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, &args);
7297 if (!map->stripes[i].dev) {
7298 map->stripes[i].dev = handle_missing_device(fs_info,
7300 if (IS_ERR(map->stripes[i].dev)) {
7301 ret = PTR_ERR(map->stripes[i].dev);
7302 free_extent_map(em);
7307 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
7308 &(map->stripes[i].dev->dev_state));
7311 write_lock(&map_tree->lock);
7312 ret = add_extent_mapping(map_tree, em, 0);
7313 write_unlock(&map_tree->lock);
7316 "failed to add chunk map, start=%llu len=%llu: %d",
7317 em->start, em->len, ret);
7319 free_extent_map(em);
7324 static void fill_device_from_item(struct extent_buffer *leaf,
7325 struct btrfs_dev_item *dev_item,
7326 struct btrfs_device *device)
7330 device->devid = btrfs_device_id(leaf, dev_item);
7331 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7332 device->total_bytes = device->disk_total_bytes;
7333 device->commit_total_bytes = device->disk_total_bytes;
7334 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
7335 device->commit_bytes_used = device->bytes_used;
7336 device->type = btrfs_device_type(leaf, dev_item);
7337 device->io_align = btrfs_device_io_align(leaf, dev_item);
7338 device->io_width = btrfs_device_io_width(leaf, dev_item);
7339 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
7340 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
7341 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
7343 ptr = btrfs_device_uuid(dev_item);
7344 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
7347 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
7350 struct btrfs_fs_devices *fs_devices;
7353 lockdep_assert_held(&uuid_mutex);
7356 /* This will match only for multi-device seed fs */
7357 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
7358 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7362 fs_devices = find_fsid(fsid, NULL);
7364 if (!btrfs_test_opt(fs_info, DEGRADED))
7365 return ERR_PTR(-ENOENT);
7367 fs_devices = alloc_fs_devices(fsid, NULL);
7368 if (IS_ERR(fs_devices))
7371 fs_devices->seeding = true;
7372 fs_devices->opened = 1;
7377 * Upon first call for a seed fs fsid, just create a private copy of the
7378 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7380 fs_devices = clone_fs_devices(fs_devices);
7381 if (IS_ERR(fs_devices))
7384 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
7386 free_fs_devices(fs_devices);
7387 return ERR_PTR(ret);
7390 if (!fs_devices->seeding) {
7391 close_fs_devices(fs_devices);
7392 free_fs_devices(fs_devices);
7393 return ERR_PTR(-EINVAL);
7396 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7401 static int read_one_dev(struct extent_buffer *leaf,
7402 struct btrfs_dev_item *dev_item)
7404 BTRFS_DEV_LOOKUP_ARGS(args);
7405 struct btrfs_fs_info *fs_info = leaf->fs_info;
7406 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7407 struct btrfs_device *device;
7410 u8 fs_uuid[BTRFS_FSID_SIZE];
7411 u8 dev_uuid[BTRFS_UUID_SIZE];
7413 devid = btrfs_device_id(leaf, dev_item);
7415 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7417 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7419 args.uuid = dev_uuid;
7420 args.fsid = fs_uuid;
7422 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7423 fs_devices = open_seed_devices(fs_info, fs_uuid);
7424 if (IS_ERR(fs_devices))
7425 return PTR_ERR(fs_devices);
7428 device = btrfs_find_device(fs_info->fs_devices, &args);
7430 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7431 btrfs_report_missing_device(fs_info, devid,
7436 device = add_missing_dev(fs_devices, devid, dev_uuid);
7437 if (IS_ERR(device)) {
7439 "failed to add missing dev %llu: %ld",
7440 devid, PTR_ERR(device));
7441 return PTR_ERR(device);
7443 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7445 if (!device->bdev) {
7446 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7447 btrfs_report_missing_device(fs_info,
7448 devid, dev_uuid, true);
7451 btrfs_report_missing_device(fs_info, devid,
7455 if (!device->bdev &&
7456 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7458 * this happens when a device that was properly setup
7459 * in the device info lists suddenly goes bad.
7460 * device->bdev is NULL, and so we have to set
7461 * device->missing to one here
7463 device->fs_devices->missing_devices++;
7464 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7467 /* Move the device to its own fs_devices */
7468 if (device->fs_devices != fs_devices) {
7469 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7470 &device->dev_state));
7472 list_move(&device->dev_list, &fs_devices->devices);
7473 device->fs_devices->num_devices--;
7474 fs_devices->num_devices++;
7476 device->fs_devices->missing_devices--;
7477 fs_devices->missing_devices++;
7479 device->fs_devices = fs_devices;
7483 if (device->fs_devices != fs_info->fs_devices) {
7484 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7485 if (device->generation !=
7486 btrfs_device_generation(leaf, dev_item))
7490 fill_device_from_item(leaf, dev_item, device);
7492 u64 max_total_bytes = bdev_nr_bytes(device->bdev);
7494 if (device->total_bytes > max_total_bytes) {
7496 "device total_bytes should be at most %llu but found %llu",
7497 max_total_bytes, device->total_bytes);
7501 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7502 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7503 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7504 device->fs_devices->total_rw_bytes += device->total_bytes;
7505 atomic64_add(device->total_bytes - device->bytes_used,
7506 &fs_info->free_chunk_space);
7512 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7514 struct btrfs_super_block *super_copy = fs_info->super_copy;
7515 struct extent_buffer *sb;
7516 struct btrfs_disk_key *disk_key;
7517 struct btrfs_chunk *chunk;
7519 unsigned long sb_array_offset;
7526 struct btrfs_key key;
7528 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7531 * We allocated a dummy extent, just to use extent buffer accessors.
7532 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
7533 * that's fine, we will not go beyond system chunk array anyway.
7535 sb = alloc_dummy_extent_buffer(fs_info, BTRFS_SUPER_INFO_OFFSET);
7538 set_extent_buffer_uptodate(sb);
7540 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7541 array_size = btrfs_super_sys_array_size(super_copy);
7543 array_ptr = super_copy->sys_chunk_array;
7544 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7547 while (cur_offset < array_size) {
7548 disk_key = (struct btrfs_disk_key *)array_ptr;
7549 len = sizeof(*disk_key);
7550 if (cur_offset + len > array_size)
7551 goto out_short_read;
7553 btrfs_disk_key_to_cpu(&key, disk_key);
7556 sb_array_offset += len;
7559 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
7561 "unexpected item type %u in sys_array at offset %u",
7562 (u32)key.type, cur_offset);
7567 chunk = (struct btrfs_chunk *)sb_array_offset;
7569 * At least one btrfs_chunk with one stripe must be present,
7570 * exact stripe count check comes afterwards
7572 len = btrfs_chunk_item_size(1);
7573 if (cur_offset + len > array_size)
7574 goto out_short_read;
7576 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7579 "invalid number of stripes %u in sys_array at offset %u",
7580 num_stripes, cur_offset);
7585 type = btrfs_chunk_type(sb, chunk);
7586 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7588 "invalid chunk type %llu in sys_array at offset %u",
7594 len = btrfs_chunk_item_size(num_stripes);
7595 if (cur_offset + len > array_size)
7596 goto out_short_read;
7598 ret = read_one_chunk(&key, sb, chunk);
7603 sb_array_offset += len;
7606 clear_extent_buffer_uptodate(sb);
7607 free_extent_buffer_stale(sb);
7611 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7613 clear_extent_buffer_uptodate(sb);
7614 free_extent_buffer_stale(sb);
7619 * Check if all chunks in the fs are OK for read-write degraded mount
7621 * If the @failing_dev is specified, it's accounted as missing.
7623 * Return true if all chunks meet the minimal RW mount requirements.
7624 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7626 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7627 struct btrfs_device *failing_dev)
7629 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7630 struct extent_map *em;
7634 read_lock(&map_tree->lock);
7635 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7636 read_unlock(&map_tree->lock);
7637 /* No chunk at all? Return false anyway */
7643 struct map_lookup *map;
7648 map = em->map_lookup;
7650 btrfs_get_num_tolerated_disk_barrier_failures(
7652 for (i = 0; i < map->num_stripes; i++) {
7653 struct btrfs_device *dev = map->stripes[i].dev;
7655 if (!dev || !dev->bdev ||
7656 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7657 dev->last_flush_error)
7659 else if (failing_dev && failing_dev == dev)
7662 if (missing > max_tolerated) {
7665 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7666 em->start, missing, max_tolerated);
7667 free_extent_map(em);
7671 next_start = extent_map_end(em);
7672 free_extent_map(em);
7674 read_lock(&map_tree->lock);
7675 em = lookup_extent_mapping(map_tree, next_start,
7676 (u64)(-1) - next_start);
7677 read_unlock(&map_tree->lock);
7683 static void readahead_tree_node_children(struct extent_buffer *node)
7686 const int nr_items = btrfs_header_nritems(node);
7688 for (i = 0; i < nr_items; i++)
7689 btrfs_readahead_node_child(node, i);
7692 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7694 struct btrfs_root *root = fs_info->chunk_root;
7695 struct btrfs_path *path;
7696 struct extent_buffer *leaf;
7697 struct btrfs_key key;
7698 struct btrfs_key found_key;
7703 u64 last_ra_node = 0;
7705 path = btrfs_alloc_path();
7710 * uuid_mutex is needed only if we are mounting a sprout FS
7711 * otherwise we don't need it.
7713 mutex_lock(&uuid_mutex);
7716 * It is possible for mount and umount to race in such a way that
7717 * we execute this code path, but open_fs_devices failed to clear
7718 * total_rw_bytes. We certainly want it cleared before reading the
7719 * device items, so clear it here.
7721 fs_info->fs_devices->total_rw_bytes = 0;
7724 * Lockdep complains about possible circular locking dependency between
7725 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7726 * used for freeze procection of a fs (struct super_block.s_writers),
7727 * which we take when starting a transaction, and extent buffers of the
7728 * chunk tree if we call read_one_dev() while holding a lock on an
7729 * extent buffer of the chunk tree. Since we are mounting the filesystem
7730 * and at this point there can't be any concurrent task modifying the
7731 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7733 ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
7734 path->skip_locking = 1;
7737 * Read all device items, and then all the chunk items. All
7738 * device items are found before any chunk item (their object id
7739 * is smaller than the lowest possible object id for a chunk
7740 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7742 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7745 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
7746 struct extent_buffer *node = path->nodes[1];
7748 leaf = path->nodes[0];
7749 slot = path->slots[0];
7752 if (last_ra_node != node->start) {
7753 readahead_tree_node_children(node);
7754 last_ra_node = node->start;
7757 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7758 struct btrfs_dev_item *dev_item;
7759 dev_item = btrfs_item_ptr(leaf, slot,
7760 struct btrfs_dev_item);
7761 ret = read_one_dev(leaf, dev_item);
7765 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7766 struct btrfs_chunk *chunk;
7769 * We are only called at mount time, so no need to take
7770 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7771 * we always lock first fs_info->chunk_mutex before
7772 * acquiring any locks on the chunk tree. This is a
7773 * requirement for chunk allocation, see the comment on
7774 * top of btrfs_chunk_alloc() for details.
7776 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7777 ret = read_one_chunk(&found_key, leaf, chunk);
7782 /* Catch error found during iteration */
7789 * After loading chunk tree, we've got all device information,
7790 * do another round of validation checks.
7792 if (total_dev != fs_info->fs_devices->total_devices) {
7794 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7795 btrfs_super_num_devices(fs_info->super_copy),
7797 fs_info->fs_devices->total_devices = total_dev;
7798 btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
7800 if (btrfs_super_total_bytes(fs_info->super_copy) <
7801 fs_info->fs_devices->total_rw_bytes) {
7803 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7804 btrfs_super_total_bytes(fs_info->super_copy),
7805 fs_info->fs_devices->total_rw_bytes);
7811 mutex_unlock(&uuid_mutex);
7813 btrfs_free_path(path);
7817 int btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7819 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7820 struct btrfs_device *device;
7823 fs_devices->fs_info = fs_info;
7825 mutex_lock(&fs_devices->device_list_mutex);
7826 list_for_each_entry(device, &fs_devices->devices, dev_list)
7827 device->fs_info = fs_info;
7829 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7830 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7831 device->fs_info = fs_info;
7832 ret = btrfs_get_dev_zone_info(device, false);
7837 seed_devs->fs_info = fs_info;
7839 mutex_unlock(&fs_devices->device_list_mutex);
7844 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7845 const struct btrfs_dev_stats_item *ptr,
7850 read_extent_buffer(eb, &val,
7851 offsetof(struct btrfs_dev_stats_item, values) +
7852 ((unsigned long)ptr) + (index * sizeof(u64)),
7857 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7858 struct btrfs_dev_stats_item *ptr,
7861 write_extent_buffer(eb, &val,
7862 offsetof(struct btrfs_dev_stats_item, values) +
7863 ((unsigned long)ptr) + (index * sizeof(u64)),
7867 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7868 struct btrfs_path *path)
7870 struct btrfs_dev_stats_item *ptr;
7871 struct extent_buffer *eb;
7872 struct btrfs_key key;
7876 if (!device->fs_info->dev_root)
7879 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7880 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7881 key.offset = device->devid;
7882 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7884 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7885 btrfs_dev_stat_set(device, i, 0);
7886 device->dev_stats_valid = 1;
7887 btrfs_release_path(path);
7888 return ret < 0 ? ret : 0;
7890 slot = path->slots[0];
7891 eb = path->nodes[0];
7892 item_size = btrfs_item_size(eb, slot);
7894 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7896 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7897 if (item_size >= (1 + i) * sizeof(__le64))
7898 btrfs_dev_stat_set(device, i,
7899 btrfs_dev_stats_value(eb, ptr, i));
7901 btrfs_dev_stat_set(device, i, 0);
7904 device->dev_stats_valid = 1;
7905 btrfs_dev_stat_print_on_load(device);
7906 btrfs_release_path(path);
7911 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7913 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7914 struct btrfs_device *device;
7915 struct btrfs_path *path = NULL;
7918 path = btrfs_alloc_path();
7922 mutex_lock(&fs_devices->device_list_mutex);
7923 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7924 ret = btrfs_device_init_dev_stats(device, path);
7928 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7929 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7930 ret = btrfs_device_init_dev_stats(device, path);
7936 mutex_unlock(&fs_devices->device_list_mutex);
7938 btrfs_free_path(path);
7942 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7943 struct btrfs_device *device)
7945 struct btrfs_fs_info *fs_info = trans->fs_info;
7946 struct btrfs_root *dev_root = fs_info->dev_root;
7947 struct btrfs_path *path;
7948 struct btrfs_key key;
7949 struct extent_buffer *eb;
7950 struct btrfs_dev_stats_item *ptr;
7954 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7955 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7956 key.offset = device->devid;
7958 path = btrfs_alloc_path();
7961 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7963 btrfs_warn_in_rcu(fs_info,
7964 "error %d while searching for dev_stats item for device %s",
7965 ret, rcu_str_deref(device->name));
7970 btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7971 /* need to delete old one and insert a new one */
7972 ret = btrfs_del_item(trans, dev_root, path);
7974 btrfs_warn_in_rcu(fs_info,
7975 "delete too small dev_stats item for device %s failed %d",
7976 rcu_str_deref(device->name), ret);
7983 /* need to insert a new item */
7984 btrfs_release_path(path);
7985 ret = btrfs_insert_empty_item(trans, dev_root, path,
7986 &key, sizeof(*ptr));
7988 btrfs_warn_in_rcu(fs_info,
7989 "insert dev_stats item for device %s failed %d",
7990 rcu_str_deref(device->name), ret);
7995 eb = path->nodes[0];
7996 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7997 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7998 btrfs_set_dev_stats_value(eb, ptr, i,
7999 btrfs_dev_stat_read(device, i));
8000 btrfs_mark_buffer_dirty(eb);
8003 btrfs_free_path(path);
8008 * called from commit_transaction. Writes all changed device stats to disk.
8010 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
8012 struct btrfs_fs_info *fs_info = trans->fs_info;
8013 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
8014 struct btrfs_device *device;
8018 mutex_lock(&fs_devices->device_list_mutex);
8019 list_for_each_entry(device, &fs_devices->devices, dev_list) {
8020 stats_cnt = atomic_read(&device->dev_stats_ccnt);
8021 if (!device->dev_stats_valid || stats_cnt == 0)
8026 * There is a LOAD-LOAD control dependency between the value of
8027 * dev_stats_ccnt and updating the on-disk values which requires
8028 * reading the in-memory counters. Such control dependencies
8029 * require explicit read memory barriers.
8031 * This memory barriers pairs with smp_mb__before_atomic in
8032 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
8033 * barrier implied by atomic_xchg in
8034 * btrfs_dev_stats_read_and_reset
8038 ret = update_dev_stat_item(trans, device);
8040 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
8042 mutex_unlock(&fs_devices->device_list_mutex);
8047 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
8049 btrfs_dev_stat_inc(dev, index);
8051 if (!dev->dev_stats_valid)
8053 btrfs_err_rl_in_rcu(dev->fs_info,
8054 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
8055 rcu_str_deref(dev->name),
8056 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
8057 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
8058 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
8059 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
8060 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
8063 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
8067 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
8068 if (btrfs_dev_stat_read(dev, i) != 0)
8070 if (i == BTRFS_DEV_STAT_VALUES_MAX)
8071 return; /* all values == 0, suppress message */
8073 btrfs_info_in_rcu(dev->fs_info,
8074 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
8075 rcu_str_deref(dev->name),
8076 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
8077 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
8078 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
8079 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
8080 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
8083 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
8084 struct btrfs_ioctl_get_dev_stats *stats)
8086 BTRFS_DEV_LOOKUP_ARGS(args);
8087 struct btrfs_device *dev;
8088 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
8091 mutex_lock(&fs_devices->device_list_mutex);
8092 args.devid = stats->devid;
8093 dev = btrfs_find_device(fs_info->fs_devices, &args);
8094 mutex_unlock(&fs_devices->device_list_mutex);
8097 btrfs_warn(fs_info, "get dev_stats failed, device not found");
8099 } else if (!dev->dev_stats_valid) {
8100 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
8102 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
8103 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
8104 if (stats->nr_items > i)
8106 btrfs_dev_stat_read_and_reset(dev, i);
8108 btrfs_dev_stat_set(dev, i, 0);
8110 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
8111 current->comm, task_pid_nr(current));
8113 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
8114 if (stats->nr_items > i)
8115 stats->values[i] = btrfs_dev_stat_read(dev, i);
8117 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
8118 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
8123 * Update the size and bytes used for each device where it changed. This is
8124 * delayed since we would otherwise get errors while writing out the
8127 * Must be invoked during transaction commit.
8129 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
8131 struct btrfs_device *curr, *next;
8133 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
8135 if (list_empty(&trans->dev_update_list))
8139 * We don't need the device_list_mutex here. This list is owned by the
8140 * transaction and the transaction must complete before the device is
8143 mutex_lock(&trans->fs_info->chunk_mutex);
8144 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
8146 list_del_init(&curr->post_commit_list);
8147 curr->commit_total_bytes = curr->disk_total_bytes;
8148 curr->commit_bytes_used = curr->bytes_used;
8150 mutex_unlock(&trans->fs_info->chunk_mutex);
8154 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
8156 int btrfs_bg_type_to_factor(u64 flags)
8158 const int index = btrfs_bg_flags_to_raid_index(flags);
8160 return btrfs_raid_array[index].ncopies;
8165 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
8166 u64 chunk_offset, u64 devid,
8167 u64 physical_offset, u64 physical_len)
8169 struct btrfs_dev_lookup_args args = { .devid = devid };
8170 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
8171 struct extent_map *em;
8172 struct map_lookup *map;
8173 struct btrfs_device *dev;
8179 read_lock(&em_tree->lock);
8180 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
8181 read_unlock(&em_tree->lock);
8185 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
8186 physical_offset, devid);
8191 map = em->map_lookup;
8192 stripe_len = btrfs_calc_stripe_length(em);
8193 if (physical_len != stripe_len) {
8195 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
8196 physical_offset, devid, em->start, physical_len,
8203 * Very old mkfs.btrfs (before v4.1) will not respect the reserved
8204 * space. Although kernel can handle it without problem, better to warn
8207 if (physical_offset < BTRFS_DEVICE_RANGE_RESERVED)
8209 "devid %llu physical %llu len %llu inside the reserved space",
8210 devid, physical_offset, physical_len);
8212 for (i = 0; i < map->num_stripes; i++) {
8213 if (map->stripes[i].dev->devid == devid &&
8214 map->stripes[i].physical == physical_offset) {
8216 if (map->verified_stripes >= map->num_stripes) {
8218 "too many dev extents for chunk %llu found",
8223 map->verified_stripes++;
8229 "dev extent physical offset %llu devid %llu has no corresponding chunk",
8230 physical_offset, devid);
8234 /* Make sure no dev extent is beyond device boundary */
8235 dev = btrfs_find_device(fs_info->fs_devices, &args);
8237 btrfs_err(fs_info, "failed to find devid %llu", devid);
8242 if (physical_offset + physical_len > dev->disk_total_bytes) {
8244 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
8245 devid, physical_offset, physical_len,
8246 dev->disk_total_bytes);
8251 if (dev->zone_info) {
8252 u64 zone_size = dev->zone_info->zone_size;
8254 if (!IS_ALIGNED(physical_offset, zone_size) ||
8255 !IS_ALIGNED(physical_len, zone_size)) {
8257 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
8258 devid, physical_offset, physical_len);
8265 free_extent_map(em);
8269 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
8271 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
8272 struct extent_map *em;
8273 struct rb_node *node;
8276 read_lock(&em_tree->lock);
8277 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
8278 em = rb_entry(node, struct extent_map, rb_node);
8279 if (em->map_lookup->num_stripes !=
8280 em->map_lookup->verified_stripes) {
8282 "chunk %llu has missing dev extent, have %d expect %d",
8283 em->start, em->map_lookup->verified_stripes,
8284 em->map_lookup->num_stripes);
8290 read_unlock(&em_tree->lock);
8295 * Ensure that all dev extents are mapped to correct chunk, otherwise
8296 * later chunk allocation/free would cause unexpected behavior.
8298 * NOTE: This will iterate through the whole device tree, which should be of
8299 * the same size level as the chunk tree. This slightly increases mount time.
8301 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
8303 struct btrfs_path *path;
8304 struct btrfs_root *root = fs_info->dev_root;
8305 struct btrfs_key key;
8307 u64 prev_dev_ext_end = 0;
8311 * We don't have a dev_root because we mounted with ignorebadroots and
8312 * failed to load the root, so we want to skip the verification in this
8315 * However if the dev root is fine, but the tree itself is corrupted
8316 * we'd still fail to mount. This verification is only to make sure
8317 * writes can happen safely, so instead just bypass this check
8318 * completely in the case of IGNOREBADROOTS.
8320 if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
8324 key.type = BTRFS_DEV_EXTENT_KEY;
8327 path = btrfs_alloc_path();
8331 path->reada = READA_FORWARD;
8332 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8336 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8337 ret = btrfs_next_leaf(root, path);
8340 /* No dev extents at all? Not good */
8347 struct extent_buffer *leaf = path->nodes[0];
8348 struct btrfs_dev_extent *dext;
8349 int slot = path->slots[0];
8351 u64 physical_offset;
8355 btrfs_item_key_to_cpu(leaf, &key, slot);
8356 if (key.type != BTRFS_DEV_EXTENT_KEY)
8358 devid = key.objectid;
8359 physical_offset = key.offset;
8361 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
8362 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
8363 physical_len = btrfs_dev_extent_length(leaf, dext);
8365 /* Check if this dev extent overlaps with the previous one */
8366 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
8368 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8369 devid, physical_offset, prev_dev_ext_end);
8374 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8375 physical_offset, physical_len);
8379 prev_dev_ext_end = physical_offset + physical_len;
8381 ret = btrfs_next_item(root, path);
8390 /* Ensure all chunks have corresponding dev extents */
8391 ret = verify_chunk_dev_extent_mapping(fs_info);
8393 btrfs_free_path(path);
8398 * Check whether the given block group or device is pinned by any inode being
8399 * used as a swapfile.
8401 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8403 struct btrfs_swapfile_pin *sp;
8404 struct rb_node *node;
8406 spin_lock(&fs_info->swapfile_pins_lock);
8407 node = fs_info->swapfile_pins.rb_node;
8409 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8411 node = node->rb_left;
8412 else if (ptr > sp->ptr)
8413 node = node->rb_right;
8417 spin_unlock(&fs_info->swapfile_pins_lock);
8418 return node != NULL;
8421 static int relocating_repair_kthread(void *data)
8423 struct btrfs_block_group *cache = data;
8424 struct btrfs_fs_info *fs_info = cache->fs_info;
8428 target = cache->start;
8429 btrfs_put_block_group(cache);
8431 sb_start_write(fs_info->sb);
8432 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8434 "zoned: skip relocating block group %llu to repair: EBUSY",
8436 sb_end_write(fs_info->sb);
8440 mutex_lock(&fs_info->reclaim_bgs_lock);
8442 /* Ensure block group still exists */
8443 cache = btrfs_lookup_block_group(fs_info, target);
8447 if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags))
8450 ret = btrfs_may_alloc_data_chunk(fs_info, target);
8455 "zoned: relocating block group %llu to repair IO failure",
8457 ret = btrfs_relocate_chunk(fs_info, target);
8461 btrfs_put_block_group(cache);
8462 mutex_unlock(&fs_info->reclaim_bgs_lock);
8463 btrfs_exclop_finish(fs_info);
8464 sb_end_write(fs_info->sb);
8469 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8471 struct btrfs_block_group *cache;
8473 if (!btrfs_is_zoned(fs_info))
8476 /* Do not attempt to repair in degraded state */
8477 if (btrfs_test_opt(fs_info, DEGRADED))
8480 cache = btrfs_lookup_block_group(fs_info, logical);
8484 if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) {
8485 btrfs_put_block_group(cache);
8489 kthread_run(relocating_repair_kthread, cache,
8490 "btrfs-relocating-repair");
8495 int __init btrfs_bioset_init(void)
8497 if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
8498 offsetof(struct btrfs_bio, bio),
8504 void __cold btrfs_bioset_exit(void)
8506 bioset_exit(&btrfs_bioset);