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 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
38 [BTRFS_RAID_RAID10] = {
41 .devs_max = 0, /* 0 == as many as possible */
43 .tolerated_failures = 1,
47 .raid_name = "raid10",
48 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
49 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
51 [BTRFS_RAID_RAID1] = {
56 .tolerated_failures = 1,
61 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
62 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
64 [BTRFS_RAID_RAID1C3] = {
69 .tolerated_failures = 2,
73 .raid_name = "raid1c3",
74 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
75 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
77 [BTRFS_RAID_RAID1C4] = {
82 .tolerated_failures = 3,
86 .raid_name = "raid1c4",
87 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
88 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
95 .tolerated_failures = 0,
100 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
103 [BTRFS_RAID_RAID0] = {
108 .tolerated_failures = 0,
112 .raid_name = "raid0",
113 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
116 [BTRFS_RAID_SINGLE] = {
121 .tolerated_failures = 0,
125 .raid_name = "single",
129 [BTRFS_RAID_RAID5] = {
134 .tolerated_failures = 1,
138 .raid_name = "raid5",
139 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
140 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
142 [BTRFS_RAID_RAID6] = {
147 .tolerated_failures = 2,
151 .raid_name = "raid6",
152 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
153 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
158 * Convert block group flags (BTRFS_BLOCK_GROUP_*) to btrfs_raid_types, which
159 * can be used as index to access btrfs_raid_array[].
161 enum btrfs_raid_types __attribute_const__ btrfs_bg_flags_to_raid_index(u64 flags)
163 if (flags & BTRFS_BLOCK_GROUP_RAID10)
164 return BTRFS_RAID_RAID10;
165 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
166 return BTRFS_RAID_RAID1;
167 else if (flags & BTRFS_BLOCK_GROUP_RAID1C3)
168 return BTRFS_RAID_RAID1C3;
169 else if (flags & BTRFS_BLOCK_GROUP_RAID1C4)
170 return BTRFS_RAID_RAID1C4;
171 else if (flags & BTRFS_BLOCK_GROUP_DUP)
172 return BTRFS_RAID_DUP;
173 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
174 return BTRFS_RAID_RAID0;
175 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
176 return BTRFS_RAID_RAID5;
177 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
178 return BTRFS_RAID_RAID6;
180 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
183 const char *btrfs_bg_type_to_raid_name(u64 flags)
185 const int index = btrfs_bg_flags_to_raid_index(flags);
187 if (index >= BTRFS_NR_RAID_TYPES)
190 return btrfs_raid_array[index].raid_name;
194 * Fill @buf with textual description of @bg_flags, no more than @size_buf
195 * bytes including terminating null byte.
197 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
202 u64 flags = bg_flags;
203 u32 size_bp = size_buf;
210 #define DESCRIBE_FLAG(flag, desc) \
212 if (flags & (flag)) { \
213 ret = snprintf(bp, size_bp, "%s|", (desc)); \
214 if (ret < 0 || ret >= size_bp) \
222 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
223 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
224 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
226 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
227 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
228 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
229 btrfs_raid_array[i].raid_name);
233 ret = snprintf(bp, size_bp, "0x%llx|", flags);
237 if (size_bp < size_buf)
238 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
241 * The text is trimmed, it's up to the caller to provide sufficiently
247 static int init_first_rw_device(struct btrfs_trans_handle *trans);
248 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
249 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
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,
253 u64 logical, u64 *length,
254 struct btrfs_bio **bbio_ret,
255 int mirror_num, 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 bio_put(device->flush_bio);
405 btrfs_destroy_dev_zone_info(device);
409 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
411 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 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
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 * Check if the device in the path matches the device in the given struct device.
537 * true If it is the same device.
538 * false If it is not the same device or on error.
540 static bool device_matched(const struct btrfs_device *device, const char *path)
548 * If we are looking for a device with the matching dev_t, then skip
549 * device without a name (a missing device).
554 device_name = kzalloc(BTRFS_PATH_NAME_MAX, GFP_KERNEL);
559 scnprintf(device_name, BTRFS_PATH_NAME_MAX, "%s", rcu_str_deref(device->name));
562 ret = lookup_bdev(device_name, &dev_old);
567 ret = lookup_bdev(path, &dev_new);
571 if (dev_old == dev_new)
578 * Search and remove all stale (devices which are not mounted) devices.
579 * When both inputs are NULL, it will search and release all stale devices.
580 * path: Optional. When provided will it release all unmounted devices
581 * matching this path only.
582 * skip_dev: Optional. Will skip this device when searching for the stale
584 * Return: 0 for success or if @path is NULL.
585 * -EBUSY if @path is a mounted device.
586 * -ENOENT if @path does not match any device in the list.
588 static int btrfs_free_stale_devices(const char *path,
589 struct btrfs_device *skip_device)
591 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
592 struct btrfs_device *device, *tmp_device;
595 lockdep_assert_held(&uuid_mutex);
600 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
602 mutex_lock(&fs_devices->device_list_mutex);
603 list_for_each_entry_safe(device, tmp_device,
604 &fs_devices->devices, dev_list) {
605 if (skip_device && skip_device == device)
607 if (path && !device_matched(device, path))
609 if (fs_devices->opened) {
610 /* for an already deleted device return 0 */
611 if (path && ret != 0)
616 /* delete the stale device */
617 fs_devices->num_devices--;
618 list_del(&device->dev_list);
619 btrfs_free_device(device);
623 mutex_unlock(&fs_devices->device_list_mutex);
625 if (fs_devices->num_devices == 0) {
626 btrfs_sysfs_remove_fsid(fs_devices);
627 list_del(&fs_devices->fs_list);
628 free_fs_devices(fs_devices);
636 * This is only used on mount, and we are protected from competing things
637 * messing with our fs_devices by the uuid_mutex, thus we do not need the
638 * fs_devices->device_list_mutex here.
640 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
641 struct btrfs_device *device, fmode_t flags,
644 struct request_queue *q;
645 struct block_device *bdev;
646 struct btrfs_super_block *disk_super;
655 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
660 devid = btrfs_stack_device_id(&disk_super->dev_item);
661 if (devid != device->devid)
662 goto error_free_page;
664 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
665 goto error_free_page;
667 device->generation = btrfs_super_generation(disk_super);
669 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
670 if (btrfs_super_incompat_flags(disk_super) &
671 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
673 "BTRFS: Invalid seeding and uuid-changed device detected\n");
674 goto error_free_page;
677 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
678 fs_devices->seeding = true;
680 if (bdev_read_only(bdev))
681 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
683 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
686 q = bdev_get_queue(bdev);
687 if (!blk_queue_nonrot(q))
688 fs_devices->rotating = true;
691 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
692 device->mode = flags;
694 fs_devices->open_devices++;
695 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
696 device->devid != BTRFS_DEV_REPLACE_DEVID) {
697 fs_devices->rw_devices++;
698 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
700 btrfs_release_disk_super(disk_super);
705 btrfs_release_disk_super(disk_super);
706 blkdev_put(bdev, flags);
712 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
713 * being created with a disk that has already completed its fsid change. Such
714 * disk can belong to an fs which has its FSID changed or to one which doesn't.
715 * Handle both cases here.
717 static struct btrfs_fs_devices *find_fsid_inprogress(
718 struct btrfs_super_block *disk_super)
720 struct btrfs_fs_devices *fs_devices;
722 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
723 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
724 BTRFS_FSID_SIZE) != 0 &&
725 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
726 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
731 return find_fsid(disk_super->fsid, NULL);
735 static struct btrfs_fs_devices *find_fsid_changed(
736 struct btrfs_super_block *disk_super)
738 struct btrfs_fs_devices *fs_devices;
741 * Handles the case where scanned device is part of an fs that had
742 * multiple successful changes of FSID but currently device didn't
743 * observe it. Meaning our fsid will be different than theirs. We need
744 * to handle two subcases :
745 * 1 - The fs still continues to have different METADATA/FSID uuids.
746 * 2 - The fs is switched back to its original FSID (METADATA/FSID
749 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
751 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
752 BTRFS_FSID_SIZE) != 0 &&
753 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
754 BTRFS_FSID_SIZE) == 0 &&
755 memcmp(fs_devices->fsid, disk_super->fsid,
756 BTRFS_FSID_SIZE) != 0)
759 /* Unchanged UUIDs */
760 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
761 BTRFS_FSID_SIZE) == 0 &&
762 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
763 BTRFS_FSID_SIZE) == 0)
770 static struct btrfs_fs_devices *find_fsid_reverted_metadata(
771 struct btrfs_super_block *disk_super)
773 struct btrfs_fs_devices *fs_devices;
776 * Handle the case where the scanned device is part of an fs whose last
777 * metadata UUID change reverted it to the original FSID. At the same
778 * time * fs_devices was first created by another constitutent device
779 * which didn't fully observe the operation. This results in an
780 * btrfs_fs_devices created with metadata/fsid different AND
781 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
782 * fs_devices equal to the FSID of the disk.
784 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
785 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
786 BTRFS_FSID_SIZE) != 0 &&
787 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
788 BTRFS_FSID_SIZE) == 0 &&
789 fs_devices->fsid_change)
796 * Add new device to list of registered devices
799 * device pointer which was just added or updated when successful
800 * error pointer when failed
802 static noinline struct btrfs_device *device_list_add(const char *path,
803 struct btrfs_super_block *disk_super,
804 bool *new_device_added)
806 struct btrfs_device *device;
807 struct btrfs_fs_devices *fs_devices = NULL;
808 struct rcu_string *name;
809 u64 found_transid = btrfs_super_generation(disk_super);
810 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
811 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
812 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
813 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
814 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
816 if (fsid_change_in_progress) {
817 if (!has_metadata_uuid)
818 fs_devices = find_fsid_inprogress(disk_super);
820 fs_devices = find_fsid_changed(disk_super);
821 } else if (has_metadata_uuid) {
822 fs_devices = find_fsid_with_metadata_uuid(disk_super);
824 fs_devices = find_fsid_reverted_metadata(disk_super);
826 fs_devices = find_fsid(disk_super->fsid, NULL);
831 if (has_metadata_uuid)
832 fs_devices = alloc_fs_devices(disk_super->fsid,
833 disk_super->metadata_uuid);
835 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
837 if (IS_ERR(fs_devices))
838 return ERR_CAST(fs_devices);
840 fs_devices->fsid_change = fsid_change_in_progress;
842 mutex_lock(&fs_devices->device_list_mutex);
843 list_add(&fs_devices->fs_list, &fs_uuids);
847 mutex_lock(&fs_devices->device_list_mutex);
848 device = btrfs_find_device(fs_devices, devid,
849 disk_super->dev_item.uuid, NULL);
852 * If this disk has been pulled into an fs devices created by
853 * a device which had the CHANGING_FSID_V2 flag then replace the
854 * metadata_uuid/fsid values of the fs_devices.
856 if (fs_devices->fsid_change &&
857 found_transid > fs_devices->latest_generation) {
858 memcpy(fs_devices->fsid, disk_super->fsid,
861 if (has_metadata_uuid)
862 memcpy(fs_devices->metadata_uuid,
863 disk_super->metadata_uuid,
866 memcpy(fs_devices->metadata_uuid,
867 disk_super->fsid, BTRFS_FSID_SIZE);
869 fs_devices->fsid_change = false;
874 if (fs_devices->opened) {
875 mutex_unlock(&fs_devices->device_list_mutex);
876 return ERR_PTR(-EBUSY);
879 device = btrfs_alloc_device(NULL, &devid,
880 disk_super->dev_item.uuid);
881 if (IS_ERR(device)) {
882 mutex_unlock(&fs_devices->device_list_mutex);
883 /* we can safely leave the fs_devices entry around */
887 name = rcu_string_strdup(path, GFP_NOFS);
889 btrfs_free_device(device);
890 mutex_unlock(&fs_devices->device_list_mutex);
891 return ERR_PTR(-ENOMEM);
893 rcu_assign_pointer(device->name, name);
895 list_add_rcu(&device->dev_list, &fs_devices->devices);
896 fs_devices->num_devices++;
898 device->fs_devices = fs_devices;
899 *new_device_added = true;
901 if (disk_super->label[0])
903 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
904 disk_super->label, devid, found_transid, path,
905 current->comm, task_pid_nr(current));
908 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
909 disk_super->fsid, devid, found_transid, path,
910 current->comm, task_pid_nr(current));
912 } else if (!device->name || strcmp(device->name->str, path)) {
914 * When FS is already mounted.
915 * 1. If you are here and if the device->name is NULL that
916 * means this device was missing at time of FS mount.
917 * 2. If you are here and if the device->name is different
918 * from 'path' that means either
919 * a. The same device disappeared and reappeared with
921 * b. The missing-disk-which-was-replaced, has
924 * We must allow 1 and 2a above. But 2b would be a spurious
927 * Further in case of 1 and 2a above, the disk at 'path'
928 * would have missed some transaction when it was away and
929 * in case of 2a the stale bdev has to be updated as well.
930 * 2b must not be allowed at all time.
934 * For now, we do allow update to btrfs_fs_device through the
935 * btrfs dev scan cli after FS has been mounted. We're still
936 * tracking a problem where systems fail mount by subvolume id
937 * when we reject replacement on a mounted FS.
939 if (!fs_devices->opened && found_transid < device->generation) {
941 * That is if the FS is _not_ mounted and if you
942 * are here, that means there is more than one
943 * disk with same uuid and devid.We keep the one
944 * with larger generation number or the last-in if
945 * generation are equal.
947 mutex_unlock(&fs_devices->device_list_mutex);
948 return ERR_PTR(-EEXIST);
952 * We are going to replace the device path for a given devid,
953 * make sure it's the same device if the device is mounted
959 error = lookup_bdev(path, &path_dev);
961 mutex_unlock(&fs_devices->device_list_mutex);
962 return ERR_PTR(error);
965 if (device->bdev->bd_dev != path_dev) {
966 mutex_unlock(&fs_devices->device_list_mutex);
968 * device->fs_info may not be reliable here, so
969 * pass in a NULL instead. This avoids a
970 * possible use-after-free when the fs_info and
971 * fs_info->sb are already torn down.
973 btrfs_warn_in_rcu(NULL,
974 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
975 path, devid, found_transid,
977 task_pid_nr(current));
978 return ERR_PTR(-EEXIST);
980 btrfs_info_in_rcu(device->fs_info,
981 "devid %llu device path %s changed to %s scanned by %s (%d)",
982 devid, rcu_str_deref(device->name),
984 task_pid_nr(current));
987 name = rcu_string_strdup(path, GFP_NOFS);
989 mutex_unlock(&fs_devices->device_list_mutex);
990 return ERR_PTR(-ENOMEM);
992 rcu_string_free(device->name);
993 rcu_assign_pointer(device->name, name);
994 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
995 fs_devices->missing_devices--;
996 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1001 * Unmount does not free the btrfs_device struct but would zero
1002 * generation along with most of the other members. So just update
1003 * it back. We need it to pick the disk with largest generation
1006 if (!fs_devices->opened) {
1007 device->generation = found_transid;
1008 fs_devices->latest_generation = max_t(u64, found_transid,
1009 fs_devices->latest_generation);
1012 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
1014 mutex_unlock(&fs_devices->device_list_mutex);
1018 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1020 struct btrfs_fs_devices *fs_devices;
1021 struct btrfs_device *device;
1022 struct btrfs_device *orig_dev;
1025 lockdep_assert_held(&uuid_mutex);
1027 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1028 if (IS_ERR(fs_devices))
1031 fs_devices->total_devices = orig->total_devices;
1033 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1034 struct rcu_string *name;
1036 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1038 if (IS_ERR(device)) {
1039 ret = PTR_ERR(device);
1044 * This is ok to do without rcu read locked because we hold the
1045 * uuid mutex so nothing we touch in here is going to disappear.
1047 if (orig_dev->name) {
1048 name = rcu_string_strdup(orig_dev->name->str,
1051 btrfs_free_device(device);
1055 rcu_assign_pointer(device->name, name);
1058 list_add(&device->dev_list, &fs_devices->devices);
1059 device->fs_devices = fs_devices;
1060 fs_devices->num_devices++;
1064 free_fs_devices(fs_devices);
1065 return ERR_PTR(ret);
1068 static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
1069 struct btrfs_device **latest_dev)
1071 struct btrfs_device *device, *next;
1073 /* This is the initialized path, it is safe to release the devices. */
1074 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1075 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
1076 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1077 &device->dev_state) &&
1078 !test_bit(BTRFS_DEV_STATE_MISSING,
1079 &device->dev_state) &&
1081 device->generation > (*latest_dev)->generation)) {
1082 *latest_dev = device;
1088 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1089 * in btrfs_init_dev_replace() so just continue.
1091 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1095 blkdev_put(device->bdev, device->mode);
1096 device->bdev = NULL;
1097 fs_devices->open_devices--;
1099 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1100 list_del_init(&device->dev_alloc_list);
1101 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1102 fs_devices->rw_devices--;
1104 list_del_init(&device->dev_list);
1105 fs_devices->num_devices--;
1106 btrfs_free_device(device);
1112 * After we have read the system tree and know devids belonging to this
1113 * filesystem, remove the device which does not belong there.
1115 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices)
1117 struct btrfs_device *latest_dev = NULL;
1118 struct btrfs_fs_devices *seed_dev;
1120 mutex_lock(&uuid_mutex);
1121 __btrfs_free_extra_devids(fs_devices, &latest_dev);
1123 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1124 __btrfs_free_extra_devids(seed_dev, &latest_dev);
1126 fs_devices->latest_dev = latest_dev;
1128 mutex_unlock(&uuid_mutex);
1131 static void btrfs_close_bdev(struct btrfs_device *device)
1136 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1137 sync_blockdev(device->bdev);
1138 invalidate_bdev(device->bdev);
1141 blkdev_put(device->bdev, device->mode);
1144 static void btrfs_close_one_device(struct btrfs_device *device)
1146 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1148 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1149 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1150 list_del_init(&device->dev_alloc_list);
1151 fs_devices->rw_devices--;
1154 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1155 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
1157 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1158 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1159 fs_devices->missing_devices--;
1162 btrfs_close_bdev(device);
1164 fs_devices->open_devices--;
1165 device->bdev = NULL;
1167 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1168 btrfs_destroy_dev_zone_info(device);
1170 device->fs_info = NULL;
1171 atomic_set(&device->dev_stats_ccnt, 0);
1172 extent_io_tree_release(&device->alloc_state);
1175 * Reset the flush error record. We might have a transient flush error
1176 * in this mount, and if so we aborted the current transaction and set
1177 * the fs to an error state, guaranteeing no super blocks can be further
1178 * committed. However that error might be transient and if we unmount the
1179 * filesystem and mount it again, we should allow the mount to succeed
1180 * (btrfs_check_rw_degradable() should not fail) - if after mounting the
1181 * filesystem again we still get flush errors, then we will again abort
1182 * any transaction and set the error state, guaranteeing no commits of
1183 * unsafe super blocks.
1185 device->last_flush_error = 0;
1187 /* Verify the device is back in a pristine state */
1188 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1189 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1190 ASSERT(list_empty(&device->dev_alloc_list));
1191 ASSERT(list_empty(&device->post_commit_list));
1192 ASSERT(atomic_read(&device->reada_in_flight) == 0);
1195 static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
1197 struct btrfs_device *device, *tmp;
1199 lockdep_assert_held(&uuid_mutex);
1201 if (--fs_devices->opened > 0)
1204 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
1205 btrfs_close_one_device(device);
1207 WARN_ON(fs_devices->open_devices);
1208 WARN_ON(fs_devices->rw_devices);
1209 fs_devices->opened = 0;
1210 fs_devices->seeding = false;
1211 fs_devices->fs_info = NULL;
1214 void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1217 struct btrfs_fs_devices *tmp;
1219 mutex_lock(&uuid_mutex);
1220 close_fs_devices(fs_devices);
1221 if (!fs_devices->opened)
1222 list_splice_init(&fs_devices->seed_list, &list);
1224 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
1225 close_fs_devices(fs_devices);
1226 list_del(&fs_devices->seed_list);
1227 free_fs_devices(fs_devices);
1229 mutex_unlock(&uuid_mutex);
1232 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1233 fmode_t flags, void *holder)
1235 struct btrfs_device *device;
1236 struct btrfs_device *latest_dev = NULL;
1237 struct btrfs_device *tmp_device;
1239 flags |= FMODE_EXCL;
1241 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1245 ret = btrfs_open_one_device(fs_devices, device, flags, holder);
1247 (!latest_dev || device->generation > latest_dev->generation)) {
1248 latest_dev = device;
1249 } else if (ret == -ENODATA) {
1250 fs_devices->num_devices--;
1251 list_del(&device->dev_list);
1252 btrfs_free_device(device);
1255 if (fs_devices->open_devices == 0)
1258 fs_devices->opened = 1;
1259 fs_devices->latest_dev = latest_dev;
1260 fs_devices->total_rw_bytes = 0;
1261 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1262 fs_devices->read_policy = BTRFS_READ_POLICY_PID;
1267 static int devid_cmp(void *priv, const struct list_head *a,
1268 const struct list_head *b)
1270 const struct btrfs_device *dev1, *dev2;
1272 dev1 = list_entry(a, struct btrfs_device, dev_list);
1273 dev2 = list_entry(b, struct btrfs_device, dev_list);
1275 if (dev1->devid < dev2->devid)
1277 else if (dev1->devid > dev2->devid)
1282 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1283 fmode_t flags, void *holder)
1287 lockdep_assert_held(&uuid_mutex);
1289 * The device_list_mutex cannot be taken here in case opening the
1290 * underlying device takes further locks like open_mutex.
1292 * We also don't need the lock here as this is called during mount and
1293 * exclusion is provided by uuid_mutex
1296 if (fs_devices->opened) {
1297 fs_devices->opened++;
1300 list_sort(NULL, &fs_devices->devices, devid_cmp);
1301 ret = open_fs_devices(fs_devices, flags, holder);
1307 void btrfs_release_disk_super(struct btrfs_super_block *super)
1309 struct page *page = virt_to_page(super);
1314 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1315 u64 bytenr, u64 bytenr_orig)
1317 struct btrfs_super_block *disk_super;
1322 /* make sure our super fits in the device */
1323 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1324 return ERR_PTR(-EINVAL);
1326 /* make sure our super fits in the page */
1327 if (sizeof(*disk_super) > PAGE_SIZE)
1328 return ERR_PTR(-EINVAL);
1330 /* make sure our super doesn't straddle pages on disk */
1331 index = bytenr >> PAGE_SHIFT;
1332 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1333 return ERR_PTR(-EINVAL);
1335 /* pull in the page with our super */
1336 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1339 return ERR_CAST(page);
1341 p = page_address(page);
1343 /* align our pointer to the offset of the super block */
1344 disk_super = p + offset_in_page(bytenr);
1346 if (btrfs_super_bytenr(disk_super) != bytenr_orig ||
1347 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1348 btrfs_release_disk_super(p);
1349 return ERR_PTR(-EINVAL);
1352 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1353 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1358 int btrfs_forget_devices(const char *path)
1362 mutex_lock(&uuid_mutex);
1363 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1364 mutex_unlock(&uuid_mutex);
1370 * Look for a btrfs signature on a device. This may be called out of the mount path
1371 * and we are not allowed to call set_blocksize during the scan. The superblock
1372 * is read via pagecache
1374 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1377 struct btrfs_super_block *disk_super;
1378 bool new_device_added = false;
1379 struct btrfs_device *device = NULL;
1380 struct block_device *bdev;
1381 u64 bytenr, bytenr_orig;
1384 lockdep_assert_held(&uuid_mutex);
1387 * we would like to check all the supers, but that would make
1388 * a btrfs mount succeed after a mkfs from a different FS.
1389 * So, we need to add a special mount option to scan for
1390 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1392 flags |= FMODE_EXCL;
1394 bdev = blkdev_get_by_path(path, flags, holder);
1396 return ERR_CAST(bdev);
1398 bytenr_orig = btrfs_sb_offset(0);
1399 ret = btrfs_sb_log_location_bdev(bdev, 0, READ, &bytenr);
1401 device = ERR_PTR(ret);
1402 goto error_bdev_put;
1405 disk_super = btrfs_read_disk_super(bdev, bytenr, bytenr_orig);
1406 if (IS_ERR(disk_super)) {
1407 device = ERR_CAST(disk_super);
1408 goto error_bdev_put;
1411 device = device_list_add(path, disk_super, &new_device_added);
1412 if (!IS_ERR(device)) {
1413 if (new_device_added)
1414 btrfs_free_stale_devices(path, device);
1417 btrfs_release_disk_super(disk_super);
1420 blkdev_put(bdev, flags);
1426 * Try to find a chunk that intersects [start, start + len] range and when one
1427 * such is found, record the end of it in *start
1429 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1432 u64 physical_start, physical_end;
1434 lockdep_assert_held(&device->fs_info->chunk_mutex);
1436 if (!find_first_extent_bit(&device->alloc_state, *start,
1437 &physical_start, &physical_end,
1438 CHUNK_ALLOCATED, NULL)) {
1440 if (in_range(physical_start, *start, len) ||
1441 in_range(*start, physical_start,
1442 physical_end - physical_start)) {
1443 *start = physical_end + 1;
1450 static u64 dev_extent_search_start(struct btrfs_device *device, u64 start)
1452 switch (device->fs_devices->chunk_alloc_policy) {
1453 case BTRFS_CHUNK_ALLOC_REGULAR:
1455 * We don't want to overwrite the superblock on the drive nor
1456 * any area used by the boot loader (grub for example), so we
1457 * make sure to start at an offset of at least 1MB.
1459 return max_t(u64, start, SZ_1M);
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);
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_start) {
1670 hole_size = key.offset - search_start;
1671 dev_extent_hole_check(device, &search_start, &hole_size,
1674 if (hole_size > max_hole_size) {
1675 max_hole_start = search_start;
1676 max_hole_size = hole_size;
1680 * If this free space is greater than which we need,
1681 * it must be the max free space that we have found
1682 * until now, so max_hole_start must point to the start
1683 * of this free space and the length of this free space
1684 * is stored in max_hole_size. Thus, we return
1685 * max_hole_start and max_hole_size and go back to the
1688 if (hole_size >= num_bytes) {
1694 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1695 extent_end = key.offset + btrfs_dev_extent_length(l,
1697 if (extent_end > search_start)
1698 search_start = extent_end;
1705 * At this point, search_start should be the end of
1706 * allocated dev extents, and when shrinking the device,
1707 * search_end may be smaller than search_start.
1709 if (search_end > search_start) {
1710 hole_size = search_end - search_start;
1711 if (dev_extent_hole_check(device, &search_start, &hole_size,
1713 btrfs_release_path(path);
1717 if (hole_size > max_hole_size) {
1718 max_hole_start = search_start;
1719 max_hole_size = hole_size;
1724 if (max_hole_size < num_bytes)
1730 btrfs_free_path(path);
1731 *start = max_hole_start;
1733 *len = max_hole_size;
1737 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1738 u64 *start, u64 *len)
1740 /* FIXME use last free of some kind */
1741 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1744 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1745 struct btrfs_device *device,
1746 u64 start, u64 *dev_extent_len)
1748 struct btrfs_fs_info *fs_info = device->fs_info;
1749 struct btrfs_root *root = fs_info->dev_root;
1751 struct btrfs_path *path;
1752 struct btrfs_key key;
1753 struct btrfs_key found_key;
1754 struct extent_buffer *leaf = NULL;
1755 struct btrfs_dev_extent *extent = NULL;
1757 path = btrfs_alloc_path();
1761 key.objectid = device->devid;
1763 key.type = BTRFS_DEV_EXTENT_KEY;
1765 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1767 ret = btrfs_previous_item(root, path, key.objectid,
1768 BTRFS_DEV_EXTENT_KEY);
1771 leaf = path->nodes[0];
1772 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1773 extent = btrfs_item_ptr(leaf, path->slots[0],
1774 struct btrfs_dev_extent);
1775 BUG_ON(found_key.offset > start || found_key.offset +
1776 btrfs_dev_extent_length(leaf, extent) < start);
1778 btrfs_release_path(path);
1780 } else if (ret == 0) {
1781 leaf = path->nodes[0];
1782 extent = btrfs_item_ptr(leaf, path->slots[0],
1783 struct btrfs_dev_extent);
1788 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1790 ret = btrfs_del_item(trans, root, path);
1792 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1794 btrfs_free_path(path);
1798 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1800 struct extent_map_tree *em_tree;
1801 struct extent_map *em;
1805 em_tree = &fs_info->mapping_tree;
1806 read_lock(&em_tree->lock);
1807 n = rb_last(&em_tree->map.rb_root);
1809 em = rb_entry(n, struct extent_map, rb_node);
1810 ret = em->start + em->len;
1812 read_unlock(&em_tree->lock);
1817 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1821 struct btrfs_key key;
1822 struct btrfs_key found_key;
1823 struct btrfs_path *path;
1825 path = btrfs_alloc_path();
1829 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1830 key.type = BTRFS_DEV_ITEM_KEY;
1831 key.offset = (u64)-1;
1833 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1839 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1844 ret = btrfs_previous_item(fs_info->chunk_root, path,
1845 BTRFS_DEV_ITEMS_OBJECTID,
1846 BTRFS_DEV_ITEM_KEY);
1850 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1852 *devid_ret = found_key.offset + 1;
1856 btrfs_free_path(path);
1861 * the device information is stored in the chunk root
1862 * the btrfs_device struct should be fully filled in
1864 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1865 struct btrfs_device *device)
1868 struct btrfs_path *path;
1869 struct btrfs_dev_item *dev_item;
1870 struct extent_buffer *leaf;
1871 struct btrfs_key key;
1874 path = btrfs_alloc_path();
1878 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1879 key.type = BTRFS_DEV_ITEM_KEY;
1880 key.offset = device->devid;
1882 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1883 &key, sizeof(*dev_item));
1887 leaf = path->nodes[0];
1888 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1890 btrfs_set_device_id(leaf, dev_item, device->devid);
1891 btrfs_set_device_generation(leaf, dev_item, 0);
1892 btrfs_set_device_type(leaf, dev_item, device->type);
1893 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1894 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1895 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1896 btrfs_set_device_total_bytes(leaf, dev_item,
1897 btrfs_device_get_disk_total_bytes(device));
1898 btrfs_set_device_bytes_used(leaf, dev_item,
1899 btrfs_device_get_bytes_used(device));
1900 btrfs_set_device_group(leaf, dev_item, 0);
1901 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1902 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1903 btrfs_set_device_start_offset(leaf, dev_item, 0);
1905 ptr = btrfs_device_uuid(dev_item);
1906 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1907 ptr = btrfs_device_fsid(dev_item);
1908 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1909 ptr, BTRFS_FSID_SIZE);
1910 btrfs_mark_buffer_dirty(leaf);
1914 btrfs_free_path(path);
1919 * Function to update ctime/mtime for a given device path.
1920 * Mainly used for ctime/mtime based probe like libblkid.
1922 * We don't care about errors here, this is just to be kind to userspace.
1924 static void update_dev_time(const char *device_path)
1927 struct timespec64 now;
1930 ret = kern_path(device_path, LOOKUP_FOLLOW, &path);
1934 now = current_time(d_inode(path.dentry));
1935 inode_update_time(d_inode(path.dentry), &now, S_MTIME | S_CTIME);
1939 static int btrfs_rm_dev_item(struct btrfs_device *device)
1941 struct btrfs_root *root = device->fs_info->chunk_root;
1943 struct btrfs_path *path;
1944 struct btrfs_key key;
1945 struct btrfs_trans_handle *trans;
1947 path = btrfs_alloc_path();
1951 trans = btrfs_start_transaction(root, 0);
1952 if (IS_ERR(trans)) {
1953 btrfs_free_path(path);
1954 return PTR_ERR(trans);
1956 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1957 key.type = BTRFS_DEV_ITEM_KEY;
1958 key.offset = device->devid;
1960 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1964 btrfs_abort_transaction(trans, ret);
1965 btrfs_end_transaction(trans);
1969 ret = btrfs_del_item(trans, root, path);
1971 btrfs_abort_transaction(trans, ret);
1972 btrfs_end_transaction(trans);
1976 btrfs_free_path(path);
1978 ret = btrfs_commit_transaction(trans);
1983 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1984 * filesystem. It's up to the caller to adjust that number regarding eg. device
1987 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1995 seq = read_seqbegin(&fs_info->profiles_lock);
1997 all_avail = fs_info->avail_data_alloc_bits |
1998 fs_info->avail_system_alloc_bits |
1999 fs_info->avail_metadata_alloc_bits;
2000 } while (read_seqretry(&fs_info->profiles_lock, seq));
2002 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2003 if (!(all_avail & btrfs_raid_array[i].bg_flag))
2006 if (num_devices < btrfs_raid_array[i].devs_min)
2007 return btrfs_raid_array[i].mindev_error;
2013 static struct btrfs_device * btrfs_find_next_active_device(
2014 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2016 struct btrfs_device *next_device;
2018 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2019 if (next_device != device &&
2020 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2021 && next_device->bdev)
2029 * Helper function to check if the given device is part of s_bdev / latest_dev
2030 * and replace it with the provided or the next active device, in the context
2031 * where this function called, there should be always be another device (or
2032 * this_dev) which is active.
2034 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
2035 struct btrfs_device *next_device)
2037 struct btrfs_fs_info *fs_info = device->fs_info;
2040 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2042 ASSERT(next_device);
2044 if (fs_info->sb->s_bdev &&
2045 (fs_info->sb->s_bdev == device->bdev))
2046 fs_info->sb->s_bdev = next_device->bdev;
2048 if (fs_info->fs_devices->latest_dev->bdev == device->bdev)
2049 fs_info->fs_devices->latest_dev = next_device;
2053 * Return btrfs_fs_devices::num_devices excluding the device that's being
2054 * currently replaced.
2056 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2058 u64 num_devices = fs_info->fs_devices->num_devices;
2060 down_read(&fs_info->dev_replace.rwsem);
2061 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2062 ASSERT(num_devices > 1);
2065 up_read(&fs_info->dev_replace.rwsem);
2070 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2071 struct block_device *bdev,
2072 const char *device_path)
2074 struct btrfs_super_block *disk_super;
2080 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2084 disk_super = btrfs_read_dev_one_super(bdev, copy_num);
2085 if (IS_ERR(disk_super))
2088 if (bdev_is_zoned(bdev)) {
2089 btrfs_reset_sb_log_zones(bdev, copy_num);
2093 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
2095 page = virt_to_page(disk_super);
2096 set_page_dirty(page);
2098 /* write_on_page() unlocks the page */
2099 ret = write_one_page(page);
2102 "error clearing superblock number %d (%d)",
2104 btrfs_release_disk_super(disk_super);
2108 /* Notify udev that device has changed */
2109 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2111 /* Update ctime/mtime for device path for libblkid */
2112 update_dev_time(device_path);
2115 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2116 u64 devid, struct block_device **bdev, fmode_t *mode)
2118 struct btrfs_device *device;
2119 struct btrfs_fs_devices *cur_devices;
2120 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2125 * The device list in fs_devices is accessed without locks (neither
2126 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2127 * filesystem and another device rm cannot run.
2129 num_devices = btrfs_num_devices(fs_info);
2131 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2135 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2137 if (IS_ERR(device)) {
2138 if (PTR_ERR(device) == -ENOENT &&
2139 device_path && strcmp(device_path, "missing") == 0)
2140 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2142 ret = PTR_ERR(device);
2146 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2147 btrfs_warn_in_rcu(fs_info,
2148 "cannot remove device %s (devid %llu) due to active swapfile",
2149 rcu_str_deref(device->name), device->devid);
2154 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2155 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2159 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2160 fs_info->fs_devices->rw_devices == 1) {
2161 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2165 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2166 mutex_lock(&fs_info->chunk_mutex);
2167 list_del_init(&device->dev_alloc_list);
2168 device->fs_devices->rw_devices--;
2169 mutex_unlock(&fs_info->chunk_mutex);
2172 ret = btrfs_shrink_device(device, 0);
2174 btrfs_reada_remove_dev(device);
2179 * TODO: the superblock still includes this device in its num_devices
2180 * counter although write_all_supers() is not locked out. This
2181 * could give a filesystem state which requires a degraded mount.
2183 ret = btrfs_rm_dev_item(device);
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.
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);
2254 if (cur_devices->open_devices == 0) {
2255 list_del_init(&cur_devices->seed_list);
2256 close_fs_devices(cur_devices);
2257 free_fs_devices(cur_devices);
2264 btrfs_reada_undo_remove_dev(device);
2265 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2266 mutex_lock(&fs_info->chunk_mutex);
2267 list_add(&device->dev_alloc_list,
2268 &fs_devices->alloc_list);
2269 device->fs_devices->rw_devices++;
2270 mutex_unlock(&fs_info->chunk_mutex);
2275 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2277 struct btrfs_fs_devices *fs_devices;
2279 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2282 * in case of fs with no seed, srcdev->fs_devices will point
2283 * to fs_devices of fs_info. However when the dev being replaced is
2284 * a seed dev it will point to the seed's local fs_devices. In short
2285 * srcdev will have its correct fs_devices in both the cases.
2287 fs_devices = srcdev->fs_devices;
2289 list_del_rcu(&srcdev->dev_list);
2290 list_del(&srcdev->dev_alloc_list);
2291 fs_devices->num_devices--;
2292 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2293 fs_devices->missing_devices--;
2295 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2296 fs_devices->rw_devices--;
2299 fs_devices->open_devices--;
2302 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2304 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2306 mutex_lock(&uuid_mutex);
2308 btrfs_close_bdev(srcdev);
2310 btrfs_free_device(srcdev);
2312 /* if this is no devs we rather delete the fs_devices */
2313 if (!fs_devices->num_devices) {
2315 * On a mounted FS, num_devices can't be zero unless it's a
2316 * seed. In case of a seed device being replaced, the replace
2317 * target added to the sprout FS, so there will be no more
2318 * device left under the seed FS.
2320 ASSERT(fs_devices->seeding);
2322 list_del_init(&fs_devices->seed_list);
2323 close_fs_devices(fs_devices);
2324 free_fs_devices(fs_devices);
2326 mutex_unlock(&uuid_mutex);
2329 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2331 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2333 mutex_lock(&fs_devices->device_list_mutex);
2335 btrfs_sysfs_remove_device(tgtdev);
2338 fs_devices->open_devices--;
2340 fs_devices->num_devices--;
2342 btrfs_assign_next_active_device(tgtdev, NULL);
2344 list_del_rcu(&tgtdev->dev_list);
2346 mutex_unlock(&fs_devices->device_list_mutex);
2348 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2351 btrfs_close_bdev(tgtdev);
2353 btrfs_free_device(tgtdev);
2356 static struct btrfs_device *btrfs_find_device_by_path(
2357 struct btrfs_fs_info *fs_info, const char *device_path)
2360 struct btrfs_super_block *disk_super;
2363 struct block_device *bdev;
2364 struct btrfs_device *device;
2366 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2367 fs_info->bdev_holder, 0, &bdev, &disk_super);
2369 return ERR_PTR(ret);
2371 devid = btrfs_stack_device_id(&disk_super->dev_item);
2372 dev_uuid = disk_super->dev_item.uuid;
2373 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2374 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2375 disk_super->metadata_uuid);
2377 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2380 btrfs_release_disk_super(disk_super);
2382 device = ERR_PTR(-ENOENT);
2383 blkdev_put(bdev, FMODE_READ);
2388 * Lookup a device given by device id, or the path if the id is 0.
2390 struct btrfs_device *btrfs_find_device_by_devspec(
2391 struct btrfs_fs_info *fs_info, u64 devid,
2392 const char *device_path)
2394 struct btrfs_device *device;
2397 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2400 return ERR_PTR(-ENOENT);
2404 if (!device_path || !device_path[0])
2405 return ERR_PTR(-EINVAL);
2407 if (strcmp(device_path, "missing") == 0) {
2408 /* Find first missing device */
2409 list_for_each_entry(device, &fs_info->fs_devices->devices,
2411 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2412 &device->dev_state) && !device->bdev)
2415 return ERR_PTR(-ENOENT);
2418 return btrfs_find_device_by_path(fs_info, device_path);
2422 * does all the dirty work required for changing file system's UUID.
2424 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2426 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2427 struct btrfs_fs_devices *old_devices;
2428 struct btrfs_fs_devices *seed_devices;
2429 struct btrfs_super_block *disk_super = fs_info->super_copy;
2430 struct btrfs_device *device;
2433 lockdep_assert_held(&uuid_mutex);
2434 if (!fs_devices->seeding)
2438 * Private copy of the seed devices, anchored at
2439 * fs_info->fs_devices->seed_list
2441 seed_devices = alloc_fs_devices(NULL, NULL);
2442 if (IS_ERR(seed_devices))
2443 return PTR_ERR(seed_devices);
2446 * It's necessary to retain a copy of the original seed fs_devices in
2447 * fs_uuids so that filesystems which have been seeded can successfully
2448 * reference the seed device from open_seed_devices. This also supports
2451 old_devices = clone_fs_devices(fs_devices);
2452 if (IS_ERR(old_devices)) {
2453 kfree(seed_devices);
2454 return PTR_ERR(old_devices);
2457 list_add(&old_devices->fs_list, &fs_uuids);
2459 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2460 seed_devices->opened = 1;
2461 INIT_LIST_HEAD(&seed_devices->devices);
2462 INIT_LIST_HEAD(&seed_devices->alloc_list);
2463 mutex_init(&seed_devices->device_list_mutex);
2465 mutex_lock(&fs_devices->device_list_mutex);
2466 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2468 list_for_each_entry(device, &seed_devices->devices, dev_list)
2469 device->fs_devices = seed_devices;
2471 fs_devices->seeding = false;
2472 fs_devices->num_devices = 0;
2473 fs_devices->open_devices = 0;
2474 fs_devices->missing_devices = 0;
2475 fs_devices->rotating = false;
2476 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2478 generate_random_uuid(fs_devices->fsid);
2479 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2480 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2481 mutex_unlock(&fs_devices->device_list_mutex);
2483 super_flags = btrfs_super_flags(disk_super) &
2484 ~BTRFS_SUPER_FLAG_SEEDING;
2485 btrfs_set_super_flags(disk_super, super_flags);
2491 * Store the expected generation for seed devices in device items.
2493 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2495 struct btrfs_fs_info *fs_info = trans->fs_info;
2496 struct btrfs_root *root = fs_info->chunk_root;
2497 struct btrfs_path *path;
2498 struct extent_buffer *leaf;
2499 struct btrfs_dev_item *dev_item;
2500 struct btrfs_device *device;
2501 struct btrfs_key key;
2502 u8 fs_uuid[BTRFS_FSID_SIZE];
2503 u8 dev_uuid[BTRFS_UUID_SIZE];
2507 path = btrfs_alloc_path();
2511 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2513 key.type = BTRFS_DEV_ITEM_KEY;
2516 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2520 leaf = path->nodes[0];
2522 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2523 ret = btrfs_next_leaf(root, path);
2528 leaf = path->nodes[0];
2529 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2530 btrfs_release_path(path);
2534 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2535 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2536 key.type != BTRFS_DEV_ITEM_KEY)
2539 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2540 struct btrfs_dev_item);
2541 devid = btrfs_device_id(leaf, dev_item);
2542 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2544 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2546 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2548 BUG_ON(!device); /* Logic error */
2550 if (device->fs_devices->seeding) {
2551 btrfs_set_device_generation(leaf, dev_item,
2552 device->generation);
2553 btrfs_mark_buffer_dirty(leaf);
2561 btrfs_free_path(path);
2565 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2567 struct btrfs_root *root = fs_info->dev_root;
2568 struct request_queue *q;
2569 struct btrfs_trans_handle *trans;
2570 struct btrfs_device *device;
2571 struct block_device *bdev;
2572 struct super_block *sb = fs_info->sb;
2573 struct rcu_string *name;
2574 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2575 u64 orig_super_total_bytes;
2576 u64 orig_super_num_devices;
2577 int seeding_dev = 0;
2579 bool locked = false;
2581 if (sb_rdonly(sb) && !fs_devices->seeding)
2584 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2585 fs_info->bdev_holder);
2587 return PTR_ERR(bdev);
2589 if (!btrfs_check_device_zone_type(fs_info, bdev)) {
2594 if (fs_devices->seeding) {
2596 down_write(&sb->s_umount);
2597 mutex_lock(&uuid_mutex);
2601 sync_blockdev(bdev);
2604 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2605 if (device->bdev == bdev) {
2613 device = btrfs_alloc_device(fs_info, NULL, NULL);
2614 if (IS_ERR(device)) {
2615 /* we can safely leave the fs_devices entry around */
2616 ret = PTR_ERR(device);
2620 name = rcu_string_strdup(device_path, GFP_KERNEL);
2623 goto error_free_device;
2625 rcu_assign_pointer(device->name, name);
2627 device->fs_info = fs_info;
2628 device->bdev = bdev;
2630 ret = btrfs_get_dev_zone_info(device, false);
2632 goto error_free_device;
2634 trans = btrfs_start_transaction(root, 0);
2635 if (IS_ERR(trans)) {
2636 ret = PTR_ERR(trans);
2637 goto error_free_zone;
2640 q = bdev_get_queue(bdev);
2641 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2642 device->generation = trans->transid;
2643 device->io_width = fs_info->sectorsize;
2644 device->io_align = fs_info->sectorsize;
2645 device->sector_size = fs_info->sectorsize;
2646 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2647 fs_info->sectorsize);
2648 device->disk_total_bytes = device->total_bytes;
2649 device->commit_total_bytes = device->total_bytes;
2650 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2651 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2652 device->mode = FMODE_EXCL;
2653 device->dev_stats_valid = 1;
2654 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2657 btrfs_clear_sb_rdonly(sb);
2658 ret = btrfs_prepare_sprout(fs_info);
2660 btrfs_abort_transaction(trans, ret);
2663 btrfs_assign_next_active_device(fs_info->fs_devices->latest_dev,
2667 device->fs_devices = fs_devices;
2669 mutex_lock(&fs_devices->device_list_mutex);
2670 mutex_lock(&fs_info->chunk_mutex);
2671 list_add_rcu(&device->dev_list, &fs_devices->devices);
2672 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2673 fs_devices->num_devices++;
2674 fs_devices->open_devices++;
2675 fs_devices->rw_devices++;
2676 fs_devices->total_devices++;
2677 fs_devices->total_rw_bytes += device->total_bytes;
2679 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2681 if (!blk_queue_nonrot(q))
2682 fs_devices->rotating = true;
2684 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2685 btrfs_set_super_total_bytes(fs_info->super_copy,
2686 round_down(orig_super_total_bytes + device->total_bytes,
2687 fs_info->sectorsize));
2689 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2690 btrfs_set_super_num_devices(fs_info->super_copy,
2691 orig_super_num_devices + 1);
2694 * we've got more storage, clear any full flags on the space
2697 btrfs_clear_space_info_full(fs_info);
2699 mutex_unlock(&fs_info->chunk_mutex);
2701 /* Add sysfs device entry */
2702 btrfs_sysfs_add_device(device);
2704 mutex_unlock(&fs_devices->device_list_mutex);
2707 mutex_lock(&fs_info->chunk_mutex);
2708 ret = init_first_rw_device(trans);
2709 mutex_unlock(&fs_info->chunk_mutex);
2711 btrfs_abort_transaction(trans, ret);
2716 ret = btrfs_add_dev_item(trans, device);
2718 btrfs_abort_transaction(trans, ret);
2723 ret = btrfs_finish_sprout(trans);
2725 btrfs_abort_transaction(trans, ret);
2730 * fs_devices now represents the newly sprouted filesystem and
2731 * its fsid has been changed by btrfs_prepare_sprout
2733 btrfs_sysfs_update_sprout_fsid(fs_devices);
2736 ret = btrfs_commit_transaction(trans);
2739 mutex_unlock(&uuid_mutex);
2740 up_write(&sb->s_umount);
2743 if (ret) /* transaction commit */
2746 ret = btrfs_relocate_sys_chunks(fs_info);
2748 btrfs_handle_fs_error(fs_info, ret,
2749 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2750 trans = btrfs_attach_transaction(root);
2751 if (IS_ERR(trans)) {
2752 if (PTR_ERR(trans) == -ENOENT)
2754 ret = PTR_ERR(trans);
2758 ret = btrfs_commit_transaction(trans);
2762 * Now that we have written a new super block to this device, check all
2763 * other fs_devices list if device_path alienates any other scanned
2765 * We can ignore the return value as it typically returns -EINVAL and
2766 * only succeeds if the device was an alien.
2768 btrfs_forget_devices(device_path);
2770 /* Update ctime/mtime for blkid or udev */
2771 update_dev_time(device_path);
2776 btrfs_sysfs_remove_device(device);
2777 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2778 mutex_lock(&fs_info->chunk_mutex);
2779 list_del_rcu(&device->dev_list);
2780 list_del(&device->dev_alloc_list);
2781 fs_info->fs_devices->num_devices--;
2782 fs_info->fs_devices->open_devices--;
2783 fs_info->fs_devices->rw_devices--;
2784 fs_info->fs_devices->total_devices--;
2785 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2786 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2787 btrfs_set_super_total_bytes(fs_info->super_copy,
2788 orig_super_total_bytes);
2789 btrfs_set_super_num_devices(fs_info->super_copy,
2790 orig_super_num_devices);
2791 mutex_unlock(&fs_info->chunk_mutex);
2792 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2795 btrfs_set_sb_rdonly(sb);
2797 btrfs_end_transaction(trans);
2799 btrfs_destroy_dev_zone_info(device);
2801 btrfs_free_device(device);
2803 blkdev_put(bdev, FMODE_EXCL);
2805 mutex_unlock(&uuid_mutex);
2806 up_write(&sb->s_umount);
2811 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2812 struct btrfs_device *device)
2815 struct btrfs_path *path;
2816 struct btrfs_root *root = device->fs_info->chunk_root;
2817 struct btrfs_dev_item *dev_item;
2818 struct extent_buffer *leaf;
2819 struct btrfs_key key;
2821 path = btrfs_alloc_path();
2825 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2826 key.type = BTRFS_DEV_ITEM_KEY;
2827 key.offset = device->devid;
2829 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2838 leaf = path->nodes[0];
2839 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2841 btrfs_set_device_id(leaf, dev_item, device->devid);
2842 btrfs_set_device_type(leaf, dev_item, device->type);
2843 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2844 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2845 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2846 btrfs_set_device_total_bytes(leaf, dev_item,
2847 btrfs_device_get_disk_total_bytes(device));
2848 btrfs_set_device_bytes_used(leaf, dev_item,
2849 btrfs_device_get_bytes_used(device));
2850 btrfs_mark_buffer_dirty(leaf);
2853 btrfs_free_path(path);
2857 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2858 struct btrfs_device *device, u64 new_size)
2860 struct btrfs_fs_info *fs_info = device->fs_info;
2861 struct btrfs_super_block *super_copy = fs_info->super_copy;
2865 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2868 new_size = round_down(new_size, fs_info->sectorsize);
2870 mutex_lock(&fs_info->chunk_mutex);
2871 old_total = btrfs_super_total_bytes(super_copy);
2872 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2874 if (new_size <= device->total_bytes ||
2875 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2876 mutex_unlock(&fs_info->chunk_mutex);
2880 btrfs_set_super_total_bytes(super_copy,
2881 round_down(old_total + diff, fs_info->sectorsize));
2882 device->fs_devices->total_rw_bytes += diff;
2884 btrfs_device_set_total_bytes(device, new_size);
2885 btrfs_device_set_disk_total_bytes(device, new_size);
2886 btrfs_clear_space_info_full(device->fs_info);
2887 if (list_empty(&device->post_commit_list))
2888 list_add_tail(&device->post_commit_list,
2889 &trans->transaction->dev_update_list);
2890 mutex_unlock(&fs_info->chunk_mutex);
2892 return btrfs_update_device(trans, device);
2895 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2897 struct btrfs_fs_info *fs_info = trans->fs_info;
2898 struct btrfs_root *root = fs_info->chunk_root;
2900 struct btrfs_path *path;
2901 struct btrfs_key key;
2903 path = btrfs_alloc_path();
2907 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2908 key.offset = chunk_offset;
2909 key.type = BTRFS_CHUNK_ITEM_KEY;
2911 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2914 else if (ret > 0) { /* Logic error or corruption */
2915 btrfs_handle_fs_error(fs_info, -ENOENT,
2916 "Failed lookup while freeing chunk.");
2921 ret = btrfs_del_item(trans, root, path);
2923 btrfs_handle_fs_error(fs_info, ret,
2924 "Failed to delete chunk item.");
2926 btrfs_free_path(path);
2930 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2932 struct btrfs_super_block *super_copy = fs_info->super_copy;
2933 struct btrfs_disk_key *disk_key;
2934 struct btrfs_chunk *chunk;
2941 struct btrfs_key key;
2943 lockdep_assert_held(&fs_info->chunk_mutex);
2944 array_size = btrfs_super_sys_array_size(super_copy);
2946 ptr = super_copy->sys_chunk_array;
2949 while (cur < array_size) {
2950 disk_key = (struct btrfs_disk_key *)ptr;
2951 btrfs_disk_key_to_cpu(&key, disk_key);
2953 len = sizeof(*disk_key);
2955 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2956 chunk = (struct btrfs_chunk *)(ptr + len);
2957 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2958 len += btrfs_chunk_item_size(num_stripes);
2963 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2964 key.offset == chunk_offset) {
2965 memmove(ptr, ptr + len, array_size - (cur + len));
2967 btrfs_set_super_sys_array_size(super_copy, array_size);
2977 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2978 * @logical: Logical block offset in bytes.
2979 * @length: Length of extent in bytes.
2981 * Return: Chunk mapping or ERR_PTR.
2983 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2984 u64 logical, u64 length)
2986 struct extent_map_tree *em_tree;
2987 struct extent_map *em;
2989 em_tree = &fs_info->mapping_tree;
2990 read_lock(&em_tree->lock);
2991 em = lookup_extent_mapping(em_tree, logical, length);
2992 read_unlock(&em_tree->lock);
2995 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2997 return ERR_PTR(-EINVAL);
3000 if (em->start > logical || em->start + em->len < logical) {
3002 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
3003 logical, length, em->start, em->start + em->len);
3004 free_extent_map(em);
3005 return ERR_PTR(-EINVAL);
3008 /* callers are responsible for dropping em's ref. */
3012 static int remove_chunk_item(struct btrfs_trans_handle *trans,
3013 struct map_lookup *map, u64 chunk_offset)
3018 * Removing chunk items and updating the device items in the chunks btree
3019 * requires holding the chunk_mutex.
3020 * See the comment at btrfs_chunk_alloc() for the details.
3022 lockdep_assert_held(&trans->fs_info->chunk_mutex);
3024 for (i = 0; i < map->num_stripes; i++) {
3027 ret = btrfs_update_device(trans, map->stripes[i].dev);
3032 return btrfs_free_chunk(trans, chunk_offset);
3035 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3037 struct btrfs_fs_info *fs_info = trans->fs_info;
3038 struct extent_map *em;
3039 struct map_lookup *map;
3040 u64 dev_extent_len = 0;
3042 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3044 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3047 * This is a logic error, but we don't want to just rely on the
3048 * user having built with ASSERT enabled, so if ASSERT doesn't
3049 * do anything we still error out.
3054 map = em->map_lookup;
3057 * First delete the device extent items from the devices btree.
3058 * We take the device_list_mutex to avoid racing with the finishing phase
3059 * of a device replace operation. See the comment below before acquiring
3060 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3061 * because that can result in a deadlock when deleting the device extent
3062 * items from the devices btree - COWing an extent buffer from the btree
3063 * may result in allocating a new metadata chunk, which would attempt to
3064 * lock again fs_info->chunk_mutex.
3066 mutex_lock(&fs_devices->device_list_mutex);
3067 for (i = 0; i < map->num_stripes; i++) {
3068 struct btrfs_device *device = map->stripes[i].dev;
3069 ret = btrfs_free_dev_extent(trans, device,
3070 map->stripes[i].physical,
3073 mutex_unlock(&fs_devices->device_list_mutex);
3074 btrfs_abort_transaction(trans, ret);
3078 if (device->bytes_used > 0) {
3079 mutex_lock(&fs_info->chunk_mutex);
3080 btrfs_device_set_bytes_used(device,
3081 device->bytes_used - dev_extent_len);
3082 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3083 btrfs_clear_space_info_full(fs_info);
3084 mutex_unlock(&fs_info->chunk_mutex);
3087 mutex_unlock(&fs_devices->device_list_mutex);
3090 * We acquire fs_info->chunk_mutex for 2 reasons:
3092 * 1) Just like with the first phase of the chunk allocation, we must
3093 * reserve system space, do all chunk btree updates and deletions, and
3094 * update the system chunk array in the superblock while holding this
3095 * mutex. This is for similar reasons as explained on the comment at
3096 * the top of btrfs_chunk_alloc();
3098 * 2) Prevent races with the final phase of a device replace operation
3099 * that replaces the device object associated with the map's stripes,
3100 * because the device object's id can change at any time during that
3101 * final phase of the device replace operation
3102 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3103 * replaced device and then see it with an ID of
3104 * BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3105 * the device item, which does not exists on the chunk btree.
3106 * The finishing phase of device replace acquires both the
3107 * device_list_mutex and the chunk_mutex, in that order, so we are
3108 * safe by just acquiring the chunk_mutex.
3110 trans->removing_chunk = true;
3111 mutex_lock(&fs_info->chunk_mutex);
3113 check_system_chunk(trans, map->type);
3115 ret = remove_chunk_item(trans, map, chunk_offset);
3117 * Normally we should not get -ENOSPC since we reserved space before
3118 * through the call to check_system_chunk().
3120 * Despite our system space_info having enough free space, we may not
3121 * be able to allocate extents from its block groups, because all have
3122 * an incompatible profile, which will force us to allocate a new system
3123 * block group with the right profile, or right after we called
3124 * check_system_space() above, a scrub turned the only system block group
3125 * with enough free space into RO mode.
3126 * This is explained with more detail at do_chunk_alloc().
3128 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3130 if (ret == -ENOSPC) {
3131 const u64 sys_flags = btrfs_system_alloc_profile(fs_info);
3132 struct btrfs_block_group *sys_bg;
3134 sys_bg = btrfs_alloc_chunk(trans, sys_flags);
3135 if (IS_ERR(sys_bg)) {
3136 ret = PTR_ERR(sys_bg);
3137 btrfs_abort_transaction(trans, ret);
3141 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3143 btrfs_abort_transaction(trans, ret);
3147 ret = remove_chunk_item(trans, map, chunk_offset);
3149 btrfs_abort_transaction(trans, ret);
3153 btrfs_abort_transaction(trans, ret);
3157 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3159 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3160 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3162 btrfs_abort_transaction(trans, ret);
3167 mutex_unlock(&fs_info->chunk_mutex);
3168 trans->removing_chunk = false;
3171 * We are done with chunk btree updates and deletions, so release the
3172 * system space we previously reserved (with check_system_chunk()).
3174 btrfs_trans_release_chunk_metadata(trans);
3176 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3178 btrfs_abort_transaction(trans, ret);
3183 if (trans->removing_chunk) {
3184 mutex_unlock(&fs_info->chunk_mutex);
3185 trans->removing_chunk = false;
3188 free_extent_map(em);
3192 int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3194 struct btrfs_root *root = fs_info->chunk_root;
3195 struct btrfs_trans_handle *trans;
3196 struct btrfs_block_group *block_group;
3201 * Prevent races with automatic removal of unused block groups.
3202 * After we relocate and before we remove the chunk with offset
3203 * chunk_offset, automatic removal of the block group can kick in,
3204 * resulting in a failure when calling btrfs_remove_chunk() below.
3206 * Make sure to acquire this mutex before doing a tree search (dev
3207 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3208 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3209 * we release the path used to search the chunk/dev tree and before
3210 * the current task acquires this mutex and calls us.
3212 lockdep_assert_held(&fs_info->reclaim_bgs_lock);
3214 /* step one, relocate all the extents inside this chunk */
3215 btrfs_scrub_pause(fs_info);
3216 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3217 btrfs_scrub_continue(fs_info);
3221 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3224 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3225 length = block_group->length;
3226 btrfs_put_block_group(block_group);
3229 * On a zoned file system, discard the whole block group, this will
3230 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3231 * resetting the zone fails, don't treat it as a fatal problem from the
3232 * filesystem's point of view.
3234 if (btrfs_is_zoned(fs_info)) {
3235 ret = btrfs_discard_extent(fs_info, chunk_offset, length, NULL);
3238 "failed to reset zone %llu after relocation",
3242 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3244 if (IS_ERR(trans)) {
3245 ret = PTR_ERR(trans);
3246 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3251 * step two, delete the device extents and the
3252 * chunk tree entries
3254 ret = btrfs_remove_chunk(trans, chunk_offset);
3255 btrfs_end_transaction(trans);
3259 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3261 struct btrfs_root *chunk_root = fs_info->chunk_root;
3262 struct btrfs_path *path;
3263 struct extent_buffer *leaf;
3264 struct btrfs_chunk *chunk;
3265 struct btrfs_key key;
3266 struct btrfs_key found_key;
3268 bool retried = false;
3272 path = btrfs_alloc_path();
3277 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3278 key.offset = (u64)-1;
3279 key.type = BTRFS_CHUNK_ITEM_KEY;
3282 mutex_lock(&fs_info->reclaim_bgs_lock);
3283 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3285 mutex_unlock(&fs_info->reclaim_bgs_lock);
3288 BUG_ON(ret == 0); /* Corruption */
3290 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3293 mutex_unlock(&fs_info->reclaim_bgs_lock);
3299 leaf = path->nodes[0];
3300 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3302 chunk = btrfs_item_ptr(leaf, path->slots[0],
3303 struct btrfs_chunk);
3304 chunk_type = btrfs_chunk_type(leaf, chunk);
3305 btrfs_release_path(path);
3307 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3308 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3314 mutex_unlock(&fs_info->reclaim_bgs_lock);
3316 if (found_key.offset == 0)
3318 key.offset = found_key.offset - 1;
3321 if (failed && !retried) {
3325 } else if (WARN_ON(failed && retried)) {
3329 btrfs_free_path(path);
3334 * return 1 : allocate a data chunk successfully,
3335 * return <0: errors during allocating a data chunk,
3336 * return 0 : no need to allocate a data chunk.
3338 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3341 struct btrfs_block_group *cache;
3345 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3347 chunk_type = cache->flags;
3348 btrfs_put_block_group(cache);
3350 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3353 spin_lock(&fs_info->data_sinfo->lock);
3354 bytes_used = fs_info->data_sinfo->bytes_used;
3355 spin_unlock(&fs_info->data_sinfo->lock);
3358 struct btrfs_trans_handle *trans;
3361 trans = btrfs_join_transaction(fs_info->tree_root);
3363 return PTR_ERR(trans);
3365 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3366 btrfs_end_transaction(trans);
3375 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3376 struct btrfs_balance_control *bctl)
3378 struct btrfs_root *root = fs_info->tree_root;
3379 struct btrfs_trans_handle *trans;
3380 struct btrfs_balance_item *item;
3381 struct btrfs_disk_balance_args disk_bargs;
3382 struct btrfs_path *path;
3383 struct extent_buffer *leaf;
3384 struct btrfs_key key;
3387 path = btrfs_alloc_path();
3391 trans = btrfs_start_transaction(root, 0);
3392 if (IS_ERR(trans)) {
3393 btrfs_free_path(path);
3394 return PTR_ERR(trans);
3397 key.objectid = BTRFS_BALANCE_OBJECTID;
3398 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3401 ret = btrfs_insert_empty_item(trans, root, path, &key,
3406 leaf = path->nodes[0];
3407 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3409 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3411 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3412 btrfs_set_balance_data(leaf, item, &disk_bargs);
3413 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3414 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3415 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3416 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3418 btrfs_set_balance_flags(leaf, item, bctl->flags);
3420 btrfs_mark_buffer_dirty(leaf);
3422 btrfs_free_path(path);
3423 err = btrfs_commit_transaction(trans);
3429 static int del_balance_item(struct btrfs_fs_info *fs_info)
3431 struct btrfs_root *root = fs_info->tree_root;
3432 struct btrfs_trans_handle *trans;
3433 struct btrfs_path *path;
3434 struct btrfs_key key;
3437 path = btrfs_alloc_path();
3441 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3442 if (IS_ERR(trans)) {
3443 btrfs_free_path(path);
3444 return PTR_ERR(trans);
3447 key.objectid = BTRFS_BALANCE_OBJECTID;
3448 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3451 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3459 ret = btrfs_del_item(trans, root, path);
3461 btrfs_free_path(path);
3462 err = btrfs_commit_transaction(trans);
3469 * This is a heuristic used to reduce the number of chunks balanced on
3470 * resume after balance was interrupted.
3472 static void update_balance_args(struct btrfs_balance_control *bctl)
3475 * Turn on soft mode for chunk types that were being converted.
3477 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3478 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3479 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3480 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3481 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3482 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3485 * Turn on usage filter if is not already used. The idea is
3486 * that chunks that we have already balanced should be
3487 * reasonably full. Don't do it for chunks that are being
3488 * converted - that will keep us from relocating unconverted
3489 * (albeit full) chunks.
3491 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3492 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3493 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3494 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3495 bctl->data.usage = 90;
3497 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3498 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3499 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3500 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3501 bctl->sys.usage = 90;
3503 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3504 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3505 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3506 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3507 bctl->meta.usage = 90;
3512 * Clear the balance status in fs_info and delete the balance item from disk.
3514 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3516 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3519 BUG_ON(!fs_info->balance_ctl);
3521 spin_lock(&fs_info->balance_lock);
3522 fs_info->balance_ctl = NULL;
3523 spin_unlock(&fs_info->balance_lock);
3526 ret = del_balance_item(fs_info);
3528 btrfs_handle_fs_error(fs_info, ret, NULL);
3532 * Balance filters. Return 1 if chunk should be filtered out
3533 * (should not be balanced).
3535 static int chunk_profiles_filter(u64 chunk_type,
3536 struct btrfs_balance_args *bargs)
3538 chunk_type = chunk_to_extended(chunk_type) &
3539 BTRFS_EXTENDED_PROFILE_MASK;
3541 if (bargs->profiles & chunk_type)
3547 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3548 struct btrfs_balance_args *bargs)
3550 struct btrfs_block_group *cache;
3552 u64 user_thresh_min;
3553 u64 user_thresh_max;
3556 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3557 chunk_used = cache->used;
3559 if (bargs->usage_min == 0)
3560 user_thresh_min = 0;
3562 user_thresh_min = div_factor_fine(cache->length,
3565 if (bargs->usage_max == 0)
3566 user_thresh_max = 1;
3567 else if (bargs->usage_max > 100)
3568 user_thresh_max = cache->length;
3570 user_thresh_max = div_factor_fine(cache->length,
3573 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3576 btrfs_put_block_group(cache);
3580 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3581 u64 chunk_offset, struct btrfs_balance_args *bargs)
3583 struct btrfs_block_group *cache;
3584 u64 chunk_used, user_thresh;
3587 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3588 chunk_used = cache->used;
3590 if (bargs->usage_min == 0)
3592 else if (bargs->usage > 100)
3593 user_thresh = cache->length;
3595 user_thresh = div_factor_fine(cache->length, bargs->usage);
3597 if (chunk_used < user_thresh)
3600 btrfs_put_block_group(cache);
3604 static int chunk_devid_filter(struct extent_buffer *leaf,
3605 struct btrfs_chunk *chunk,
3606 struct btrfs_balance_args *bargs)
3608 struct btrfs_stripe *stripe;
3609 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3612 for (i = 0; i < num_stripes; i++) {
3613 stripe = btrfs_stripe_nr(chunk, i);
3614 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3621 static u64 calc_data_stripes(u64 type, int num_stripes)
3623 const int index = btrfs_bg_flags_to_raid_index(type);
3624 const int ncopies = btrfs_raid_array[index].ncopies;
3625 const int nparity = btrfs_raid_array[index].nparity;
3627 return (num_stripes - nparity) / ncopies;
3630 /* [pstart, pend) */
3631 static int chunk_drange_filter(struct extent_buffer *leaf,
3632 struct btrfs_chunk *chunk,
3633 struct btrfs_balance_args *bargs)
3635 struct btrfs_stripe *stripe;
3636 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3643 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3646 type = btrfs_chunk_type(leaf, chunk);
3647 factor = calc_data_stripes(type, num_stripes);
3649 for (i = 0; i < num_stripes; i++) {
3650 stripe = btrfs_stripe_nr(chunk, i);
3651 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3654 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3655 stripe_length = btrfs_chunk_length(leaf, chunk);
3656 stripe_length = div_u64(stripe_length, factor);
3658 if (stripe_offset < bargs->pend &&
3659 stripe_offset + stripe_length > bargs->pstart)
3666 /* [vstart, vend) */
3667 static int chunk_vrange_filter(struct extent_buffer *leaf,
3668 struct btrfs_chunk *chunk,
3670 struct btrfs_balance_args *bargs)
3672 if (chunk_offset < bargs->vend &&
3673 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3674 /* at least part of the chunk is inside this vrange */
3680 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3681 struct btrfs_chunk *chunk,
3682 struct btrfs_balance_args *bargs)
3684 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3686 if (bargs->stripes_min <= num_stripes
3687 && num_stripes <= bargs->stripes_max)
3693 static int chunk_soft_convert_filter(u64 chunk_type,
3694 struct btrfs_balance_args *bargs)
3696 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3699 chunk_type = chunk_to_extended(chunk_type) &
3700 BTRFS_EXTENDED_PROFILE_MASK;
3702 if (bargs->target == chunk_type)
3708 static int should_balance_chunk(struct extent_buffer *leaf,
3709 struct btrfs_chunk *chunk, u64 chunk_offset)
3711 struct btrfs_fs_info *fs_info = leaf->fs_info;
3712 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3713 struct btrfs_balance_args *bargs = NULL;
3714 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3717 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3718 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3722 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3723 bargs = &bctl->data;
3724 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3726 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3727 bargs = &bctl->meta;
3729 /* profiles filter */
3730 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3731 chunk_profiles_filter(chunk_type, bargs)) {
3736 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3737 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3739 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3740 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3745 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3746 chunk_devid_filter(leaf, chunk, bargs)) {
3750 /* drange filter, makes sense only with devid filter */
3751 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3752 chunk_drange_filter(leaf, chunk, bargs)) {
3757 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3758 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3762 /* stripes filter */
3763 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3764 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3768 /* soft profile changing mode */
3769 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3770 chunk_soft_convert_filter(chunk_type, bargs)) {
3775 * limited by count, must be the last filter
3777 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3778 if (bargs->limit == 0)
3782 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3784 * Same logic as the 'limit' filter; the minimum cannot be
3785 * determined here because we do not have the global information
3786 * about the count of all chunks that satisfy the filters.
3788 if (bargs->limit_max == 0)
3797 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3799 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3800 struct btrfs_root *chunk_root = fs_info->chunk_root;
3802 struct btrfs_chunk *chunk;
3803 struct btrfs_path *path = NULL;
3804 struct btrfs_key key;
3805 struct btrfs_key found_key;
3806 struct extent_buffer *leaf;
3809 int enospc_errors = 0;
3810 bool counting = true;
3811 /* The single value limit and min/max limits use the same bytes in the */
3812 u64 limit_data = bctl->data.limit;
3813 u64 limit_meta = bctl->meta.limit;
3814 u64 limit_sys = bctl->sys.limit;
3818 int chunk_reserved = 0;
3820 path = btrfs_alloc_path();
3826 /* zero out stat counters */
3827 spin_lock(&fs_info->balance_lock);
3828 memset(&bctl->stat, 0, sizeof(bctl->stat));
3829 spin_unlock(&fs_info->balance_lock);
3833 * The single value limit and min/max limits use the same bytes
3836 bctl->data.limit = limit_data;
3837 bctl->meta.limit = limit_meta;
3838 bctl->sys.limit = limit_sys;
3840 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3841 key.offset = (u64)-1;
3842 key.type = BTRFS_CHUNK_ITEM_KEY;
3845 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3846 atomic_read(&fs_info->balance_cancel_req)) {
3851 mutex_lock(&fs_info->reclaim_bgs_lock);
3852 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3854 mutex_unlock(&fs_info->reclaim_bgs_lock);
3859 * this shouldn't happen, it means the last relocate
3863 BUG(); /* FIXME break ? */
3865 ret = btrfs_previous_item(chunk_root, path, 0,
3866 BTRFS_CHUNK_ITEM_KEY);
3868 mutex_unlock(&fs_info->reclaim_bgs_lock);
3873 leaf = path->nodes[0];
3874 slot = path->slots[0];
3875 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3877 if (found_key.objectid != key.objectid) {
3878 mutex_unlock(&fs_info->reclaim_bgs_lock);
3882 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3883 chunk_type = btrfs_chunk_type(leaf, chunk);
3886 spin_lock(&fs_info->balance_lock);
3887 bctl->stat.considered++;
3888 spin_unlock(&fs_info->balance_lock);
3891 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3893 btrfs_release_path(path);
3895 mutex_unlock(&fs_info->reclaim_bgs_lock);
3900 mutex_unlock(&fs_info->reclaim_bgs_lock);
3901 spin_lock(&fs_info->balance_lock);
3902 bctl->stat.expected++;
3903 spin_unlock(&fs_info->balance_lock);
3905 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3907 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3909 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3916 * Apply limit_min filter, no need to check if the LIMITS
3917 * filter is used, limit_min is 0 by default
3919 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3920 count_data < bctl->data.limit_min)
3921 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3922 count_meta < bctl->meta.limit_min)
3923 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3924 count_sys < bctl->sys.limit_min)) {
3925 mutex_unlock(&fs_info->reclaim_bgs_lock);
3929 if (!chunk_reserved) {
3931 * We may be relocating the only data chunk we have,
3932 * which could potentially end up with losing data's
3933 * raid profile, so lets allocate an empty one in
3936 ret = btrfs_may_alloc_data_chunk(fs_info,
3939 mutex_unlock(&fs_info->reclaim_bgs_lock);
3941 } else if (ret == 1) {
3946 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3947 mutex_unlock(&fs_info->reclaim_bgs_lock);
3948 if (ret == -ENOSPC) {
3950 } else if (ret == -ETXTBSY) {
3952 "skipping relocation of block group %llu due to active swapfile",
3958 spin_lock(&fs_info->balance_lock);
3959 bctl->stat.completed++;
3960 spin_unlock(&fs_info->balance_lock);
3963 if (found_key.offset == 0)
3965 key.offset = found_key.offset - 1;
3969 btrfs_release_path(path);
3974 btrfs_free_path(path);
3975 if (enospc_errors) {
3976 btrfs_info(fs_info, "%d enospc errors during balance",
3986 * alloc_profile_is_valid - see if a given profile is valid and reduced
3987 * @flags: profile to validate
3988 * @extended: if true @flags is treated as an extended profile
3990 static int alloc_profile_is_valid(u64 flags, int extended)
3992 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3993 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3995 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3997 /* 1) check that all other bits are zeroed */
4001 /* 2) see if profile is reduced */
4003 return !extended; /* "0" is valid for usual profiles */
4005 return has_single_bit_set(flags);
4008 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
4010 /* cancel requested || normal exit path */
4011 return atomic_read(&fs_info->balance_cancel_req) ||
4012 (atomic_read(&fs_info->balance_pause_req) == 0 &&
4013 atomic_read(&fs_info->balance_cancel_req) == 0);
4017 * Validate target profile against allowed profiles and return true if it's OK.
4018 * Otherwise print the error message and return false.
4020 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
4021 const struct btrfs_balance_args *bargs,
4022 u64 allowed, const char *type)
4024 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4027 if (fs_info->sectorsize < PAGE_SIZE &&
4028 bargs->target & BTRFS_BLOCK_GROUP_RAID56_MASK) {
4030 "RAID56 is not yet supported for sectorsize %u with page size %lu",
4031 fs_info->sectorsize, PAGE_SIZE);
4034 /* Profile is valid and does not have bits outside of the allowed set */
4035 if (alloc_profile_is_valid(bargs->target, 1) &&
4036 (bargs->target & ~allowed) == 0)
4039 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
4040 type, btrfs_bg_type_to_raid_name(bargs->target));
4045 * Fill @buf with textual description of balance filter flags @bargs, up to
4046 * @size_buf including the terminating null. The output may be trimmed if it
4047 * does not fit into the provided buffer.
4049 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4053 u32 size_bp = size_buf;
4055 u64 flags = bargs->flags;
4056 char tmp_buf[128] = {'\0'};
4061 #define CHECK_APPEND_NOARG(a) \
4063 ret = snprintf(bp, size_bp, (a)); \
4064 if (ret < 0 || ret >= size_bp) \
4065 goto out_overflow; \
4070 #define CHECK_APPEND_1ARG(a, v1) \
4072 ret = snprintf(bp, size_bp, (a), (v1)); \
4073 if (ret < 0 || ret >= size_bp) \
4074 goto out_overflow; \
4079 #define CHECK_APPEND_2ARG(a, v1, v2) \
4081 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
4082 if (ret < 0 || ret >= size_bp) \
4083 goto out_overflow; \
4088 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4089 CHECK_APPEND_1ARG("convert=%s,",
4090 btrfs_bg_type_to_raid_name(bargs->target));
4092 if (flags & BTRFS_BALANCE_ARGS_SOFT)
4093 CHECK_APPEND_NOARG("soft,");
4095 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4096 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4098 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4101 if (flags & BTRFS_BALANCE_ARGS_USAGE)
4102 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4104 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4105 CHECK_APPEND_2ARG("usage=%u..%u,",
4106 bargs->usage_min, bargs->usage_max);
4108 if (flags & BTRFS_BALANCE_ARGS_DEVID)
4109 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4111 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4112 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4113 bargs->pstart, bargs->pend);
4115 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4116 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4117 bargs->vstart, bargs->vend);
4119 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4120 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4122 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4123 CHECK_APPEND_2ARG("limit=%u..%u,",
4124 bargs->limit_min, bargs->limit_max);
4126 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4127 CHECK_APPEND_2ARG("stripes=%u..%u,",
4128 bargs->stripes_min, bargs->stripes_max);
4130 #undef CHECK_APPEND_2ARG
4131 #undef CHECK_APPEND_1ARG
4132 #undef CHECK_APPEND_NOARG
4136 if (size_bp < size_buf)
4137 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4142 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4144 u32 size_buf = 1024;
4145 char tmp_buf[192] = {'\0'};
4148 u32 size_bp = size_buf;
4150 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4152 buf = kzalloc(size_buf, GFP_KERNEL);
4158 #define CHECK_APPEND_1ARG(a, v1) \
4160 ret = snprintf(bp, size_bp, (a), (v1)); \
4161 if (ret < 0 || ret >= size_bp) \
4162 goto out_overflow; \
4167 if (bctl->flags & BTRFS_BALANCE_FORCE)
4168 CHECK_APPEND_1ARG("%s", "-f ");
4170 if (bctl->flags & BTRFS_BALANCE_DATA) {
4171 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4172 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4175 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4176 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4177 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4180 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4181 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4182 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4185 #undef CHECK_APPEND_1ARG
4189 if (size_bp < size_buf)
4190 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4191 btrfs_info(fs_info, "balance: %s %s",
4192 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4193 "resume" : "start", buf);
4199 * Should be called with balance mutexe held
4201 int btrfs_balance(struct btrfs_fs_info *fs_info,
4202 struct btrfs_balance_control *bctl,
4203 struct btrfs_ioctl_balance_args *bargs)
4205 u64 meta_target, data_target;
4211 bool reducing_redundancy;
4214 if (btrfs_fs_closing(fs_info) ||
4215 atomic_read(&fs_info->balance_pause_req) ||
4216 btrfs_should_cancel_balance(fs_info)) {
4221 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4222 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4226 * In case of mixed groups both data and meta should be picked,
4227 * and identical options should be given for both of them.
4229 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4230 if (mixed && (bctl->flags & allowed)) {
4231 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4232 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4233 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4235 "balance: mixed groups data and metadata options must be the same");
4242 * rw_devices will not change at the moment, device add/delete/replace
4245 num_devices = fs_info->fs_devices->rw_devices;
4248 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4249 * special bit for it, to make it easier to distinguish. Thus we need
4250 * to set it manually, or balance would refuse the profile.
4252 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4253 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4254 if (num_devices >= btrfs_raid_array[i].devs_min)
4255 allowed |= btrfs_raid_array[i].bg_flag;
4257 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4258 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4259 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
4265 * Allow to reduce metadata or system integrity only if force set for
4266 * profiles with redundancy (copies, parity)
4269 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4270 if (btrfs_raid_array[i].ncopies >= 2 ||
4271 btrfs_raid_array[i].tolerated_failures >= 1)
4272 allowed |= btrfs_raid_array[i].bg_flag;
4275 seq = read_seqbegin(&fs_info->profiles_lock);
4277 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4278 (fs_info->avail_system_alloc_bits & allowed) &&
4279 !(bctl->sys.target & allowed)) ||
4280 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4281 (fs_info->avail_metadata_alloc_bits & allowed) &&
4282 !(bctl->meta.target & allowed)))
4283 reducing_redundancy = true;
4285 reducing_redundancy = false;
4287 /* if we're not converting, the target field is uninitialized */
4288 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4289 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4290 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4291 bctl->data.target : fs_info->avail_data_alloc_bits;
4292 } while (read_seqretry(&fs_info->profiles_lock, seq));
4294 if (reducing_redundancy) {
4295 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4297 "balance: force reducing metadata redundancy");
4300 "balance: reduces metadata redundancy, use --force if you want this");
4306 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4307 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4309 "balance: metadata profile %s has lower redundancy than data profile %s",
4310 btrfs_bg_type_to_raid_name(meta_target),
4311 btrfs_bg_type_to_raid_name(data_target));
4314 ret = insert_balance_item(fs_info, bctl);
4315 if (ret && ret != -EEXIST)
4318 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4319 BUG_ON(ret == -EEXIST);
4320 BUG_ON(fs_info->balance_ctl);
4321 spin_lock(&fs_info->balance_lock);
4322 fs_info->balance_ctl = bctl;
4323 spin_unlock(&fs_info->balance_lock);
4325 BUG_ON(ret != -EEXIST);
4326 spin_lock(&fs_info->balance_lock);
4327 update_balance_args(bctl);
4328 spin_unlock(&fs_info->balance_lock);
4331 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4332 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4333 describe_balance_start_or_resume(fs_info);
4334 mutex_unlock(&fs_info->balance_mutex);
4336 ret = __btrfs_balance(fs_info);
4338 mutex_lock(&fs_info->balance_mutex);
4339 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4340 btrfs_info(fs_info, "balance: paused");
4342 * Balance can be canceled by:
4344 * - Regular cancel request
4345 * Then ret == -ECANCELED and balance_cancel_req > 0
4347 * - Fatal signal to "btrfs" process
4348 * Either the signal caught by wait_reserve_ticket() and callers
4349 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4351 * Either way, in this case balance_cancel_req = 0, and
4352 * ret == -EINTR or ret == -ECANCELED.
4354 * So here we only check the return value to catch canceled balance.
4356 else if (ret == -ECANCELED || ret == -EINTR)
4357 btrfs_info(fs_info, "balance: canceled");
4359 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4361 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4364 memset(bargs, 0, sizeof(*bargs));
4365 btrfs_update_ioctl_balance_args(fs_info, bargs);
4368 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4369 balance_need_close(fs_info)) {
4370 reset_balance_state(fs_info);
4371 btrfs_exclop_finish(fs_info);
4374 wake_up(&fs_info->balance_wait_q);
4378 if (bctl->flags & BTRFS_BALANCE_RESUME)
4379 reset_balance_state(fs_info);
4382 btrfs_exclop_finish(fs_info);
4387 static int balance_kthread(void *data)
4389 struct btrfs_fs_info *fs_info = data;
4392 mutex_lock(&fs_info->balance_mutex);
4393 if (fs_info->balance_ctl)
4394 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4395 mutex_unlock(&fs_info->balance_mutex);
4400 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4402 struct task_struct *tsk;
4404 mutex_lock(&fs_info->balance_mutex);
4405 if (!fs_info->balance_ctl) {
4406 mutex_unlock(&fs_info->balance_mutex);
4409 mutex_unlock(&fs_info->balance_mutex);
4411 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4412 btrfs_info(fs_info, "balance: resume skipped");
4417 * A ro->rw remount sequence should continue with the paused balance
4418 * regardless of who pauses it, system or the user as of now, so set
4421 spin_lock(&fs_info->balance_lock);
4422 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4423 spin_unlock(&fs_info->balance_lock);
4425 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4426 return PTR_ERR_OR_ZERO(tsk);
4429 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4431 struct btrfs_balance_control *bctl;
4432 struct btrfs_balance_item *item;
4433 struct btrfs_disk_balance_args disk_bargs;
4434 struct btrfs_path *path;
4435 struct extent_buffer *leaf;
4436 struct btrfs_key key;
4439 path = btrfs_alloc_path();
4443 key.objectid = BTRFS_BALANCE_OBJECTID;
4444 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4447 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4450 if (ret > 0) { /* ret = -ENOENT; */
4455 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4461 leaf = path->nodes[0];
4462 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4464 bctl->flags = btrfs_balance_flags(leaf, item);
4465 bctl->flags |= BTRFS_BALANCE_RESUME;
4467 btrfs_balance_data(leaf, item, &disk_bargs);
4468 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4469 btrfs_balance_meta(leaf, item, &disk_bargs);
4470 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4471 btrfs_balance_sys(leaf, item, &disk_bargs);
4472 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4475 * This should never happen, as the paused balance state is recovered
4476 * during mount without any chance of other exclusive ops to collide.
4478 * This gives the exclusive op status to balance and keeps in paused
4479 * state until user intervention (cancel or umount). If the ownership
4480 * cannot be assigned, show a message but do not fail. The balance
4481 * is in a paused state and must have fs_info::balance_ctl properly
4484 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
4486 "balance: cannot set exclusive op status, resume manually");
4488 btrfs_release_path(path);
4490 mutex_lock(&fs_info->balance_mutex);
4491 BUG_ON(fs_info->balance_ctl);
4492 spin_lock(&fs_info->balance_lock);
4493 fs_info->balance_ctl = bctl;
4494 spin_unlock(&fs_info->balance_lock);
4495 mutex_unlock(&fs_info->balance_mutex);
4497 btrfs_free_path(path);
4501 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4505 mutex_lock(&fs_info->balance_mutex);
4506 if (!fs_info->balance_ctl) {
4507 mutex_unlock(&fs_info->balance_mutex);
4511 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4512 atomic_inc(&fs_info->balance_pause_req);
4513 mutex_unlock(&fs_info->balance_mutex);
4515 wait_event(fs_info->balance_wait_q,
4516 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4518 mutex_lock(&fs_info->balance_mutex);
4519 /* we are good with balance_ctl ripped off from under us */
4520 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4521 atomic_dec(&fs_info->balance_pause_req);
4526 mutex_unlock(&fs_info->balance_mutex);
4530 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4532 mutex_lock(&fs_info->balance_mutex);
4533 if (!fs_info->balance_ctl) {
4534 mutex_unlock(&fs_info->balance_mutex);
4539 * A paused balance with the item stored on disk can be resumed at
4540 * mount time if the mount is read-write. Otherwise it's still paused
4541 * and we must not allow cancelling as it deletes the item.
4543 if (sb_rdonly(fs_info->sb)) {
4544 mutex_unlock(&fs_info->balance_mutex);
4548 atomic_inc(&fs_info->balance_cancel_req);
4550 * if we are running just wait and return, balance item is
4551 * deleted in btrfs_balance in this case
4553 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4554 mutex_unlock(&fs_info->balance_mutex);
4555 wait_event(fs_info->balance_wait_q,
4556 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4557 mutex_lock(&fs_info->balance_mutex);
4559 mutex_unlock(&fs_info->balance_mutex);
4561 * Lock released to allow other waiters to continue, we'll
4562 * reexamine the status again.
4564 mutex_lock(&fs_info->balance_mutex);
4566 if (fs_info->balance_ctl) {
4567 reset_balance_state(fs_info);
4568 btrfs_exclop_finish(fs_info);
4569 btrfs_info(fs_info, "balance: canceled");
4573 BUG_ON(fs_info->balance_ctl ||
4574 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4575 atomic_dec(&fs_info->balance_cancel_req);
4576 mutex_unlock(&fs_info->balance_mutex);
4580 int btrfs_uuid_scan_kthread(void *data)
4582 struct btrfs_fs_info *fs_info = data;
4583 struct btrfs_root *root = fs_info->tree_root;
4584 struct btrfs_key key;
4585 struct btrfs_path *path = NULL;
4587 struct extent_buffer *eb;
4589 struct btrfs_root_item root_item;
4591 struct btrfs_trans_handle *trans = NULL;
4592 bool closing = false;
4594 path = btrfs_alloc_path();
4601 key.type = BTRFS_ROOT_ITEM_KEY;
4605 if (btrfs_fs_closing(fs_info)) {
4609 ret = btrfs_search_forward(root, &key, path,
4610 BTRFS_OLDEST_GENERATION);
4617 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4618 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4619 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4620 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4623 eb = path->nodes[0];
4624 slot = path->slots[0];
4625 item_size = btrfs_item_size_nr(eb, slot);
4626 if (item_size < sizeof(root_item))
4629 read_extent_buffer(eb, &root_item,
4630 btrfs_item_ptr_offset(eb, slot),
4631 (int)sizeof(root_item));
4632 if (btrfs_root_refs(&root_item) == 0)
4635 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4636 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4640 btrfs_release_path(path);
4642 * 1 - subvol uuid item
4643 * 1 - received_subvol uuid item
4645 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4646 if (IS_ERR(trans)) {
4647 ret = PTR_ERR(trans);
4655 btrfs_release_path(path);
4656 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4657 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4658 BTRFS_UUID_KEY_SUBVOL,
4661 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4667 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4668 ret = btrfs_uuid_tree_add(trans,
4669 root_item.received_uuid,
4670 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4673 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4680 btrfs_release_path(path);
4682 ret = btrfs_end_transaction(trans);
4688 if (key.offset < (u64)-1) {
4690 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4692 key.type = BTRFS_ROOT_ITEM_KEY;
4693 } else if (key.objectid < (u64)-1) {
4695 key.type = BTRFS_ROOT_ITEM_KEY;
4704 btrfs_free_path(path);
4705 if (trans && !IS_ERR(trans))
4706 btrfs_end_transaction(trans);
4708 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4710 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4711 up(&fs_info->uuid_tree_rescan_sem);
4715 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4717 struct btrfs_trans_handle *trans;
4718 struct btrfs_root *tree_root = fs_info->tree_root;
4719 struct btrfs_root *uuid_root;
4720 struct task_struct *task;
4727 trans = btrfs_start_transaction(tree_root, 2);
4729 return PTR_ERR(trans);
4731 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4732 if (IS_ERR(uuid_root)) {
4733 ret = PTR_ERR(uuid_root);
4734 btrfs_abort_transaction(trans, ret);
4735 btrfs_end_transaction(trans);
4739 fs_info->uuid_root = uuid_root;
4741 ret = btrfs_commit_transaction(trans);
4745 down(&fs_info->uuid_tree_rescan_sem);
4746 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4748 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4749 btrfs_warn(fs_info, "failed to start uuid_scan task");
4750 up(&fs_info->uuid_tree_rescan_sem);
4751 return PTR_ERR(task);
4758 * shrinking a device means finding all of the device extents past
4759 * the new size, and then following the back refs to the chunks.
4760 * The chunk relocation code actually frees the device extent
4762 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4764 struct btrfs_fs_info *fs_info = device->fs_info;
4765 struct btrfs_root *root = fs_info->dev_root;
4766 struct btrfs_trans_handle *trans;
4767 struct btrfs_dev_extent *dev_extent = NULL;
4768 struct btrfs_path *path;
4774 bool retried = false;
4775 struct extent_buffer *l;
4776 struct btrfs_key key;
4777 struct btrfs_super_block *super_copy = fs_info->super_copy;
4778 u64 old_total = btrfs_super_total_bytes(super_copy);
4779 u64 old_size = btrfs_device_get_total_bytes(device);
4783 new_size = round_down(new_size, fs_info->sectorsize);
4785 diff = round_down(old_size - new_size, fs_info->sectorsize);
4787 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4790 path = btrfs_alloc_path();
4794 path->reada = READA_BACK;
4796 trans = btrfs_start_transaction(root, 0);
4797 if (IS_ERR(trans)) {
4798 btrfs_free_path(path);
4799 return PTR_ERR(trans);
4802 mutex_lock(&fs_info->chunk_mutex);
4804 btrfs_device_set_total_bytes(device, new_size);
4805 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4806 device->fs_devices->total_rw_bytes -= diff;
4807 atomic64_sub(diff, &fs_info->free_chunk_space);
4811 * Once the device's size has been set to the new size, ensure all
4812 * in-memory chunks are synced to disk so that the loop below sees them
4813 * and relocates them accordingly.
4815 if (contains_pending_extent(device, &start, diff)) {
4816 mutex_unlock(&fs_info->chunk_mutex);
4817 ret = btrfs_commit_transaction(trans);
4821 mutex_unlock(&fs_info->chunk_mutex);
4822 btrfs_end_transaction(trans);
4826 key.objectid = device->devid;
4827 key.offset = (u64)-1;
4828 key.type = BTRFS_DEV_EXTENT_KEY;
4831 mutex_lock(&fs_info->reclaim_bgs_lock);
4832 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4834 mutex_unlock(&fs_info->reclaim_bgs_lock);
4838 ret = btrfs_previous_item(root, path, 0, key.type);
4840 mutex_unlock(&fs_info->reclaim_bgs_lock);
4844 btrfs_release_path(path);
4849 slot = path->slots[0];
4850 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4852 if (key.objectid != device->devid) {
4853 mutex_unlock(&fs_info->reclaim_bgs_lock);
4854 btrfs_release_path(path);
4858 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4859 length = btrfs_dev_extent_length(l, dev_extent);
4861 if (key.offset + length <= new_size) {
4862 mutex_unlock(&fs_info->reclaim_bgs_lock);
4863 btrfs_release_path(path);
4867 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4868 btrfs_release_path(path);
4871 * We may be relocating the only data chunk we have,
4872 * which could potentially end up with losing data's
4873 * raid profile, so lets allocate an empty one in
4876 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4878 mutex_unlock(&fs_info->reclaim_bgs_lock);
4882 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4883 mutex_unlock(&fs_info->reclaim_bgs_lock);
4884 if (ret == -ENOSPC) {
4887 if (ret == -ETXTBSY) {
4889 "could not shrink block group %llu due to active swapfile",
4894 } while (key.offset-- > 0);
4896 if (failed && !retried) {
4900 } else if (failed && retried) {
4905 /* Shrinking succeeded, else we would be at "done". */
4906 trans = btrfs_start_transaction(root, 0);
4907 if (IS_ERR(trans)) {
4908 ret = PTR_ERR(trans);
4912 mutex_lock(&fs_info->chunk_mutex);
4913 /* Clear all state bits beyond the shrunk device size */
4914 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4917 btrfs_device_set_disk_total_bytes(device, new_size);
4918 if (list_empty(&device->post_commit_list))
4919 list_add_tail(&device->post_commit_list,
4920 &trans->transaction->dev_update_list);
4922 WARN_ON(diff > old_total);
4923 btrfs_set_super_total_bytes(super_copy,
4924 round_down(old_total - diff, fs_info->sectorsize));
4925 mutex_unlock(&fs_info->chunk_mutex);
4927 /* Now btrfs_update_device() will change the on-disk size. */
4928 ret = btrfs_update_device(trans, device);
4930 btrfs_abort_transaction(trans, ret);
4931 btrfs_end_transaction(trans);
4933 ret = btrfs_commit_transaction(trans);
4936 btrfs_free_path(path);
4938 mutex_lock(&fs_info->chunk_mutex);
4939 btrfs_device_set_total_bytes(device, old_size);
4940 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4941 device->fs_devices->total_rw_bytes += diff;
4942 atomic64_add(diff, &fs_info->free_chunk_space);
4943 mutex_unlock(&fs_info->chunk_mutex);
4948 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4949 struct btrfs_key *key,
4950 struct btrfs_chunk *chunk, int item_size)
4952 struct btrfs_super_block *super_copy = fs_info->super_copy;
4953 struct btrfs_disk_key disk_key;
4957 lockdep_assert_held(&fs_info->chunk_mutex);
4959 array_size = btrfs_super_sys_array_size(super_copy);
4960 if (array_size + item_size + sizeof(disk_key)
4961 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
4964 ptr = super_copy->sys_chunk_array + array_size;
4965 btrfs_cpu_key_to_disk(&disk_key, key);
4966 memcpy(ptr, &disk_key, sizeof(disk_key));
4967 ptr += sizeof(disk_key);
4968 memcpy(ptr, chunk, item_size);
4969 item_size += sizeof(disk_key);
4970 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4976 * sort the devices in descending order by max_avail, total_avail
4978 static int btrfs_cmp_device_info(const void *a, const void *b)
4980 const struct btrfs_device_info *di_a = a;
4981 const struct btrfs_device_info *di_b = b;
4983 if (di_a->max_avail > di_b->max_avail)
4985 if (di_a->max_avail < di_b->max_avail)
4987 if (di_a->total_avail > di_b->total_avail)
4989 if (di_a->total_avail < di_b->total_avail)
4994 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4996 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4999 btrfs_set_fs_incompat(info, RAID56);
5002 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
5004 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
5007 btrfs_set_fs_incompat(info, RAID1C34);
5011 * Structure used internally for __btrfs_alloc_chunk() function.
5012 * Wraps needed parameters.
5014 struct alloc_chunk_ctl {
5017 /* Total number of stripes to allocate */
5019 /* sub_stripes info for map */
5021 /* Stripes per device */
5023 /* Maximum number of devices to use */
5025 /* Minimum number of devices to use */
5027 /* ndevs has to be a multiple of this */
5029 /* Number of copies */
5031 /* Number of stripes worth of bytes to store parity information */
5033 u64 max_stripe_size;
5041 static void init_alloc_chunk_ctl_policy_regular(
5042 struct btrfs_fs_devices *fs_devices,
5043 struct alloc_chunk_ctl *ctl)
5045 u64 type = ctl->type;
5047 if (type & BTRFS_BLOCK_GROUP_DATA) {
5048 ctl->max_stripe_size = SZ_1G;
5049 ctl->max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
5050 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5051 /* For larger filesystems, use larger metadata chunks */
5052 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
5053 ctl->max_stripe_size = SZ_1G;
5055 ctl->max_stripe_size = SZ_256M;
5056 ctl->max_chunk_size = ctl->max_stripe_size;
5057 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5058 ctl->max_stripe_size = SZ_32M;
5059 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5060 ctl->devs_max = min_t(int, ctl->devs_max,
5061 BTRFS_MAX_DEVS_SYS_CHUNK);
5066 /* We don't want a chunk larger than 10% of writable space */
5067 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
5068 ctl->max_chunk_size);
5069 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
5072 static void init_alloc_chunk_ctl_policy_zoned(
5073 struct btrfs_fs_devices *fs_devices,
5074 struct alloc_chunk_ctl *ctl)
5076 u64 zone_size = fs_devices->fs_info->zone_size;
5078 int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5079 int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5080 u64 min_chunk_size = min_data_stripes * zone_size;
5081 u64 type = ctl->type;
5083 ctl->max_stripe_size = zone_size;
5084 if (type & BTRFS_BLOCK_GROUP_DATA) {
5085 ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5087 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5088 ctl->max_chunk_size = ctl->max_stripe_size;
5089 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5090 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5091 ctl->devs_max = min_t(int, ctl->devs_max,
5092 BTRFS_MAX_DEVS_SYS_CHUNK);
5097 /* We don't want a chunk larger than 10% of writable space */
5098 limit = max(round_down(div_factor(fs_devices->total_rw_bytes, 1),
5101 ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5102 ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5105 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5106 struct alloc_chunk_ctl *ctl)
5108 int index = btrfs_bg_flags_to_raid_index(ctl->type);
5110 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5111 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5112 ctl->devs_max = btrfs_raid_array[index].devs_max;
5114 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5115 ctl->devs_min = btrfs_raid_array[index].devs_min;
5116 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5117 ctl->ncopies = btrfs_raid_array[index].ncopies;
5118 ctl->nparity = btrfs_raid_array[index].nparity;
5121 switch (fs_devices->chunk_alloc_policy) {
5122 case BTRFS_CHUNK_ALLOC_REGULAR:
5123 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5125 case BTRFS_CHUNK_ALLOC_ZONED:
5126 init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5133 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5134 struct alloc_chunk_ctl *ctl,
5135 struct btrfs_device_info *devices_info)
5137 struct btrfs_fs_info *info = fs_devices->fs_info;
5138 struct btrfs_device *device;
5140 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5147 * in the first pass through the devices list, we gather information
5148 * about the available holes on each device.
5150 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5151 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5153 "BTRFS: read-only device in alloc_list\n");
5157 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5158 &device->dev_state) ||
5159 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5162 if (device->total_bytes > device->bytes_used)
5163 total_avail = device->total_bytes - device->bytes_used;
5167 /* If there is no space on this device, skip it. */
5168 if (total_avail < ctl->dev_extent_min)
5171 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5173 if (ret && ret != -ENOSPC)
5177 max_avail = dev_extent_want;
5179 if (max_avail < ctl->dev_extent_min) {
5180 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5182 "%s: devid %llu has no free space, have=%llu want=%llu",
5183 __func__, device->devid, max_avail,
5184 ctl->dev_extent_min);
5188 if (ndevs == fs_devices->rw_devices) {
5189 WARN(1, "%s: found more than %llu devices\n",
5190 __func__, fs_devices->rw_devices);
5193 devices_info[ndevs].dev_offset = dev_offset;
5194 devices_info[ndevs].max_avail = max_avail;
5195 devices_info[ndevs].total_avail = total_avail;
5196 devices_info[ndevs].dev = device;
5202 * now sort the devices by hole size / available space
5204 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5205 btrfs_cmp_device_info, NULL);
5210 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5211 struct btrfs_device_info *devices_info)
5213 /* Number of stripes that count for block group size */
5217 * The primary goal is to maximize the number of stripes, so use as
5218 * many devices as possible, even if the stripes are not maximum sized.
5220 * The DUP profile stores more than one stripe per device, the
5221 * max_avail is the total size so we have to adjust.
5223 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5225 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5227 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5228 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5231 * Use the number of data stripes to figure out how big this chunk is
5232 * really going to be in terms of logical address space, and compare
5233 * that answer with the max chunk size. If it's higher, we try to
5234 * reduce stripe_size.
5236 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5238 * Reduce stripe_size, round it up to a 16MB boundary again and
5239 * then use it, unless it ends up being even bigger than the
5240 * previous value we had already.
5242 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5243 data_stripes), SZ_16M),
5247 /* Align to BTRFS_STRIPE_LEN */
5248 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5249 ctl->chunk_size = ctl->stripe_size * data_stripes;
5254 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5255 struct btrfs_device_info *devices_info)
5257 u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5258 /* Number of stripes that count for block group size */
5262 * It should hold because:
5263 * dev_extent_min == dev_extent_want == zone_size * dev_stripes
5265 ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min);
5267 ctl->stripe_size = zone_size;
5268 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5269 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5271 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */
5272 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5273 ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5274 ctl->stripe_size) + ctl->nparity,
5276 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5277 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5278 ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size);
5281 ctl->chunk_size = ctl->stripe_size * data_stripes;
5286 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5287 struct alloc_chunk_ctl *ctl,
5288 struct btrfs_device_info *devices_info)
5290 struct btrfs_fs_info *info = fs_devices->fs_info;
5293 * Round down to number of usable stripes, devs_increment can be any
5294 * number so we can't use round_down() that requires power of 2, while
5295 * rounddown is safe.
5297 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5299 if (ctl->ndevs < ctl->devs_min) {
5300 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5302 "%s: not enough devices with free space: have=%d minimum required=%d",
5303 __func__, ctl->ndevs, ctl->devs_min);
5308 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5310 switch (fs_devices->chunk_alloc_policy) {
5311 case BTRFS_CHUNK_ALLOC_REGULAR:
5312 return decide_stripe_size_regular(ctl, devices_info);
5313 case BTRFS_CHUNK_ALLOC_ZONED:
5314 return decide_stripe_size_zoned(ctl, devices_info);
5320 static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
5321 struct alloc_chunk_ctl *ctl,
5322 struct btrfs_device_info *devices_info)
5324 struct btrfs_fs_info *info = trans->fs_info;
5325 struct map_lookup *map = NULL;
5326 struct extent_map_tree *em_tree;
5327 struct btrfs_block_group *block_group;
5328 struct extent_map *em;
5329 u64 start = ctl->start;
5330 u64 type = ctl->type;
5335 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5337 return ERR_PTR(-ENOMEM);
5338 map->num_stripes = ctl->num_stripes;
5340 for (i = 0; i < ctl->ndevs; ++i) {
5341 for (j = 0; j < ctl->dev_stripes; ++j) {
5342 int s = i * ctl->dev_stripes + j;
5343 map->stripes[s].dev = devices_info[i].dev;
5344 map->stripes[s].physical = devices_info[i].dev_offset +
5345 j * ctl->stripe_size;
5348 map->stripe_len = BTRFS_STRIPE_LEN;
5349 map->io_align = BTRFS_STRIPE_LEN;
5350 map->io_width = BTRFS_STRIPE_LEN;
5352 map->sub_stripes = ctl->sub_stripes;
5354 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5356 em = alloc_extent_map();
5359 return ERR_PTR(-ENOMEM);
5361 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5362 em->map_lookup = map;
5364 em->len = ctl->chunk_size;
5365 em->block_start = 0;
5366 em->block_len = em->len;
5367 em->orig_block_len = ctl->stripe_size;
5369 em_tree = &info->mapping_tree;
5370 write_lock(&em_tree->lock);
5371 ret = add_extent_mapping(em_tree, em, 0);
5373 write_unlock(&em_tree->lock);
5374 free_extent_map(em);
5375 return ERR_PTR(ret);
5377 write_unlock(&em_tree->lock);
5379 block_group = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5380 if (IS_ERR(block_group))
5381 goto error_del_extent;
5383 for (i = 0; i < map->num_stripes; i++) {
5384 struct btrfs_device *dev = map->stripes[i].dev;
5386 btrfs_device_set_bytes_used(dev,
5387 dev->bytes_used + ctl->stripe_size);
5388 if (list_empty(&dev->post_commit_list))
5389 list_add_tail(&dev->post_commit_list,
5390 &trans->transaction->dev_update_list);
5393 atomic64_sub(ctl->stripe_size * map->num_stripes,
5394 &info->free_chunk_space);
5396 free_extent_map(em);
5397 check_raid56_incompat_flag(info, type);
5398 check_raid1c34_incompat_flag(info, type);
5403 write_lock(&em_tree->lock);
5404 remove_extent_mapping(em_tree, em);
5405 write_unlock(&em_tree->lock);
5407 /* One for our allocation */
5408 free_extent_map(em);
5409 /* One for the tree reference */
5410 free_extent_map(em);
5415 struct btrfs_block_group *btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
5418 struct btrfs_fs_info *info = trans->fs_info;
5419 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5420 struct btrfs_device_info *devices_info = NULL;
5421 struct alloc_chunk_ctl ctl;
5422 struct btrfs_block_group *block_group;
5425 lockdep_assert_held(&info->chunk_mutex);
5427 if (!alloc_profile_is_valid(type, 0)) {
5429 return ERR_PTR(-EINVAL);
5432 if (list_empty(&fs_devices->alloc_list)) {
5433 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5434 btrfs_debug(info, "%s: no writable device", __func__);
5435 return ERR_PTR(-ENOSPC);
5438 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5439 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5441 return ERR_PTR(-EINVAL);
5444 ctl.start = find_next_chunk(info);
5446 init_alloc_chunk_ctl(fs_devices, &ctl);
5448 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5451 return ERR_PTR(-ENOMEM);
5453 ret = gather_device_info(fs_devices, &ctl, devices_info);
5455 block_group = ERR_PTR(ret);
5459 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5461 block_group = ERR_PTR(ret);
5465 block_group = create_chunk(trans, &ctl, devices_info);
5468 kfree(devices_info);
5473 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5474 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5477 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5480 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
5481 struct btrfs_block_group *bg)
5483 struct btrfs_fs_info *fs_info = trans->fs_info;
5484 struct btrfs_root *extent_root = fs_info->extent_root;
5485 struct btrfs_root *chunk_root = fs_info->chunk_root;
5486 struct btrfs_key key;
5487 struct btrfs_chunk *chunk;
5488 struct btrfs_stripe *stripe;
5489 struct extent_map *em;
5490 struct map_lookup *map;
5496 * We take the chunk_mutex for 2 reasons:
5498 * 1) Updates and insertions in the chunk btree must be done while holding
5499 * the chunk_mutex, as well as updating the system chunk array in the
5500 * superblock. See the comment on top of btrfs_chunk_alloc() for the
5503 * 2) To prevent races with the final phase of a device replace operation
5504 * that replaces the device object associated with the map's stripes,
5505 * because the device object's id can change at any time during that
5506 * final phase of the device replace operation
5507 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5508 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5509 * which would cause a failure when updating the device item, which does
5510 * not exists, or persisting a stripe of the chunk item with such ID.
5511 * Here we can't use the device_list_mutex because our caller already
5512 * has locked the chunk_mutex, and the final phase of device replace
5513 * acquires both mutexes - first the device_list_mutex and then the
5514 * chunk_mutex. Using any of those two mutexes protects us from a
5515 * concurrent device replace.
5517 lockdep_assert_held(&fs_info->chunk_mutex);
5519 em = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
5522 btrfs_abort_transaction(trans, ret);
5526 map = em->map_lookup;
5527 item_size = btrfs_chunk_item_size(map->num_stripes);
5529 chunk = kzalloc(item_size, GFP_NOFS);
5532 btrfs_abort_transaction(trans, ret);
5536 for (i = 0; i < map->num_stripes; i++) {
5537 struct btrfs_device *device = map->stripes[i].dev;
5539 ret = btrfs_update_device(trans, device);
5544 stripe = &chunk->stripe;
5545 for (i = 0; i < map->num_stripes; i++) {
5546 struct btrfs_device *device = map->stripes[i].dev;
5547 const u64 dev_offset = map->stripes[i].physical;
5549 btrfs_set_stack_stripe_devid(stripe, device->devid);
5550 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5551 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5555 btrfs_set_stack_chunk_length(chunk, bg->length);
5556 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5557 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5558 btrfs_set_stack_chunk_type(chunk, map->type);
5559 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5560 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5561 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5562 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5563 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5565 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5566 key.type = BTRFS_CHUNK_ITEM_KEY;
5567 key.offset = bg->start;
5569 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5573 bg->chunk_item_inserted = 1;
5575 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5576 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5583 free_extent_map(em);
5587 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5589 struct btrfs_fs_info *fs_info = trans->fs_info;
5591 struct btrfs_block_group *meta_bg;
5592 struct btrfs_block_group *sys_bg;
5595 * When adding a new device for sprouting, the seed device is read-only
5596 * so we must first allocate a metadata and a system chunk. But before
5597 * adding the block group items to the extent, device and chunk btrees,
5600 * 1) Create both chunks without doing any changes to the btrees, as
5601 * otherwise we would get -ENOSPC since the block groups from the
5602 * seed device are read-only;
5604 * 2) Add the device item for the new sprout device - finishing the setup
5605 * of a new block group requires updating the device item in the chunk
5606 * btree, so it must exist when we attempt to do it. The previous step
5607 * ensures this does not fail with -ENOSPC.
5609 * After that we can add the block group items to their btrees:
5610 * update existing device item in the chunk btree, add a new block group
5611 * item to the extent btree, add a new chunk item to the chunk btree and
5612 * finally add the new device extent items to the devices btree.
5615 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5616 meta_bg = btrfs_alloc_chunk(trans, alloc_profile);
5617 if (IS_ERR(meta_bg))
5618 return PTR_ERR(meta_bg);
5620 alloc_profile = btrfs_system_alloc_profile(fs_info);
5621 sys_bg = btrfs_alloc_chunk(trans, alloc_profile);
5623 return PTR_ERR(sys_bg);
5628 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5630 const int index = btrfs_bg_flags_to_raid_index(map->type);
5632 return btrfs_raid_array[index].tolerated_failures;
5635 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5637 struct extent_map *em;
5638 struct map_lookup *map;
5643 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5647 map = em->map_lookup;
5648 for (i = 0; i < map->num_stripes; i++) {
5649 if (test_bit(BTRFS_DEV_STATE_MISSING,
5650 &map->stripes[i].dev->dev_state)) {
5654 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5655 &map->stripes[i].dev->dev_state)) {
5662 * If the number of missing devices is larger than max errors,
5663 * we can not write the data into that chunk successfully, so
5666 if (miss_ndevs > btrfs_chunk_max_errors(map))
5669 free_extent_map(em);
5673 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5675 struct extent_map *em;
5678 write_lock(&tree->lock);
5679 em = lookup_extent_mapping(tree, 0, (u64)-1);
5681 remove_extent_mapping(tree, em);
5682 write_unlock(&tree->lock);
5686 free_extent_map(em);
5687 /* once for the tree */
5688 free_extent_map(em);
5692 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5694 struct extent_map *em;
5695 struct map_lookup *map;
5698 em = btrfs_get_chunk_map(fs_info, logical, len);
5701 * We could return errors for these cases, but that could get
5702 * ugly and we'd probably do the same thing which is just not do
5703 * anything else and exit, so return 1 so the callers don't try
5704 * to use other copies.
5708 map = em->map_lookup;
5709 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5710 ret = map->num_stripes;
5711 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5712 ret = map->sub_stripes;
5713 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5715 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5717 * There could be two corrupted data stripes, we need
5718 * to loop retry in order to rebuild the correct data.
5720 * Fail a stripe at a time on every retry except the
5721 * stripe under reconstruction.
5723 ret = map->num_stripes;
5726 free_extent_map(em);
5728 down_read(&fs_info->dev_replace.rwsem);
5729 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5730 fs_info->dev_replace.tgtdev)
5732 up_read(&fs_info->dev_replace.rwsem);
5737 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5740 struct extent_map *em;
5741 struct map_lookup *map;
5742 unsigned long len = fs_info->sectorsize;
5744 em = btrfs_get_chunk_map(fs_info, logical, len);
5746 if (!WARN_ON(IS_ERR(em))) {
5747 map = em->map_lookup;
5748 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5749 len = map->stripe_len * nr_data_stripes(map);
5750 free_extent_map(em);
5755 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5757 struct extent_map *em;
5758 struct map_lookup *map;
5761 em = btrfs_get_chunk_map(fs_info, logical, len);
5763 if(!WARN_ON(IS_ERR(em))) {
5764 map = em->map_lookup;
5765 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5767 free_extent_map(em);
5772 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5773 struct map_lookup *map, int first,
5774 int dev_replace_is_ongoing)
5778 int preferred_mirror;
5780 struct btrfs_device *srcdev;
5783 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5785 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5786 num_stripes = map->sub_stripes;
5788 num_stripes = map->num_stripes;
5790 switch (fs_info->fs_devices->read_policy) {
5792 /* Shouldn't happen, just warn and use pid instead of failing */
5793 btrfs_warn_rl(fs_info,
5794 "unknown read_policy type %u, reset to pid",
5795 fs_info->fs_devices->read_policy);
5796 fs_info->fs_devices->read_policy = BTRFS_READ_POLICY_PID;
5798 case BTRFS_READ_POLICY_PID:
5799 preferred_mirror = first + (current->pid % num_stripes);
5803 if (dev_replace_is_ongoing &&
5804 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5805 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5806 srcdev = fs_info->dev_replace.srcdev;
5811 * try to avoid the drive that is the source drive for a
5812 * dev-replace procedure, only choose it if no other non-missing
5813 * mirror is available
5815 for (tolerance = 0; tolerance < 2; tolerance++) {
5816 if (map->stripes[preferred_mirror].dev->bdev &&
5817 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5818 return preferred_mirror;
5819 for (i = first; i < first + num_stripes; i++) {
5820 if (map->stripes[i].dev->bdev &&
5821 (tolerance || map->stripes[i].dev != srcdev))
5826 /* we couldn't find one that doesn't fail. Just return something
5827 * and the io error handling code will clean up eventually
5829 return preferred_mirror;
5832 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5833 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5840 for (i = 0; i < num_stripes - 1; i++) {
5841 /* Swap if parity is on a smaller index */
5842 if (bbio->raid_map[i] > bbio->raid_map[i + 1]) {
5843 swap(bbio->stripes[i], bbio->stripes[i + 1]);
5844 swap(bbio->raid_map[i], bbio->raid_map[i + 1]);
5851 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5853 struct btrfs_bio *bbio = kzalloc(
5854 /* the size of the btrfs_bio */
5855 sizeof(struct btrfs_bio) +
5856 /* plus the variable array for the stripes */
5857 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5858 /* plus the variable array for the tgt dev */
5859 sizeof(int) * (real_stripes) +
5861 * plus the raid_map, which includes both the tgt dev
5864 sizeof(u64) * (total_stripes),
5865 GFP_NOFS|__GFP_NOFAIL);
5867 atomic_set(&bbio->error, 0);
5868 refcount_set(&bbio->refs, 1);
5870 bbio->tgtdev_map = (int *)(bbio->stripes + total_stripes);
5871 bbio->raid_map = (u64 *)(bbio->tgtdev_map + real_stripes);
5876 void btrfs_get_bbio(struct btrfs_bio *bbio)
5878 WARN_ON(!refcount_read(&bbio->refs));
5879 refcount_inc(&bbio->refs);
5882 void btrfs_put_bbio(struct btrfs_bio *bbio)
5886 if (refcount_dec_and_test(&bbio->refs))
5890 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5892 * Please note that, discard won't be sent to target device of device
5895 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5896 u64 logical, u64 *length_ret,
5897 struct btrfs_bio **bbio_ret)
5899 struct extent_map *em;
5900 struct map_lookup *map;
5901 struct btrfs_bio *bbio;
5902 u64 length = *length_ret;
5906 u64 stripe_end_offset;
5913 u32 sub_stripes = 0;
5914 u64 stripes_per_dev = 0;
5915 u32 remaining_stripes = 0;
5916 u32 last_stripe = 0;
5920 /* discard always return a bbio */
5923 em = btrfs_get_chunk_map(fs_info, logical, length);
5927 map = em->map_lookup;
5928 /* we don't discard raid56 yet */
5929 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5934 offset = logical - em->start;
5935 length = min_t(u64, em->start + em->len - logical, length);
5936 *length_ret = length;
5938 stripe_len = map->stripe_len;
5940 * stripe_nr counts the total number of stripes we have to stride
5941 * to get to this block
5943 stripe_nr = div64_u64(offset, stripe_len);
5945 /* stripe_offset is the offset of this block in its stripe */
5946 stripe_offset = offset - stripe_nr * stripe_len;
5948 stripe_nr_end = round_up(offset + length, map->stripe_len);
5949 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5950 stripe_cnt = stripe_nr_end - stripe_nr;
5951 stripe_end_offset = stripe_nr_end * map->stripe_len -
5954 * after this, stripe_nr is the number of stripes on this
5955 * device we have to walk to find the data, and stripe_index is
5956 * the number of our device in the stripe array
5960 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5961 BTRFS_BLOCK_GROUP_RAID10)) {
5962 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5965 sub_stripes = map->sub_stripes;
5967 factor = map->num_stripes / sub_stripes;
5968 num_stripes = min_t(u64, map->num_stripes,
5969 sub_stripes * stripe_cnt);
5970 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5971 stripe_index *= sub_stripes;
5972 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5973 &remaining_stripes);
5974 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5975 last_stripe *= sub_stripes;
5976 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5977 BTRFS_BLOCK_GROUP_DUP)) {
5978 num_stripes = map->num_stripes;
5980 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5984 bbio = alloc_btrfs_bio(num_stripes, 0);
5990 for (i = 0; i < num_stripes; i++) {
5991 bbio->stripes[i].physical =
5992 map->stripes[stripe_index].physical +
5993 stripe_offset + stripe_nr * map->stripe_len;
5994 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5996 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5997 BTRFS_BLOCK_GROUP_RAID10)) {
5998 bbio->stripes[i].length = stripes_per_dev *
6001 if (i / sub_stripes < remaining_stripes)
6002 bbio->stripes[i].length +=
6006 * Special for the first stripe and
6009 * |-------|...|-------|
6013 if (i < sub_stripes)
6014 bbio->stripes[i].length -=
6017 if (stripe_index >= last_stripe &&
6018 stripe_index <= (last_stripe +
6020 bbio->stripes[i].length -=
6023 if (i == sub_stripes - 1)
6026 bbio->stripes[i].length = length;
6030 if (stripe_index == map->num_stripes) {
6037 bbio->map_type = map->type;
6038 bbio->num_stripes = num_stripes;
6040 free_extent_map(em);
6045 * In dev-replace case, for repair case (that's the only case where the mirror
6046 * is selected explicitly when calling btrfs_map_block), blocks left of the
6047 * left cursor can also be read from the target drive.
6049 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
6051 * For READ, it also needs to be supported using the same mirror number.
6053 * If the requested block is not left of the left cursor, EIO is returned. This
6054 * can happen because btrfs_num_copies() returns one more in the dev-replace
6057 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
6058 u64 logical, u64 length,
6059 u64 srcdev_devid, int *mirror_num,
6062 struct btrfs_bio *bbio = NULL;
6064 int index_srcdev = 0;
6066 u64 physical_of_found = 0;
6070 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
6071 logical, &length, &bbio, 0, 0);
6073 ASSERT(bbio == NULL);
6077 num_stripes = bbio->num_stripes;
6078 if (*mirror_num > num_stripes) {
6080 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
6081 * that means that the requested area is not left of the left
6084 btrfs_put_bbio(bbio);
6089 * process the rest of the function using the mirror_num of the source
6090 * drive. Therefore look it up first. At the end, patch the device
6091 * pointer to the one of the target drive.
6093 for (i = 0; i < num_stripes; i++) {
6094 if (bbio->stripes[i].dev->devid != srcdev_devid)
6098 * In case of DUP, in order to keep it simple, only add the
6099 * mirror with the lowest physical address
6102 physical_of_found <= bbio->stripes[i].physical)
6107 physical_of_found = bbio->stripes[i].physical;
6110 btrfs_put_bbio(bbio);
6116 *mirror_num = index_srcdev + 1;
6117 *physical = physical_of_found;
6121 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6123 struct btrfs_block_group *cache;
6126 /* Non zoned filesystem does not use "to_copy" flag */
6127 if (!btrfs_is_zoned(fs_info))
6130 cache = btrfs_lookup_block_group(fs_info, logical);
6132 spin_lock(&cache->lock);
6133 ret = cache->to_copy;
6134 spin_unlock(&cache->lock);
6136 btrfs_put_block_group(cache);
6140 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
6141 struct btrfs_bio **bbio_ret,
6142 struct btrfs_dev_replace *dev_replace,
6144 int *num_stripes_ret, int *max_errors_ret)
6146 struct btrfs_bio *bbio = *bbio_ret;
6147 u64 srcdev_devid = dev_replace->srcdev->devid;
6148 int tgtdev_indexes = 0;
6149 int num_stripes = *num_stripes_ret;
6150 int max_errors = *max_errors_ret;
6153 if (op == BTRFS_MAP_WRITE) {
6154 int index_where_to_add;
6157 * A block group which have "to_copy" set will eventually
6158 * copied by dev-replace process. We can avoid cloning IO here.
6160 if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6164 * duplicate the write operations while the dev replace
6165 * procedure is running. Since the copying of the old disk to
6166 * the new disk takes place at run time while the filesystem is
6167 * mounted writable, the regular write operations to the old
6168 * disk have to be duplicated to go to the new disk as well.
6170 * Note that device->missing is handled by the caller, and that
6171 * the write to the old disk is already set up in the stripes
6174 index_where_to_add = num_stripes;
6175 for (i = 0; i < num_stripes; i++) {
6176 if (bbio->stripes[i].dev->devid == srcdev_devid) {
6177 /* write to new disk, too */
6178 struct btrfs_bio_stripe *new =
6179 bbio->stripes + index_where_to_add;
6180 struct btrfs_bio_stripe *old =
6183 new->physical = old->physical;
6184 new->length = old->length;
6185 new->dev = dev_replace->tgtdev;
6186 bbio->tgtdev_map[i] = index_where_to_add;
6187 index_where_to_add++;
6192 num_stripes = index_where_to_add;
6193 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
6194 int index_srcdev = 0;
6196 u64 physical_of_found = 0;
6199 * During the dev-replace procedure, the target drive can also
6200 * be used to read data in case it is needed to repair a corrupt
6201 * block elsewhere. This is possible if the requested area is
6202 * left of the left cursor. In this area, the target drive is a
6203 * full copy of the source drive.
6205 for (i = 0; i < num_stripes; i++) {
6206 if (bbio->stripes[i].dev->devid == srcdev_devid) {
6208 * In case of DUP, in order to keep it simple,
6209 * only add the mirror with the lowest physical
6213 physical_of_found <=
6214 bbio->stripes[i].physical)
6218 physical_of_found = bbio->stripes[i].physical;
6222 struct btrfs_bio_stripe *tgtdev_stripe =
6223 bbio->stripes + num_stripes;
6225 tgtdev_stripe->physical = physical_of_found;
6226 tgtdev_stripe->length =
6227 bbio->stripes[index_srcdev].length;
6228 tgtdev_stripe->dev = dev_replace->tgtdev;
6229 bbio->tgtdev_map[index_srcdev] = num_stripes;
6236 *num_stripes_ret = num_stripes;
6237 *max_errors_ret = max_errors;
6238 bbio->num_tgtdevs = tgtdev_indexes;
6242 static bool need_full_stripe(enum btrfs_map_op op)
6244 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
6248 * Calculate the geometry of a particular (address, len) tuple. This
6249 * information is used to calculate how big a particular bio can get before it
6250 * straddles a stripe.
6252 * @fs_info: the filesystem
6253 * @em: mapping containing the logical extent
6254 * @op: type of operation - write or read
6255 * @logical: address that we want to figure out the geometry of
6256 * @io_geom: pointer used to return values
6258 * Returns < 0 in case a chunk for the given logical address cannot be found,
6259 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
6261 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, struct extent_map *em,
6262 enum btrfs_map_op op, u64 logical,
6263 struct btrfs_io_geometry *io_geom)
6265 struct map_lookup *map;
6271 u64 raid56_full_stripe_start = (u64)-1;
6274 ASSERT(op != BTRFS_MAP_DISCARD);
6276 map = em->map_lookup;
6277 /* Offset of this logical address in the chunk */
6278 offset = logical - em->start;
6279 /* Len of a stripe in a chunk */
6280 stripe_len = map->stripe_len;
6281 /* Stripe where this block falls in */
6282 stripe_nr = div64_u64(offset, stripe_len);
6283 /* Offset of stripe in the chunk */
6284 stripe_offset = stripe_nr * stripe_len;
6285 if (offset < stripe_offset) {
6287 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
6288 stripe_offset, offset, em->start, logical, stripe_len);
6292 /* stripe_offset is the offset of this block in its stripe */
6293 stripe_offset = offset - stripe_offset;
6294 data_stripes = nr_data_stripes(map);
6296 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6297 u64 max_len = stripe_len - stripe_offset;
6300 * In case of raid56, we need to know the stripe aligned start
6302 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6303 unsigned long full_stripe_len = stripe_len * data_stripes;
6304 raid56_full_stripe_start = offset;
6307 * Allow a write of a full stripe, but make sure we
6308 * don't allow straddling of stripes
6310 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6312 raid56_full_stripe_start *= full_stripe_len;
6315 * For writes to RAID[56], allow a full stripeset across
6316 * all disks. For other RAID types and for RAID[56]
6317 * reads, just allow a single stripe (on a single disk).
6319 if (op == BTRFS_MAP_WRITE) {
6320 max_len = stripe_len * data_stripes -
6321 (offset - raid56_full_stripe_start);
6324 len = min_t(u64, em->len - offset, max_len);
6326 len = em->len - offset;
6330 io_geom->offset = offset;
6331 io_geom->stripe_len = stripe_len;
6332 io_geom->stripe_nr = stripe_nr;
6333 io_geom->stripe_offset = stripe_offset;
6334 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6339 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6340 enum btrfs_map_op op,
6341 u64 logical, u64 *length,
6342 struct btrfs_bio **bbio_ret,
6343 int mirror_num, int need_raid_map)
6345 struct extent_map *em;
6346 struct map_lookup *map;
6356 int tgtdev_indexes = 0;
6357 struct btrfs_bio *bbio = NULL;
6358 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6359 int dev_replace_is_ongoing = 0;
6360 int num_alloc_stripes;
6361 int patch_the_first_stripe_for_dev_replace = 0;
6362 u64 physical_to_patch_in_first_stripe = 0;
6363 u64 raid56_full_stripe_start = (u64)-1;
6364 struct btrfs_io_geometry geom;
6367 ASSERT(op != BTRFS_MAP_DISCARD);
6369 em = btrfs_get_chunk_map(fs_info, logical, *length);
6370 ASSERT(!IS_ERR(em));
6372 ret = btrfs_get_io_geometry(fs_info, em, op, logical, &geom);
6376 map = em->map_lookup;
6379 stripe_len = geom.stripe_len;
6380 stripe_nr = geom.stripe_nr;
6381 stripe_offset = geom.stripe_offset;
6382 raid56_full_stripe_start = geom.raid56_stripe_offset;
6383 data_stripes = nr_data_stripes(map);
6385 down_read(&dev_replace->rwsem);
6386 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6388 * Hold the semaphore for read during the whole operation, write is
6389 * requested at commit time but must wait.
6391 if (!dev_replace_is_ongoing)
6392 up_read(&dev_replace->rwsem);
6394 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6395 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6396 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6397 dev_replace->srcdev->devid,
6399 &physical_to_patch_in_first_stripe);
6403 patch_the_first_stripe_for_dev_replace = 1;
6404 } else if (mirror_num > map->num_stripes) {
6410 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6411 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6413 if (!need_full_stripe(op))
6415 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6416 if (need_full_stripe(op))
6417 num_stripes = map->num_stripes;
6418 else if (mirror_num)
6419 stripe_index = mirror_num - 1;
6421 stripe_index = find_live_mirror(fs_info, map, 0,
6422 dev_replace_is_ongoing);
6423 mirror_num = stripe_index + 1;
6426 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6427 if (need_full_stripe(op)) {
6428 num_stripes = map->num_stripes;
6429 } else if (mirror_num) {
6430 stripe_index = mirror_num - 1;
6435 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6436 u32 factor = map->num_stripes / map->sub_stripes;
6438 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6439 stripe_index *= map->sub_stripes;
6441 if (need_full_stripe(op))
6442 num_stripes = map->sub_stripes;
6443 else if (mirror_num)
6444 stripe_index += mirror_num - 1;
6446 int old_stripe_index = stripe_index;
6447 stripe_index = find_live_mirror(fs_info, map,
6449 dev_replace_is_ongoing);
6450 mirror_num = stripe_index - old_stripe_index + 1;
6453 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6454 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6455 /* push stripe_nr back to the start of the full stripe */
6456 stripe_nr = div64_u64(raid56_full_stripe_start,
6457 stripe_len * data_stripes);
6459 /* RAID[56] write or recovery. Return all stripes */
6460 num_stripes = map->num_stripes;
6461 max_errors = nr_parity_stripes(map);
6463 *length = map->stripe_len;
6468 * Mirror #0 or #1 means the original data block.
6469 * Mirror #2 is RAID5 parity block.
6470 * Mirror #3 is RAID6 Q block.
6472 stripe_nr = div_u64_rem(stripe_nr,
6473 data_stripes, &stripe_index);
6475 stripe_index = data_stripes + mirror_num - 2;
6477 /* We distribute the parity blocks across stripes */
6478 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6480 if (!need_full_stripe(op) && mirror_num <= 1)
6485 * after this, stripe_nr is the number of stripes on this
6486 * device we have to walk to find the data, and stripe_index is
6487 * the number of our device in the stripe array
6489 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6491 mirror_num = stripe_index + 1;
6493 if (stripe_index >= map->num_stripes) {
6495 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6496 stripe_index, map->num_stripes);
6501 num_alloc_stripes = num_stripes;
6502 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6503 if (op == BTRFS_MAP_WRITE)
6504 num_alloc_stripes <<= 1;
6505 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6506 num_alloc_stripes++;
6507 tgtdev_indexes = num_stripes;
6510 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6516 for (i = 0; i < num_stripes; i++) {
6517 bbio->stripes[i].physical = map->stripes[stripe_index].physical +
6518 stripe_offset + stripe_nr * map->stripe_len;
6519 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
6523 /* build raid_map */
6524 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6525 (need_full_stripe(op) || mirror_num > 1)) {
6529 /* Work out the disk rotation on this stripe-set */
6530 div_u64_rem(stripe_nr, num_stripes, &rot);
6532 /* Fill in the logical address of each stripe */
6533 tmp = stripe_nr * data_stripes;
6534 for (i = 0; i < data_stripes; i++)
6535 bbio->raid_map[(i+rot) % num_stripes] =
6536 em->start + (tmp + i) * map->stripe_len;
6538 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6539 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6540 bbio->raid_map[(i+rot+1) % num_stripes] =
6543 sort_parity_stripes(bbio, num_stripes);
6546 if (need_full_stripe(op))
6547 max_errors = btrfs_chunk_max_errors(map);
6549 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6550 need_full_stripe(op)) {
6551 handle_ops_on_dev_replace(op, &bbio, dev_replace, logical,
6552 &num_stripes, &max_errors);
6556 bbio->map_type = map->type;
6557 bbio->num_stripes = num_stripes;
6558 bbio->max_errors = max_errors;
6559 bbio->mirror_num = mirror_num;
6562 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6563 * mirror_num == num_stripes + 1 && dev_replace target drive is
6564 * available as a mirror
6566 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6567 WARN_ON(num_stripes > 1);
6568 bbio->stripes[0].dev = dev_replace->tgtdev;
6569 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6570 bbio->mirror_num = map->num_stripes + 1;
6573 if (dev_replace_is_ongoing) {
6574 lockdep_assert_held(&dev_replace->rwsem);
6575 /* Unlock and let waiting writers proceed */
6576 up_read(&dev_replace->rwsem);
6578 free_extent_map(em);
6582 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6583 u64 logical, u64 *length,
6584 struct btrfs_bio **bbio_ret, int mirror_num)
6586 if (op == BTRFS_MAP_DISCARD)
6587 return __btrfs_map_block_for_discard(fs_info, logical,
6590 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6594 /* For Scrub/replace */
6595 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6596 u64 logical, u64 *length,
6597 struct btrfs_bio **bbio_ret)
6599 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6602 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6604 bio->bi_private = bbio->private;
6605 bio->bi_end_io = bbio->end_io;
6608 btrfs_put_bbio(bbio);
6611 static void btrfs_end_bio(struct bio *bio)
6613 struct btrfs_bio *bbio = bio->bi_private;
6614 int is_orig_bio = 0;
6616 if (bio->bi_status) {
6617 atomic_inc(&bbio->error);
6618 if (bio->bi_status == BLK_STS_IOERR ||
6619 bio->bi_status == BLK_STS_TARGET) {
6620 struct btrfs_device *dev = btrfs_io_bio(bio)->device;
6623 if (btrfs_op(bio) == BTRFS_MAP_WRITE)
6624 btrfs_dev_stat_inc_and_print(dev,
6625 BTRFS_DEV_STAT_WRITE_ERRS);
6626 else if (!(bio->bi_opf & REQ_RAHEAD))
6627 btrfs_dev_stat_inc_and_print(dev,
6628 BTRFS_DEV_STAT_READ_ERRS);
6629 if (bio->bi_opf & REQ_PREFLUSH)
6630 btrfs_dev_stat_inc_and_print(dev,
6631 BTRFS_DEV_STAT_FLUSH_ERRS);
6635 if (bio == bbio->orig_bio)
6638 btrfs_bio_counter_dec(bbio->fs_info);
6640 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6643 bio = bbio->orig_bio;
6646 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6647 /* only send an error to the higher layers if it is
6648 * beyond the tolerance of the btrfs bio
6650 if (atomic_read(&bbio->error) > bbio->max_errors) {
6651 bio->bi_status = BLK_STS_IOERR;
6654 * this bio is actually up to date, we didn't
6655 * go over the max number of errors
6657 bio->bi_status = BLK_STS_OK;
6660 btrfs_end_bbio(bbio, bio);
6661 } else if (!is_orig_bio) {
6666 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6667 u64 physical, struct btrfs_device *dev)
6669 struct btrfs_fs_info *fs_info = bbio->fs_info;
6671 bio->bi_private = bbio;
6672 btrfs_io_bio(bio)->device = dev;
6673 bio->bi_end_io = btrfs_end_bio;
6674 bio->bi_iter.bi_sector = physical >> 9;
6676 * For zone append writing, bi_sector must point the beginning of the
6679 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
6680 if (btrfs_dev_is_sequential(dev, physical)) {
6681 u64 zone_start = round_down(physical, fs_info->zone_size);
6683 bio->bi_iter.bi_sector = zone_start >> SECTOR_SHIFT;
6685 bio->bi_opf &= ~REQ_OP_ZONE_APPEND;
6686 bio->bi_opf |= REQ_OP_WRITE;
6689 btrfs_debug_in_rcu(fs_info,
6690 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6691 bio_op(bio), bio->bi_opf, bio->bi_iter.bi_sector,
6692 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6693 dev->devid, bio->bi_iter.bi_size);
6694 bio_set_dev(bio, dev->bdev);
6696 btrfs_bio_counter_inc_noblocked(fs_info);
6698 btrfsic_submit_bio(bio);
6701 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6703 atomic_inc(&bbio->error);
6704 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6705 /* Should be the original bio. */
6706 WARN_ON(bio != bbio->orig_bio);
6708 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6709 bio->bi_iter.bi_sector = logical >> 9;
6710 if (atomic_read(&bbio->error) > bbio->max_errors)
6711 bio->bi_status = BLK_STS_IOERR;
6713 bio->bi_status = BLK_STS_OK;
6714 btrfs_end_bbio(bbio, bio);
6718 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6721 struct btrfs_device *dev;
6722 struct bio *first_bio = bio;
6723 u64 logical = bio->bi_iter.bi_sector << 9;
6729 struct btrfs_bio *bbio = NULL;
6731 length = bio->bi_iter.bi_size;
6732 map_length = length;
6734 btrfs_bio_counter_inc_blocked(fs_info);
6735 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6736 &map_length, &bbio, mirror_num, 1);
6738 btrfs_bio_counter_dec(fs_info);
6739 return errno_to_blk_status(ret);
6742 total_devs = bbio->num_stripes;
6743 bbio->orig_bio = first_bio;
6744 bbio->private = first_bio->bi_private;
6745 bbio->end_io = first_bio->bi_end_io;
6746 bbio->fs_info = fs_info;
6747 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6749 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6750 ((btrfs_op(bio) == BTRFS_MAP_WRITE) || (mirror_num > 1))) {
6751 /* In this case, map_length has been set to the length of
6752 a single stripe; not the whole write */
6753 if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
6754 ret = raid56_parity_write(fs_info, bio, bbio,
6757 ret = raid56_parity_recover(fs_info, bio, bbio,
6758 map_length, mirror_num, 1);
6761 btrfs_bio_counter_dec(fs_info);
6762 return errno_to_blk_status(ret);
6765 if (map_length < length) {
6767 "mapping failed logical %llu bio len %llu len %llu",
6768 logical, length, map_length);
6772 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6773 dev = bbio->stripes[dev_nr].dev;
6774 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6776 (btrfs_op(first_bio) == BTRFS_MAP_WRITE &&
6777 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6778 bbio_error(bbio, first_bio, logical);
6782 if (dev_nr < total_devs - 1)
6783 bio = btrfs_bio_clone(first_bio);
6787 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical, dev);
6789 btrfs_bio_counter_dec(fs_info);
6794 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6797 * If devid and uuid are both specified, the match must be exact, otherwise
6798 * only devid is used.
6800 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6801 u64 devid, u8 *uuid, u8 *fsid)
6803 struct btrfs_device *device;
6804 struct btrfs_fs_devices *seed_devs;
6806 if (!fsid || !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6807 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6808 if (device->devid == devid &&
6809 (!uuid || memcmp(device->uuid, uuid,
6810 BTRFS_UUID_SIZE) == 0))
6815 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6817 !memcmp(seed_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6818 list_for_each_entry(device, &seed_devs->devices,
6820 if (device->devid == devid &&
6821 (!uuid || memcmp(device->uuid, uuid,
6822 BTRFS_UUID_SIZE) == 0))
6831 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6832 u64 devid, u8 *dev_uuid)
6834 struct btrfs_device *device;
6835 unsigned int nofs_flag;
6838 * We call this under the chunk_mutex, so we want to use NOFS for this
6839 * allocation, however we don't want to change btrfs_alloc_device() to
6840 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6843 nofs_flag = memalloc_nofs_save();
6844 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6845 memalloc_nofs_restore(nofs_flag);
6849 list_add(&device->dev_list, &fs_devices->devices);
6850 device->fs_devices = fs_devices;
6851 fs_devices->num_devices++;
6853 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6854 fs_devices->missing_devices++;
6860 * btrfs_alloc_device - allocate struct btrfs_device
6861 * @fs_info: used only for generating a new devid, can be NULL if
6862 * devid is provided (i.e. @devid != NULL).
6863 * @devid: a pointer to devid for this device. If NULL a new devid
6865 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6868 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6869 * on error. Returned struct is not linked onto any lists and must be
6870 * destroyed with btrfs_free_device.
6872 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6876 struct btrfs_device *dev;
6879 if (WARN_ON(!devid && !fs_info))
6880 return ERR_PTR(-EINVAL);
6882 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
6884 return ERR_PTR(-ENOMEM);
6887 * Preallocate a bio that's always going to be used for flushing device
6888 * barriers and matches the device lifespan
6890 dev->flush_bio = bio_kmalloc(GFP_KERNEL, 0);
6891 if (!dev->flush_bio) {
6893 return ERR_PTR(-ENOMEM);
6896 INIT_LIST_HEAD(&dev->dev_list);
6897 INIT_LIST_HEAD(&dev->dev_alloc_list);
6898 INIT_LIST_HEAD(&dev->post_commit_list);
6900 atomic_set(&dev->reada_in_flight, 0);
6901 atomic_set(&dev->dev_stats_ccnt, 0);
6902 btrfs_device_data_ordered_init(dev);
6903 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
6904 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
6905 extent_io_tree_init(fs_info, &dev->alloc_state,
6906 IO_TREE_DEVICE_ALLOC_STATE, NULL);
6913 ret = find_next_devid(fs_info, &tmp);
6915 btrfs_free_device(dev);
6916 return ERR_PTR(ret);
6922 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6924 generate_random_uuid(dev->uuid);
6929 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6930 u64 devid, u8 *uuid, bool error)
6933 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6936 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6940 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6942 const int data_stripes = calc_data_stripes(type, num_stripes);
6944 return div_u64(chunk_len, data_stripes);
6947 #if BITS_PER_LONG == 32
6949 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
6950 * can't be accessed on 32bit systems.
6952 * This function do mount time check to reject the fs if it already has
6953 * metadata chunk beyond that limit.
6955 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6956 u64 logical, u64 length, u64 type)
6958 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6961 if (logical + length < MAX_LFS_FILESIZE)
6964 btrfs_err_32bit_limit(fs_info);
6969 * This is to give early warning for any metadata chunk reaching
6970 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
6971 * Although we can still access the metadata, it's not going to be possible
6972 * once the limit is reached.
6974 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6975 u64 logical, u64 length, u64 type)
6977 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6980 if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6983 btrfs_warn_32bit_limit(fs_info);
6987 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6988 struct btrfs_chunk *chunk)
6990 struct btrfs_fs_info *fs_info = leaf->fs_info;
6991 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6992 struct map_lookup *map;
6993 struct extent_map *em;
6998 u8 uuid[BTRFS_UUID_SIZE];
7003 logical = key->offset;
7004 length = btrfs_chunk_length(leaf, chunk);
7005 type = btrfs_chunk_type(leaf, chunk);
7006 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
7008 #if BITS_PER_LONG == 32
7009 ret = check_32bit_meta_chunk(fs_info, logical, length, type);
7012 warn_32bit_meta_chunk(fs_info, logical, length, type);
7016 * Only need to verify chunk item if we're reading from sys chunk array,
7017 * as chunk item in tree block is already verified by tree-checker.
7019 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
7020 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
7025 read_lock(&map_tree->lock);
7026 em = lookup_extent_mapping(map_tree, logical, 1);
7027 read_unlock(&map_tree->lock);
7029 /* already mapped? */
7030 if (em && em->start <= logical && em->start + em->len > logical) {
7031 free_extent_map(em);
7034 free_extent_map(em);
7037 em = alloc_extent_map();
7040 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
7042 free_extent_map(em);
7046 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
7047 em->map_lookup = map;
7048 em->start = logical;
7051 em->block_start = 0;
7052 em->block_len = em->len;
7054 map->num_stripes = num_stripes;
7055 map->io_width = btrfs_chunk_io_width(leaf, chunk);
7056 map->io_align = btrfs_chunk_io_align(leaf, chunk);
7057 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
7059 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
7060 map->verified_stripes = 0;
7061 em->orig_block_len = calc_stripe_length(type, em->len,
7063 for (i = 0; i < num_stripes; i++) {
7064 map->stripes[i].physical =
7065 btrfs_stripe_offset_nr(leaf, chunk, i);
7066 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
7067 read_extent_buffer(leaf, uuid, (unsigned long)
7068 btrfs_stripe_dev_uuid_nr(chunk, i),
7070 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
7072 if (!map->stripes[i].dev &&
7073 !btrfs_test_opt(fs_info, DEGRADED)) {
7074 free_extent_map(em);
7075 btrfs_report_missing_device(fs_info, devid, uuid, true);
7078 if (!map->stripes[i].dev) {
7079 map->stripes[i].dev =
7080 add_missing_dev(fs_info->fs_devices, devid,
7082 if (IS_ERR(map->stripes[i].dev)) {
7083 free_extent_map(em);
7085 "failed to init missing dev %llu: %ld",
7086 devid, PTR_ERR(map->stripes[i].dev));
7087 return PTR_ERR(map->stripes[i].dev);
7089 btrfs_report_missing_device(fs_info, devid, uuid, false);
7091 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
7092 &(map->stripes[i].dev->dev_state));
7096 write_lock(&map_tree->lock);
7097 ret = add_extent_mapping(map_tree, em, 0);
7098 write_unlock(&map_tree->lock);
7101 "failed to add chunk map, start=%llu len=%llu: %d",
7102 em->start, em->len, ret);
7104 free_extent_map(em);
7109 static void fill_device_from_item(struct extent_buffer *leaf,
7110 struct btrfs_dev_item *dev_item,
7111 struct btrfs_device *device)
7115 device->devid = btrfs_device_id(leaf, dev_item);
7116 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7117 device->total_bytes = device->disk_total_bytes;
7118 device->commit_total_bytes = device->disk_total_bytes;
7119 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
7120 device->commit_bytes_used = device->bytes_used;
7121 device->type = btrfs_device_type(leaf, dev_item);
7122 device->io_align = btrfs_device_io_align(leaf, dev_item);
7123 device->io_width = btrfs_device_io_width(leaf, dev_item);
7124 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
7125 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
7126 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
7128 ptr = btrfs_device_uuid(dev_item);
7129 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
7132 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
7135 struct btrfs_fs_devices *fs_devices;
7138 lockdep_assert_held(&uuid_mutex);
7141 /* This will match only for multi-device seed fs */
7142 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
7143 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7147 fs_devices = find_fsid(fsid, NULL);
7149 if (!btrfs_test_opt(fs_info, DEGRADED))
7150 return ERR_PTR(-ENOENT);
7152 fs_devices = alloc_fs_devices(fsid, NULL);
7153 if (IS_ERR(fs_devices))
7156 fs_devices->seeding = true;
7157 fs_devices->opened = 1;
7162 * Upon first call for a seed fs fsid, just create a private copy of the
7163 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7165 fs_devices = clone_fs_devices(fs_devices);
7166 if (IS_ERR(fs_devices))
7169 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
7171 free_fs_devices(fs_devices);
7172 return ERR_PTR(ret);
7175 if (!fs_devices->seeding) {
7176 close_fs_devices(fs_devices);
7177 free_fs_devices(fs_devices);
7178 return ERR_PTR(-EINVAL);
7181 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7186 static int read_one_dev(struct extent_buffer *leaf,
7187 struct btrfs_dev_item *dev_item)
7189 struct btrfs_fs_info *fs_info = leaf->fs_info;
7190 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7191 struct btrfs_device *device;
7194 u8 fs_uuid[BTRFS_FSID_SIZE];
7195 u8 dev_uuid[BTRFS_UUID_SIZE];
7197 devid = btrfs_device_id(leaf, dev_item);
7198 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7200 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7203 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7204 fs_devices = open_seed_devices(fs_info, fs_uuid);
7205 if (IS_ERR(fs_devices))
7206 return PTR_ERR(fs_devices);
7209 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
7212 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7213 btrfs_report_missing_device(fs_info, devid,
7218 device = add_missing_dev(fs_devices, devid, dev_uuid);
7219 if (IS_ERR(device)) {
7221 "failed to add missing dev %llu: %ld",
7222 devid, PTR_ERR(device));
7223 return PTR_ERR(device);
7225 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7227 if (!device->bdev) {
7228 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7229 btrfs_report_missing_device(fs_info,
7230 devid, dev_uuid, true);
7233 btrfs_report_missing_device(fs_info, devid,
7237 if (!device->bdev &&
7238 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7240 * this happens when a device that was properly setup
7241 * in the device info lists suddenly goes bad.
7242 * device->bdev is NULL, and so we have to set
7243 * device->missing to one here
7245 device->fs_devices->missing_devices++;
7246 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7249 /* Move the device to its own fs_devices */
7250 if (device->fs_devices != fs_devices) {
7251 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7252 &device->dev_state));
7254 list_move(&device->dev_list, &fs_devices->devices);
7255 device->fs_devices->num_devices--;
7256 fs_devices->num_devices++;
7258 device->fs_devices->missing_devices--;
7259 fs_devices->missing_devices++;
7261 device->fs_devices = fs_devices;
7265 if (device->fs_devices != fs_info->fs_devices) {
7266 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7267 if (device->generation !=
7268 btrfs_device_generation(leaf, dev_item))
7272 fill_device_from_item(leaf, dev_item, device);
7274 u64 max_total_bytes = i_size_read(device->bdev->bd_inode);
7276 if (device->total_bytes > max_total_bytes) {
7278 "device total_bytes should be at most %llu but found %llu",
7279 max_total_bytes, device->total_bytes);
7283 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7284 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7285 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7286 device->fs_devices->total_rw_bytes += device->total_bytes;
7287 atomic64_add(device->total_bytes - device->bytes_used,
7288 &fs_info->free_chunk_space);
7294 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7296 struct btrfs_root *root = fs_info->tree_root;
7297 struct btrfs_super_block *super_copy = fs_info->super_copy;
7298 struct extent_buffer *sb;
7299 struct btrfs_disk_key *disk_key;
7300 struct btrfs_chunk *chunk;
7302 unsigned long sb_array_offset;
7309 struct btrfs_key key;
7311 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7313 * This will create extent buffer of nodesize, superblock size is
7314 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7315 * overallocate but we can keep it as-is, only the first page is used.
7317 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET,
7318 root->root_key.objectid, 0);
7321 set_extent_buffer_uptodate(sb);
7323 * The sb extent buffer is artificial and just used to read the system array.
7324 * set_extent_buffer_uptodate() call does not properly mark all it's
7325 * pages up-to-date when the page is larger: extent does not cover the
7326 * whole page and consequently check_page_uptodate does not find all
7327 * the page's extents up-to-date (the hole beyond sb),
7328 * write_extent_buffer then triggers a WARN_ON.
7330 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7331 * but sb spans only this function. Add an explicit SetPageUptodate call
7332 * to silence the warning eg. on PowerPC 64.
7334 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
7335 SetPageUptodate(sb->pages[0]);
7337 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7338 array_size = btrfs_super_sys_array_size(super_copy);
7340 array_ptr = super_copy->sys_chunk_array;
7341 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7344 while (cur_offset < array_size) {
7345 disk_key = (struct btrfs_disk_key *)array_ptr;
7346 len = sizeof(*disk_key);
7347 if (cur_offset + len > array_size)
7348 goto out_short_read;
7350 btrfs_disk_key_to_cpu(&key, disk_key);
7353 sb_array_offset += len;
7356 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
7358 "unexpected item type %u in sys_array at offset %u",
7359 (u32)key.type, cur_offset);
7364 chunk = (struct btrfs_chunk *)sb_array_offset;
7366 * At least one btrfs_chunk with one stripe must be present,
7367 * exact stripe count check comes afterwards
7369 len = btrfs_chunk_item_size(1);
7370 if (cur_offset + len > array_size)
7371 goto out_short_read;
7373 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7376 "invalid number of stripes %u in sys_array at offset %u",
7377 num_stripes, cur_offset);
7382 type = btrfs_chunk_type(sb, chunk);
7383 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7385 "invalid chunk type %llu in sys_array at offset %u",
7391 len = btrfs_chunk_item_size(num_stripes);
7392 if (cur_offset + len > array_size)
7393 goto out_short_read;
7395 ret = read_one_chunk(&key, sb, chunk);
7400 sb_array_offset += len;
7403 clear_extent_buffer_uptodate(sb);
7404 free_extent_buffer_stale(sb);
7408 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7410 clear_extent_buffer_uptodate(sb);
7411 free_extent_buffer_stale(sb);
7416 * Check if all chunks in the fs are OK for read-write degraded mount
7418 * If the @failing_dev is specified, it's accounted as missing.
7420 * Return true if all chunks meet the minimal RW mount requirements.
7421 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7423 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7424 struct btrfs_device *failing_dev)
7426 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7427 struct extent_map *em;
7431 read_lock(&map_tree->lock);
7432 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7433 read_unlock(&map_tree->lock);
7434 /* No chunk at all? Return false anyway */
7440 struct map_lookup *map;
7445 map = em->map_lookup;
7447 btrfs_get_num_tolerated_disk_barrier_failures(
7449 for (i = 0; i < map->num_stripes; i++) {
7450 struct btrfs_device *dev = map->stripes[i].dev;
7452 if (!dev || !dev->bdev ||
7453 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7454 dev->last_flush_error)
7456 else if (failing_dev && failing_dev == dev)
7459 if (missing > max_tolerated) {
7462 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7463 em->start, missing, max_tolerated);
7464 free_extent_map(em);
7468 next_start = extent_map_end(em);
7469 free_extent_map(em);
7471 read_lock(&map_tree->lock);
7472 em = lookup_extent_mapping(map_tree, next_start,
7473 (u64)(-1) - next_start);
7474 read_unlock(&map_tree->lock);
7480 static void readahead_tree_node_children(struct extent_buffer *node)
7483 const int nr_items = btrfs_header_nritems(node);
7485 for (i = 0; i < nr_items; i++)
7486 btrfs_readahead_node_child(node, i);
7489 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7491 struct btrfs_root *root = fs_info->chunk_root;
7492 struct btrfs_path *path;
7493 struct extent_buffer *leaf;
7494 struct btrfs_key key;
7495 struct btrfs_key found_key;
7499 u64 last_ra_node = 0;
7501 path = btrfs_alloc_path();
7506 * uuid_mutex is needed only if we are mounting a sprout FS
7507 * otherwise we don't need it.
7509 mutex_lock(&uuid_mutex);
7512 * It is possible for mount and umount to race in such a way that
7513 * we execute this code path, but open_fs_devices failed to clear
7514 * total_rw_bytes. We certainly want it cleared before reading the
7515 * device items, so clear it here.
7517 fs_info->fs_devices->total_rw_bytes = 0;
7520 * Lockdep complains about possible circular locking dependency between
7521 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7522 * used for freeze procection of a fs (struct super_block.s_writers),
7523 * which we take when starting a transaction, and extent buffers of the
7524 * chunk tree if we call read_one_dev() while holding a lock on an
7525 * extent buffer of the chunk tree. Since we are mounting the filesystem
7526 * and at this point there can't be any concurrent task modifying the
7527 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7529 ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
7530 path->skip_locking = 1;
7533 * Read all device items, and then all the chunk items. All
7534 * device items are found before any chunk item (their object id
7535 * is smaller than the lowest possible object id for a chunk
7536 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7538 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7541 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7545 struct extent_buffer *node;
7547 leaf = path->nodes[0];
7548 slot = path->slots[0];
7549 if (slot >= btrfs_header_nritems(leaf)) {
7550 ret = btrfs_next_leaf(root, path);
7557 node = path->nodes[1];
7559 if (last_ra_node != node->start) {
7560 readahead_tree_node_children(node);
7561 last_ra_node = node->start;
7564 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7565 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7566 struct btrfs_dev_item *dev_item;
7567 dev_item = btrfs_item_ptr(leaf, slot,
7568 struct btrfs_dev_item);
7569 ret = read_one_dev(leaf, dev_item);
7573 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7574 struct btrfs_chunk *chunk;
7577 * We are only called at mount time, so no need to take
7578 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7579 * we always lock first fs_info->chunk_mutex before
7580 * acquiring any locks on the chunk tree. This is a
7581 * requirement for chunk allocation, see the comment on
7582 * top of btrfs_chunk_alloc() for details.
7584 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7585 ret = read_one_chunk(&found_key, leaf, chunk);
7593 * After loading chunk tree, we've got all device information,
7594 * do another round of validation checks.
7596 if (total_dev != fs_info->fs_devices->total_devices) {
7598 "super_num_devices %llu mismatch with num_devices %llu found here",
7599 btrfs_super_num_devices(fs_info->super_copy),
7604 if (btrfs_super_total_bytes(fs_info->super_copy) <
7605 fs_info->fs_devices->total_rw_bytes) {
7607 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7608 btrfs_super_total_bytes(fs_info->super_copy),
7609 fs_info->fs_devices->total_rw_bytes);
7615 mutex_unlock(&uuid_mutex);
7617 btrfs_free_path(path);
7621 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7623 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7624 struct btrfs_device *device;
7626 fs_devices->fs_info = fs_info;
7628 mutex_lock(&fs_devices->device_list_mutex);
7629 list_for_each_entry(device, &fs_devices->devices, dev_list)
7630 device->fs_info = fs_info;
7632 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7633 list_for_each_entry(device, &seed_devs->devices, dev_list)
7634 device->fs_info = fs_info;
7636 seed_devs->fs_info = fs_info;
7638 mutex_unlock(&fs_devices->device_list_mutex);
7641 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7642 const struct btrfs_dev_stats_item *ptr,
7647 read_extent_buffer(eb, &val,
7648 offsetof(struct btrfs_dev_stats_item, values) +
7649 ((unsigned long)ptr) + (index * sizeof(u64)),
7654 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7655 struct btrfs_dev_stats_item *ptr,
7658 write_extent_buffer(eb, &val,
7659 offsetof(struct btrfs_dev_stats_item, values) +
7660 ((unsigned long)ptr) + (index * sizeof(u64)),
7664 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7665 struct btrfs_path *path)
7667 struct btrfs_dev_stats_item *ptr;
7668 struct extent_buffer *eb;
7669 struct btrfs_key key;
7673 if (!device->fs_info->dev_root)
7676 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7677 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7678 key.offset = device->devid;
7679 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7681 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7682 btrfs_dev_stat_set(device, i, 0);
7683 device->dev_stats_valid = 1;
7684 btrfs_release_path(path);
7685 return ret < 0 ? ret : 0;
7687 slot = path->slots[0];
7688 eb = path->nodes[0];
7689 item_size = btrfs_item_size_nr(eb, slot);
7691 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7693 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7694 if (item_size >= (1 + i) * sizeof(__le64))
7695 btrfs_dev_stat_set(device, i,
7696 btrfs_dev_stats_value(eb, ptr, i));
7698 btrfs_dev_stat_set(device, i, 0);
7701 device->dev_stats_valid = 1;
7702 btrfs_dev_stat_print_on_load(device);
7703 btrfs_release_path(path);
7708 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7710 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7711 struct btrfs_device *device;
7712 struct btrfs_path *path = NULL;
7715 path = btrfs_alloc_path();
7719 mutex_lock(&fs_devices->device_list_mutex);
7720 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7721 ret = btrfs_device_init_dev_stats(device, path);
7725 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7726 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7727 ret = btrfs_device_init_dev_stats(device, path);
7733 mutex_unlock(&fs_devices->device_list_mutex);
7735 btrfs_free_path(path);
7739 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7740 struct btrfs_device *device)
7742 struct btrfs_fs_info *fs_info = trans->fs_info;
7743 struct btrfs_root *dev_root = fs_info->dev_root;
7744 struct btrfs_path *path;
7745 struct btrfs_key key;
7746 struct extent_buffer *eb;
7747 struct btrfs_dev_stats_item *ptr;
7751 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7752 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7753 key.offset = device->devid;
7755 path = btrfs_alloc_path();
7758 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7760 btrfs_warn_in_rcu(fs_info,
7761 "error %d while searching for dev_stats item for device %s",
7762 ret, rcu_str_deref(device->name));
7767 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7768 /* need to delete old one and insert a new one */
7769 ret = btrfs_del_item(trans, dev_root, path);
7771 btrfs_warn_in_rcu(fs_info,
7772 "delete too small dev_stats item for device %s failed %d",
7773 rcu_str_deref(device->name), ret);
7780 /* need to insert a new item */
7781 btrfs_release_path(path);
7782 ret = btrfs_insert_empty_item(trans, dev_root, path,
7783 &key, sizeof(*ptr));
7785 btrfs_warn_in_rcu(fs_info,
7786 "insert dev_stats item for device %s failed %d",
7787 rcu_str_deref(device->name), ret);
7792 eb = path->nodes[0];
7793 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7794 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7795 btrfs_set_dev_stats_value(eb, ptr, i,
7796 btrfs_dev_stat_read(device, i));
7797 btrfs_mark_buffer_dirty(eb);
7800 btrfs_free_path(path);
7805 * called from commit_transaction. Writes all changed device stats to disk.
7807 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7809 struct btrfs_fs_info *fs_info = trans->fs_info;
7810 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7811 struct btrfs_device *device;
7815 mutex_lock(&fs_devices->device_list_mutex);
7816 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7817 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7818 if (!device->dev_stats_valid || stats_cnt == 0)
7823 * There is a LOAD-LOAD control dependency between the value of
7824 * dev_stats_ccnt and updating the on-disk values which requires
7825 * reading the in-memory counters. Such control dependencies
7826 * require explicit read memory barriers.
7828 * This memory barriers pairs with smp_mb__before_atomic in
7829 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7830 * barrier implied by atomic_xchg in
7831 * btrfs_dev_stats_read_and_reset
7835 ret = update_dev_stat_item(trans, device);
7837 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7839 mutex_unlock(&fs_devices->device_list_mutex);
7844 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7846 btrfs_dev_stat_inc(dev, index);
7847 btrfs_dev_stat_print_on_error(dev);
7850 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7852 if (!dev->dev_stats_valid)
7854 btrfs_err_rl_in_rcu(dev->fs_info,
7855 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7856 rcu_str_deref(dev->name),
7857 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7858 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7859 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7860 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7861 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7864 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7868 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7869 if (btrfs_dev_stat_read(dev, i) != 0)
7871 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7872 return; /* all values == 0, suppress message */
7874 btrfs_info_in_rcu(dev->fs_info,
7875 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7876 rcu_str_deref(dev->name),
7877 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7878 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7879 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7880 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7881 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7884 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7885 struct btrfs_ioctl_get_dev_stats *stats)
7887 struct btrfs_device *dev;
7888 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7891 mutex_lock(&fs_devices->device_list_mutex);
7892 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL);
7893 mutex_unlock(&fs_devices->device_list_mutex);
7896 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7898 } else if (!dev->dev_stats_valid) {
7899 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7901 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7902 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7903 if (stats->nr_items > i)
7905 btrfs_dev_stat_read_and_reset(dev, i);
7907 btrfs_dev_stat_set(dev, i, 0);
7909 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7910 current->comm, task_pid_nr(current));
7912 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7913 if (stats->nr_items > i)
7914 stats->values[i] = btrfs_dev_stat_read(dev, i);
7916 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7917 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7922 * Update the size and bytes used for each device where it changed. This is
7923 * delayed since we would otherwise get errors while writing out the
7926 * Must be invoked during transaction commit.
7928 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7930 struct btrfs_device *curr, *next;
7932 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7934 if (list_empty(&trans->dev_update_list))
7938 * We don't need the device_list_mutex here. This list is owned by the
7939 * transaction and the transaction must complete before the device is
7942 mutex_lock(&trans->fs_info->chunk_mutex);
7943 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7945 list_del_init(&curr->post_commit_list);
7946 curr->commit_total_bytes = curr->disk_total_bytes;
7947 curr->commit_bytes_used = curr->bytes_used;
7949 mutex_unlock(&trans->fs_info->chunk_mutex);
7953 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7955 int btrfs_bg_type_to_factor(u64 flags)
7957 const int index = btrfs_bg_flags_to_raid_index(flags);
7959 return btrfs_raid_array[index].ncopies;
7964 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7965 u64 chunk_offset, u64 devid,
7966 u64 physical_offset, u64 physical_len)
7968 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7969 struct extent_map *em;
7970 struct map_lookup *map;
7971 struct btrfs_device *dev;
7977 read_lock(&em_tree->lock);
7978 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7979 read_unlock(&em_tree->lock);
7983 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7984 physical_offset, devid);
7989 map = em->map_lookup;
7990 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7991 if (physical_len != stripe_len) {
7993 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7994 physical_offset, devid, em->start, physical_len,
8000 for (i = 0; i < map->num_stripes; i++) {
8001 if (map->stripes[i].dev->devid == devid &&
8002 map->stripes[i].physical == physical_offset) {
8004 if (map->verified_stripes >= map->num_stripes) {
8006 "too many dev extents for chunk %llu found",
8011 map->verified_stripes++;
8017 "dev extent physical offset %llu devid %llu has no corresponding chunk",
8018 physical_offset, devid);
8022 /* Make sure no dev extent is beyond device boundary */
8023 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL);
8025 btrfs_err(fs_info, "failed to find devid %llu", devid);
8030 if (physical_offset + physical_len > dev->disk_total_bytes) {
8032 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
8033 devid, physical_offset, physical_len,
8034 dev->disk_total_bytes);
8039 if (dev->zone_info) {
8040 u64 zone_size = dev->zone_info->zone_size;
8042 if (!IS_ALIGNED(physical_offset, zone_size) ||
8043 !IS_ALIGNED(physical_len, zone_size)) {
8045 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
8046 devid, physical_offset, physical_len);
8053 free_extent_map(em);
8057 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
8059 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
8060 struct extent_map *em;
8061 struct rb_node *node;
8064 read_lock(&em_tree->lock);
8065 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
8066 em = rb_entry(node, struct extent_map, rb_node);
8067 if (em->map_lookup->num_stripes !=
8068 em->map_lookup->verified_stripes) {
8070 "chunk %llu has missing dev extent, have %d expect %d",
8071 em->start, em->map_lookup->verified_stripes,
8072 em->map_lookup->num_stripes);
8078 read_unlock(&em_tree->lock);
8083 * Ensure that all dev extents are mapped to correct chunk, otherwise
8084 * later chunk allocation/free would cause unexpected behavior.
8086 * NOTE: This will iterate through the whole device tree, which should be of
8087 * the same size level as the chunk tree. This slightly increases mount time.
8089 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
8091 struct btrfs_path *path;
8092 struct btrfs_root *root = fs_info->dev_root;
8093 struct btrfs_key key;
8095 u64 prev_dev_ext_end = 0;
8099 * We don't have a dev_root because we mounted with ignorebadroots and
8100 * failed to load the root, so we want to skip the verification in this
8103 * However if the dev root is fine, but the tree itself is corrupted
8104 * we'd still fail to mount. This verification is only to make sure
8105 * writes can happen safely, so instead just bypass this check
8106 * completely in the case of IGNOREBADROOTS.
8108 if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
8112 key.type = BTRFS_DEV_EXTENT_KEY;
8115 path = btrfs_alloc_path();
8119 path->reada = READA_FORWARD;
8120 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8124 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8125 ret = btrfs_next_leaf(root, path);
8128 /* No dev extents at all? Not good */
8135 struct extent_buffer *leaf = path->nodes[0];
8136 struct btrfs_dev_extent *dext;
8137 int slot = path->slots[0];
8139 u64 physical_offset;
8143 btrfs_item_key_to_cpu(leaf, &key, slot);
8144 if (key.type != BTRFS_DEV_EXTENT_KEY)
8146 devid = key.objectid;
8147 physical_offset = key.offset;
8149 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
8150 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
8151 physical_len = btrfs_dev_extent_length(leaf, dext);
8153 /* Check if this dev extent overlaps with the previous one */
8154 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
8156 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8157 devid, physical_offset, prev_dev_ext_end);
8162 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8163 physical_offset, physical_len);
8167 prev_dev_ext_end = physical_offset + physical_len;
8169 ret = btrfs_next_item(root, path);
8178 /* Ensure all chunks have corresponding dev extents */
8179 ret = verify_chunk_dev_extent_mapping(fs_info);
8181 btrfs_free_path(path);
8186 * Check whether the given block group or device is pinned by any inode being
8187 * used as a swapfile.
8189 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8191 struct btrfs_swapfile_pin *sp;
8192 struct rb_node *node;
8194 spin_lock(&fs_info->swapfile_pins_lock);
8195 node = fs_info->swapfile_pins.rb_node;
8197 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8199 node = node->rb_left;
8200 else if (ptr > sp->ptr)
8201 node = node->rb_right;
8205 spin_unlock(&fs_info->swapfile_pins_lock);
8206 return node != NULL;
8209 static int relocating_repair_kthread(void *data)
8211 struct btrfs_block_group *cache = (struct btrfs_block_group *)data;
8212 struct btrfs_fs_info *fs_info = cache->fs_info;
8216 target = cache->start;
8217 btrfs_put_block_group(cache);
8219 sb_start_write(fs_info->sb);
8220 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8222 "zoned: skip relocating block group %llu to repair: EBUSY",
8224 sb_end_write(fs_info->sb);
8228 mutex_lock(&fs_info->reclaim_bgs_lock);
8230 /* Ensure block group still exists */
8231 cache = btrfs_lookup_block_group(fs_info, target);
8235 if (!cache->relocating_repair)
8238 ret = btrfs_may_alloc_data_chunk(fs_info, target);
8243 "zoned: relocating block group %llu to repair IO failure",
8245 ret = btrfs_relocate_chunk(fs_info, target);
8249 btrfs_put_block_group(cache);
8250 mutex_unlock(&fs_info->reclaim_bgs_lock);
8251 btrfs_exclop_finish(fs_info);
8252 sb_end_write(fs_info->sb);
8257 int btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8259 struct btrfs_block_group *cache;
8261 /* Do not attempt to repair in degraded state */
8262 if (btrfs_test_opt(fs_info, DEGRADED))
8265 cache = btrfs_lookup_block_group(fs_info, logical);
8269 spin_lock(&cache->lock);
8270 if (cache->relocating_repair) {
8271 spin_unlock(&cache->lock);
8272 btrfs_put_block_group(cache);
8275 cache->relocating_repair = 1;
8276 spin_unlock(&cache->lock);
8278 kthread_run(relocating_repair_kthread, cache,
8279 "btrfs-relocating-repair");