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 sb_start_write(fs_info->sb);
4393 mutex_lock(&fs_info->balance_mutex);
4394 if (fs_info->balance_ctl)
4395 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4396 mutex_unlock(&fs_info->balance_mutex);
4397 sb_end_write(fs_info->sb);
4402 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4404 struct task_struct *tsk;
4406 mutex_lock(&fs_info->balance_mutex);
4407 if (!fs_info->balance_ctl) {
4408 mutex_unlock(&fs_info->balance_mutex);
4411 mutex_unlock(&fs_info->balance_mutex);
4413 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4414 btrfs_info(fs_info, "balance: resume skipped");
4419 * A ro->rw remount sequence should continue with the paused balance
4420 * regardless of who pauses it, system or the user as of now, so set
4423 spin_lock(&fs_info->balance_lock);
4424 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4425 spin_unlock(&fs_info->balance_lock);
4427 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4428 return PTR_ERR_OR_ZERO(tsk);
4431 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4433 struct btrfs_balance_control *bctl;
4434 struct btrfs_balance_item *item;
4435 struct btrfs_disk_balance_args disk_bargs;
4436 struct btrfs_path *path;
4437 struct extent_buffer *leaf;
4438 struct btrfs_key key;
4441 path = btrfs_alloc_path();
4445 key.objectid = BTRFS_BALANCE_OBJECTID;
4446 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4449 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4452 if (ret > 0) { /* ret = -ENOENT; */
4457 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4463 leaf = path->nodes[0];
4464 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4466 bctl->flags = btrfs_balance_flags(leaf, item);
4467 bctl->flags |= BTRFS_BALANCE_RESUME;
4469 btrfs_balance_data(leaf, item, &disk_bargs);
4470 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4471 btrfs_balance_meta(leaf, item, &disk_bargs);
4472 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4473 btrfs_balance_sys(leaf, item, &disk_bargs);
4474 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4477 * This should never happen, as the paused balance state is recovered
4478 * during mount without any chance of other exclusive ops to collide.
4480 * This gives the exclusive op status to balance and keeps in paused
4481 * state until user intervention (cancel or umount). If the ownership
4482 * cannot be assigned, show a message but do not fail. The balance
4483 * is in a paused state and must have fs_info::balance_ctl properly
4486 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
4488 "balance: cannot set exclusive op status, resume manually");
4490 btrfs_release_path(path);
4492 mutex_lock(&fs_info->balance_mutex);
4493 BUG_ON(fs_info->balance_ctl);
4494 spin_lock(&fs_info->balance_lock);
4495 fs_info->balance_ctl = bctl;
4496 spin_unlock(&fs_info->balance_lock);
4497 mutex_unlock(&fs_info->balance_mutex);
4499 btrfs_free_path(path);
4503 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4507 mutex_lock(&fs_info->balance_mutex);
4508 if (!fs_info->balance_ctl) {
4509 mutex_unlock(&fs_info->balance_mutex);
4513 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4514 atomic_inc(&fs_info->balance_pause_req);
4515 mutex_unlock(&fs_info->balance_mutex);
4517 wait_event(fs_info->balance_wait_q,
4518 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4520 mutex_lock(&fs_info->balance_mutex);
4521 /* we are good with balance_ctl ripped off from under us */
4522 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4523 atomic_dec(&fs_info->balance_pause_req);
4528 mutex_unlock(&fs_info->balance_mutex);
4532 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4534 mutex_lock(&fs_info->balance_mutex);
4535 if (!fs_info->balance_ctl) {
4536 mutex_unlock(&fs_info->balance_mutex);
4541 * A paused balance with the item stored on disk can be resumed at
4542 * mount time if the mount is read-write. Otherwise it's still paused
4543 * and we must not allow cancelling as it deletes the item.
4545 if (sb_rdonly(fs_info->sb)) {
4546 mutex_unlock(&fs_info->balance_mutex);
4550 atomic_inc(&fs_info->balance_cancel_req);
4552 * if we are running just wait and return, balance item is
4553 * deleted in btrfs_balance in this case
4555 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4556 mutex_unlock(&fs_info->balance_mutex);
4557 wait_event(fs_info->balance_wait_q,
4558 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4559 mutex_lock(&fs_info->balance_mutex);
4561 mutex_unlock(&fs_info->balance_mutex);
4563 * Lock released to allow other waiters to continue, we'll
4564 * reexamine the status again.
4566 mutex_lock(&fs_info->balance_mutex);
4568 if (fs_info->balance_ctl) {
4569 reset_balance_state(fs_info);
4570 btrfs_exclop_finish(fs_info);
4571 btrfs_info(fs_info, "balance: canceled");
4575 BUG_ON(fs_info->balance_ctl ||
4576 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4577 atomic_dec(&fs_info->balance_cancel_req);
4578 mutex_unlock(&fs_info->balance_mutex);
4582 int btrfs_uuid_scan_kthread(void *data)
4584 struct btrfs_fs_info *fs_info = data;
4585 struct btrfs_root *root = fs_info->tree_root;
4586 struct btrfs_key key;
4587 struct btrfs_path *path = NULL;
4589 struct extent_buffer *eb;
4591 struct btrfs_root_item root_item;
4593 struct btrfs_trans_handle *trans = NULL;
4594 bool closing = false;
4596 path = btrfs_alloc_path();
4603 key.type = BTRFS_ROOT_ITEM_KEY;
4607 if (btrfs_fs_closing(fs_info)) {
4611 ret = btrfs_search_forward(root, &key, path,
4612 BTRFS_OLDEST_GENERATION);
4619 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4620 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4621 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4622 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4625 eb = path->nodes[0];
4626 slot = path->slots[0];
4627 item_size = btrfs_item_size_nr(eb, slot);
4628 if (item_size < sizeof(root_item))
4631 read_extent_buffer(eb, &root_item,
4632 btrfs_item_ptr_offset(eb, slot),
4633 (int)sizeof(root_item));
4634 if (btrfs_root_refs(&root_item) == 0)
4637 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4638 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4642 btrfs_release_path(path);
4644 * 1 - subvol uuid item
4645 * 1 - received_subvol uuid item
4647 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4648 if (IS_ERR(trans)) {
4649 ret = PTR_ERR(trans);
4657 btrfs_release_path(path);
4658 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4659 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4660 BTRFS_UUID_KEY_SUBVOL,
4663 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4669 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4670 ret = btrfs_uuid_tree_add(trans,
4671 root_item.received_uuid,
4672 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4675 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4682 btrfs_release_path(path);
4684 ret = btrfs_end_transaction(trans);
4690 if (key.offset < (u64)-1) {
4692 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4694 key.type = BTRFS_ROOT_ITEM_KEY;
4695 } else if (key.objectid < (u64)-1) {
4697 key.type = BTRFS_ROOT_ITEM_KEY;
4706 btrfs_free_path(path);
4707 if (trans && !IS_ERR(trans))
4708 btrfs_end_transaction(trans);
4710 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4712 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4713 up(&fs_info->uuid_tree_rescan_sem);
4717 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4719 struct btrfs_trans_handle *trans;
4720 struct btrfs_root *tree_root = fs_info->tree_root;
4721 struct btrfs_root *uuid_root;
4722 struct task_struct *task;
4729 trans = btrfs_start_transaction(tree_root, 2);
4731 return PTR_ERR(trans);
4733 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4734 if (IS_ERR(uuid_root)) {
4735 ret = PTR_ERR(uuid_root);
4736 btrfs_abort_transaction(trans, ret);
4737 btrfs_end_transaction(trans);
4741 fs_info->uuid_root = uuid_root;
4743 ret = btrfs_commit_transaction(trans);
4747 down(&fs_info->uuid_tree_rescan_sem);
4748 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4750 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4751 btrfs_warn(fs_info, "failed to start uuid_scan task");
4752 up(&fs_info->uuid_tree_rescan_sem);
4753 return PTR_ERR(task);
4760 * shrinking a device means finding all of the device extents past
4761 * the new size, and then following the back refs to the chunks.
4762 * The chunk relocation code actually frees the device extent
4764 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4766 struct btrfs_fs_info *fs_info = device->fs_info;
4767 struct btrfs_root *root = fs_info->dev_root;
4768 struct btrfs_trans_handle *trans;
4769 struct btrfs_dev_extent *dev_extent = NULL;
4770 struct btrfs_path *path;
4776 bool retried = false;
4777 struct extent_buffer *l;
4778 struct btrfs_key key;
4779 struct btrfs_super_block *super_copy = fs_info->super_copy;
4780 u64 old_total = btrfs_super_total_bytes(super_copy);
4781 u64 old_size = btrfs_device_get_total_bytes(device);
4785 new_size = round_down(new_size, fs_info->sectorsize);
4787 diff = round_down(old_size - new_size, fs_info->sectorsize);
4789 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4792 path = btrfs_alloc_path();
4796 path->reada = READA_BACK;
4798 trans = btrfs_start_transaction(root, 0);
4799 if (IS_ERR(trans)) {
4800 btrfs_free_path(path);
4801 return PTR_ERR(trans);
4804 mutex_lock(&fs_info->chunk_mutex);
4806 btrfs_device_set_total_bytes(device, new_size);
4807 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4808 device->fs_devices->total_rw_bytes -= diff;
4809 atomic64_sub(diff, &fs_info->free_chunk_space);
4813 * Once the device's size has been set to the new size, ensure all
4814 * in-memory chunks are synced to disk so that the loop below sees them
4815 * and relocates them accordingly.
4817 if (contains_pending_extent(device, &start, diff)) {
4818 mutex_unlock(&fs_info->chunk_mutex);
4819 ret = btrfs_commit_transaction(trans);
4823 mutex_unlock(&fs_info->chunk_mutex);
4824 btrfs_end_transaction(trans);
4828 key.objectid = device->devid;
4829 key.offset = (u64)-1;
4830 key.type = BTRFS_DEV_EXTENT_KEY;
4833 mutex_lock(&fs_info->reclaim_bgs_lock);
4834 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4836 mutex_unlock(&fs_info->reclaim_bgs_lock);
4840 ret = btrfs_previous_item(root, path, 0, key.type);
4842 mutex_unlock(&fs_info->reclaim_bgs_lock);
4846 btrfs_release_path(path);
4851 slot = path->slots[0];
4852 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4854 if (key.objectid != device->devid) {
4855 mutex_unlock(&fs_info->reclaim_bgs_lock);
4856 btrfs_release_path(path);
4860 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4861 length = btrfs_dev_extent_length(l, dev_extent);
4863 if (key.offset + length <= new_size) {
4864 mutex_unlock(&fs_info->reclaim_bgs_lock);
4865 btrfs_release_path(path);
4869 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4870 btrfs_release_path(path);
4873 * We may be relocating the only data chunk we have,
4874 * which could potentially end up with losing data's
4875 * raid profile, so lets allocate an empty one in
4878 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4880 mutex_unlock(&fs_info->reclaim_bgs_lock);
4884 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4885 mutex_unlock(&fs_info->reclaim_bgs_lock);
4886 if (ret == -ENOSPC) {
4889 if (ret == -ETXTBSY) {
4891 "could not shrink block group %llu due to active swapfile",
4896 } while (key.offset-- > 0);
4898 if (failed && !retried) {
4902 } else if (failed && retried) {
4907 /* Shrinking succeeded, else we would be at "done". */
4908 trans = btrfs_start_transaction(root, 0);
4909 if (IS_ERR(trans)) {
4910 ret = PTR_ERR(trans);
4914 mutex_lock(&fs_info->chunk_mutex);
4915 /* Clear all state bits beyond the shrunk device size */
4916 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4919 btrfs_device_set_disk_total_bytes(device, new_size);
4920 if (list_empty(&device->post_commit_list))
4921 list_add_tail(&device->post_commit_list,
4922 &trans->transaction->dev_update_list);
4924 WARN_ON(diff > old_total);
4925 btrfs_set_super_total_bytes(super_copy,
4926 round_down(old_total - diff, fs_info->sectorsize));
4927 mutex_unlock(&fs_info->chunk_mutex);
4929 /* Now btrfs_update_device() will change the on-disk size. */
4930 ret = btrfs_update_device(trans, device);
4932 btrfs_abort_transaction(trans, ret);
4933 btrfs_end_transaction(trans);
4935 ret = btrfs_commit_transaction(trans);
4938 btrfs_free_path(path);
4940 mutex_lock(&fs_info->chunk_mutex);
4941 btrfs_device_set_total_bytes(device, old_size);
4942 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4943 device->fs_devices->total_rw_bytes += diff;
4944 atomic64_add(diff, &fs_info->free_chunk_space);
4945 mutex_unlock(&fs_info->chunk_mutex);
4950 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4951 struct btrfs_key *key,
4952 struct btrfs_chunk *chunk, int item_size)
4954 struct btrfs_super_block *super_copy = fs_info->super_copy;
4955 struct btrfs_disk_key disk_key;
4959 lockdep_assert_held(&fs_info->chunk_mutex);
4961 array_size = btrfs_super_sys_array_size(super_copy);
4962 if (array_size + item_size + sizeof(disk_key)
4963 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
4966 ptr = super_copy->sys_chunk_array + array_size;
4967 btrfs_cpu_key_to_disk(&disk_key, key);
4968 memcpy(ptr, &disk_key, sizeof(disk_key));
4969 ptr += sizeof(disk_key);
4970 memcpy(ptr, chunk, item_size);
4971 item_size += sizeof(disk_key);
4972 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4978 * sort the devices in descending order by max_avail, total_avail
4980 static int btrfs_cmp_device_info(const void *a, const void *b)
4982 const struct btrfs_device_info *di_a = a;
4983 const struct btrfs_device_info *di_b = b;
4985 if (di_a->max_avail > di_b->max_avail)
4987 if (di_a->max_avail < di_b->max_avail)
4989 if (di_a->total_avail > di_b->total_avail)
4991 if (di_a->total_avail < di_b->total_avail)
4996 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4998 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5001 btrfs_set_fs_incompat(info, RAID56);
5004 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
5006 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
5009 btrfs_set_fs_incompat(info, RAID1C34);
5013 * Structure used internally for __btrfs_alloc_chunk() function.
5014 * Wraps needed parameters.
5016 struct alloc_chunk_ctl {
5019 /* Total number of stripes to allocate */
5021 /* sub_stripes info for map */
5023 /* Stripes per device */
5025 /* Maximum number of devices to use */
5027 /* Minimum number of devices to use */
5029 /* ndevs has to be a multiple of this */
5031 /* Number of copies */
5033 /* Number of stripes worth of bytes to store parity information */
5035 u64 max_stripe_size;
5043 static void init_alloc_chunk_ctl_policy_regular(
5044 struct btrfs_fs_devices *fs_devices,
5045 struct alloc_chunk_ctl *ctl)
5047 u64 type = ctl->type;
5049 if (type & BTRFS_BLOCK_GROUP_DATA) {
5050 ctl->max_stripe_size = SZ_1G;
5051 ctl->max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
5052 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5053 /* For larger filesystems, use larger metadata chunks */
5054 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
5055 ctl->max_stripe_size = SZ_1G;
5057 ctl->max_stripe_size = SZ_256M;
5058 ctl->max_chunk_size = ctl->max_stripe_size;
5059 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5060 ctl->max_stripe_size = SZ_32M;
5061 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5062 ctl->devs_max = min_t(int, ctl->devs_max,
5063 BTRFS_MAX_DEVS_SYS_CHUNK);
5068 /* We don't want a chunk larger than 10% of writable space */
5069 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
5070 ctl->max_chunk_size);
5071 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
5074 static void init_alloc_chunk_ctl_policy_zoned(
5075 struct btrfs_fs_devices *fs_devices,
5076 struct alloc_chunk_ctl *ctl)
5078 u64 zone_size = fs_devices->fs_info->zone_size;
5080 int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5081 int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5082 u64 min_chunk_size = min_data_stripes * zone_size;
5083 u64 type = ctl->type;
5085 ctl->max_stripe_size = zone_size;
5086 if (type & BTRFS_BLOCK_GROUP_DATA) {
5087 ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5089 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5090 ctl->max_chunk_size = ctl->max_stripe_size;
5091 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5092 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5093 ctl->devs_max = min_t(int, ctl->devs_max,
5094 BTRFS_MAX_DEVS_SYS_CHUNK);
5099 /* We don't want a chunk larger than 10% of writable space */
5100 limit = max(round_down(div_factor(fs_devices->total_rw_bytes, 1),
5103 ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5104 ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5107 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5108 struct alloc_chunk_ctl *ctl)
5110 int index = btrfs_bg_flags_to_raid_index(ctl->type);
5112 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5113 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5114 ctl->devs_max = btrfs_raid_array[index].devs_max;
5116 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5117 ctl->devs_min = btrfs_raid_array[index].devs_min;
5118 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5119 ctl->ncopies = btrfs_raid_array[index].ncopies;
5120 ctl->nparity = btrfs_raid_array[index].nparity;
5123 switch (fs_devices->chunk_alloc_policy) {
5124 case BTRFS_CHUNK_ALLOC_REGULAR:
5125 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5127 case BTRFS_CHUNK_ALLOC_ZONED:
5128 init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5135 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5136 struct alloc_chunk_ctl *ctl,
5137 struct btrfs_device_info *devices_info)
5139 struct btrfs_fs_info *info = fs_devices->fs_info;
5140 struct btrfs_device *device;
5142 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5149 * in the first pass through the devices list, we gather information
5150 * about the available holes on each device.
5152 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5153 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5155 "BTRFS: read-only device in alloc_list\n");
5159 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5160 &device->dev_state) ||
5161 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5164 if (device->total_bytes > device->bytes_used)
5165 total_avail = device->total_bytes - device->bytes_used;
5169 /* If there is no space on this device, skip it. */
5170 if (total_avail < ctl->dev_extent_min)
5173 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5175 if (ret && ret != -ENOSPC)
5179 max_avail = dev_extent_want;
5181 if (max_avail < ctl->dev_extent_min) {
5182 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5184 "%s: devid %llu has no free space, have=%llu want=%llu",
5185 __func__, device->devid, max_avail,
5186 ctl->dev_extent_min);
5190 if (ndevs == fs_devices->rw_devices) {
5191 WARN(1, "%s: found more than %llu devices\n",
5192 __func__, fs_devices->rw_devices);
5195 devices_info[ndevs].dev_offset = dev_offset;
5196 devices_info[ndevs].max_avail = max_avail;
5197 devices_info[ndevs].total_avail = total_avail;
5198 devices_info[ndevs].dev = device;
5204 * now sort the devices by hole size / available space
5206 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5207 btrfs_cmp_device_info, NULL);
5212 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5213 struct btrfs_device_info *devices_info)
5215 /* Number of stripes that count for block group size */
5219 * The primary goal is to maximize the number of stripes, so use as
5220 * many devices as possible, even if the stripes are not maximum sized.
5222 * The DUP profile stores more than one stripe per device, the
5223 * max_avail is the total size so we have to adjust.
5225 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5227 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5229 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5230 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5233 * Use the number of data stripes to figure out how big this chunk is
5234 * really going to be in terms of logical address space, and compare
5235 * that answer with the max chunk size. If it's higher, we try to
5236 * reduce stripe_size.
5238 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5240 * Reduce stripe_size, round it up to a 16MB boundary again and
5241 * then use it, unless it ends up being even bigger than the
5242 * previous value we had already.
5244 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5245 data_stripes), SZ_16M),
5249 /* Align to BTRFS_STRIPE_LEN */
5250 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5251 ctl->chunk_size = ctl->stripe_size * data_stripes;
5256 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5257 struct btrfs_device_info *devices_info)
5259 u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5260 /* Number of stripes that count for block group size */
5264 * It should hold because:
5265 * dev_extent_min == dev_extent_want == zone_size * dev_stripes
5267 ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min);
5269 ctl->stripe_size = zone_size;
5270 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5271 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5273 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */
5274 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5275 ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5276 ctl->stripe_size) + ctl->nparity,
5278 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5279 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5280 ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size);
5283 ctl->chunk_size = ctl->stripe_size * data_stripes;
5288 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5289 struct alloc_chunk_ctl *ctl,
5290 struct btrfs_device_info *devices_info)
5292 struct btrfs_fs_info *info = fs_devices->fs_info;
5295 * Round down to number of usable stripes, devs_increment can be any
5296 * number so we can't use round_down() that requires power of 2, while
5297 * rounddown is safe.
5299 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5301 if (ctl->ndevs < ctl->devs_min) {
5302 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5304 "%s: not enough devices with free space: have=%d minimum required=%d",
5305 __func__, ctl->ndevs, ctl->devs_min);
5310 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5312 switch (fs_devices->chunk_alloc_policy) {
5313 case BTRFS_CHUNK_ALLOC_REGULAR:
5314 return decide_stripe_size_regular(ctl, devices_info);
5315 case BTRFS_CHUNK_ALLOC_ZONED:
5316 return decide_stripe_size_zoned(ctl, devices_info);
5322 static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
5323 struct alloc_chunk_ctl *ctl,
5324 struct btrfs_device_info *devices_info)
5326 struct btrfs_fs_info *info = trans->fs_info;
5327 struct map_lookup *map = NULL;
5328 struct extent_map_tree *em_tree;
5329 struct btrfs_block_group *block_group;
5330 struct extent_map *em;
5331 u64 start = ctl->start;
5332 u64 type = ctl->type;
5337 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5339 return ERR_PTR(-ENOMEM);
5340 map->num_stripes = ctl->num_stripes;
5342 for (i = 0; i < ctl->ndevs; ++i) {
5343 for (j = 0; j < ctl->dev_stripes; ++j) {
5344 int s = i * ctl->dev_stripes + j;
5345 map->stripes[s].dev = devices_info[i].dev;
5346 map->stripes[s].physical = devices_info[i].dev_offset +
5347 j * ctl->stripe_size;
5350 map->stripe_len = BTRFS_STRIPE_LEN;
5351 map->io_align = BTRFS_STRIPE_LEN;
5352 map->io_width = BTRFS_STRIPE_LEN;
5354 map->sub_stripes = ctl->sub_stripes;
5356 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5358 em = alloc_extent_map();
5361 return ERR_PTR(-ENOMEM);
5363 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5364 em->map_lookup = map;
5366 em->len = ctl->chunk_size;
5367 em->block_start = 0;
5368 em->block_len = em->len;
5369 em->orig_block_len = ctl->stripe_size;
5371 em_tree = &info->mapping_tree;
5372 write_lock(&em_tree->lock);
5373 ret = add_extent_mapping(em_tree, em, 0);
5375 write_unlock(&em_tree->lock);
5376 free_extent_map(em);
5377 return ERR_PTR(ret);
5379 write_unlock(&em_tree->lock);
5381 block_group = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5382 if (IS_ERR(block_group))
5383 goto error_del_extent;
5385 for (i = 0; i < map->num_stripes; i++) {
5386 struct btrfs_device *dev = map->stripes[i].dev;
5388 btrfs_device_set_bytes_used(dev,
5389 dev->bytes_used + ctl->stripe_size);
5390 if (list_empty(&dev->post_commit_list))
5391 list_add_tail(&dev->post_commit_list,
5392 &trans->transaction->dev_update_list);
5395 atomic64_sub(ctl->stripe_size * map->num_stripes,
5396 &info->free_chunk_space);
5398 free_extent_map(em);
5399 check_raid56_incompat_flag(info, type);
5400 check_raid1c34_incompat_flag(info, type);
5405 write_lock(&em_tree->lock);
5406 remove_extent_mapping(em_tree, em);
5407 write_unlock(&em_tree->lock);
5409 /* One for our allocation */
5410 free_extent_map(em);
5411 /* One for the tree reference */
5412 free_extent_map(em);
5417 struct btrfs_block_group *btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
5420 struct btrfs_fs_info *info = trans->fs_info;
5421 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5422 struct btrfs_device_info *devices_info = NULL;
5423 struct alloc_chunk_ctl ctl;
5424 struct btrfs_block_group *block_group;
5427 lockdep_assert_held(&info->chunk_mutex);
5429 if (!alloc_profile_is_valid(type, 0)) {
5431 return ERR_PTR(-EINVAL);
5434 if (list_empty(&fs_devices->alloc_list)) {
5435 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5436 btrfs_debug(info, "%s: no writable device", __func__);
5437 return ERR_PTR(-ENOSPC);
5440 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5441 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5443 return ERR_PTR(-EINVAL);
5446 ctl.start = find_next_chunk(info);
5448 init_alloc_chunk_ctl(fs_devices, &ctl);
5450 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5453 return ERR_PTR(-ENOMEM);
5455 ret = gather_device_info(fs_devices, &ctl, devices_info);
5457 block_group = ERR_PTR(ret);
5461 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5463 block_group = ERR_PTR(ret);
5467 block_group = create_chunk(trans, &ctl, devices_info);
5470 kfree(devices_info);
5475 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5476 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5479 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5482 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
5483 struct btrfs_block_group *bg)
5485 struct btrfs_fs_info *fs_info = trans->fs_info;
5486 struct btrfs_root *extent_root = fs_info->extent_root;
5487 struct btrfs_root *chunk_root = fs_info->chunk_root;
5488 struct btrfs_key key;
5489 struct btrfs_chunk *chunk;
5490 struct btrfs_stripe *stripe;
5491 struct extent_map *em;
5492 struct map_lookup *map;
5498 * We take the chunk_mutex for 2 reasons:
5500 * 1) Updates and insertions in the chunk btree must be done while holding
5501 * the chunk_mutex, as well as updating the system chunk array in the
5502 * superblock. See the comment on top of btrfs_chunk_alloc() for the
5505 * 2) To prevent races with the final phase of a device replace operation
5506 * that replaces the device object associated with the map's stripes,
5507 * because the device object's id can change at any time during that
5508 * final phase of the device replace operation
5509 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5510 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5511 * which would cause a failure when updating the device item, which does
5512 * not exists, or persisting a stripe of the chunk item with such ID.
5513 * Here we can't use the device_list_mutex because our caller already
5514 * has locked the chunk_mutex, and the final phase of device replace
5515 * acquires both mutexes - first the device_list_mutex and then the
5516 * chunk_mutex. Using any of those two mutexes protects us from a
5517 * concurrent device replace.
5519 lockdep_assert_held(&fs_info->chunk_mutex);
5521 em = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
5524 btrfs_abort_transaction(trans, ret);
5528 map = em->map_lookup;
5529 item_size = btrfs_chunk_item_size(map->num_stripes);
5531 chunk = kzalloc(item_size, GFP_NOFS);
5534 btrfs_abort_transaction(trans, ret);
5538 for (i = 0; i < map->num_stripes; i++) {
5539 struct btrfs_device *device = map->stripes[i].dev;
5541 ret = btrfs_update_device(trans, device);
5546 stripe = &chunk->stripe;
5547 for (i = 0; i < map->num_stripes; i++) {
5548 struct btrfs_device *device = map->stripes[i].dev;
5549 const u64 dev_offset = map->stripes[i].physical;
5551 btrfs_set_stack_stripe_devid(stripe, device->devid);
5552 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5553 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5557 btrfs_set_stack_chunk_length(chunk, bg->length);
5558 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5559 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5560 btrfs_set_stack_chunk_type(chunk, map->type);
5561 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5562 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5563 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5564 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5565 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5567 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5568 key.type = BTRFS_CHUNK_ITEM_KEY;
5569 key.offset = bg->start;
5571 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5575 bg->chunk_item_inserted = 1;
5577 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5578 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5585 free_extent_map(em);
5589 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5591 struct btrfs_fs_info *fs_info = trans->fs_info;
5593 struct btrfs_block_group *meta_bg;
5594 struct btrfs_block_group *sys_bg;
5597 * When adding a new device for sprouting, the seed device is read-only
5598 * so we must first allocate a metadata and a system chunk. But before
5599 * adding the block group items to the extent, device and chunk btrees,
5602 * 1) Create both chunks without doing any changes to the btrees, as
5603 * otherwise we would get -ENOSPC since the block groups from the
5604 * seed device are read-only;
5606 * 2) Add the device item for the new sprout device - finishing the setup
5607 * of a new block group requires updating the device item in the chunk
5608 * btree, so it must exist when we attempt to do it. The previous step
5609 * ensures this does not fail with -ENOSPC.
5611 * After that we can add the block group items to their btrees:
5612 * update existing device item in the chunk btree, add a new block group
5613 * item to the extent btree, add a new chunk item to the chunk btree and
5614 * finally add the new device extent items to the devices btree.
5617 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5618 meta_bg = btrfs_alloc_chunk(trans, alloc_profile);
5619 if (IS_ERR(meta_bg))
5620 return PTR_ERR(meta_bg);
5622 alloc_profile = btrfs_system_alloc_profile(fs_info);
5623 sys_bg = btrfs_alloc_chunk(trans, alloc_profile);
5625 return PTR_ERR(sys_bg);
5630 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5632 const int index = btrfs_bg_flags_to_raid_index(map->type);
5634 return btrfs_raid_array[index].tolerated_failures;
5637 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5639 struct extent_map *em;
5640 struct map_lookup *map;
5645 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5649 map = em->map_lookup;
5650 for (i = 0; i < map->num_stripes; i++) {
5651 if (test_bit(BTRFS_DEV_STATE_MISSING,
5652 &map->stripes[i].dev->dev_state)) {
5656 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5657 &map->stripes[i].dev->dev_state)) {
5664 * If the number of missing devices is larger than max errors,
5665 * we can not write the data into that chunk successfully, so
5668 if (miss_ndevs > btrfs_chunk_max_errors(map))
5671 free_extent_map(em);
5675 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5677 struct extent_map *em;
5680 write_lock(&tree->lock);
5681 em = lookup_extent_mapping(tree, 0, (u64)-1);
5683 remove_extent_mapping(tree, em);
5684 write_unlock(&tree->lock);
5688 free_extent_map(em);
5689 /* once for the tree */
5690 free_extent_map(em);
5694 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5696 struct extent_map *em;
5697 struct map_lookup *map;
5700 em = btrfs_get_chunk_map(fs_info, logical, len);
5703 * We could return errors for these cases, but that could get
5704 * ugly and we'd probably do the same thing which is just not do
5705 * anything else and exit, so return 1 so the callers don't try
5706 * to use other copies.
5710 map = em->map_lookup;
5711 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5712 ret = map->num_stripes;
5713 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5714 ret = map->sub_stripes;
5715 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5717 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5719 * There could be two corrupted data stripes, we need
5720 * to loop retry in order to rebuild the correct data.
5722 * Fail a stripe at a time on every retry except the
5723 * stripe under reconstruction.
5725 ret = map->num_stripes;
5728 free_extent_map(em);
5730 down_read(&fs_info->dev_replace.rwsem);
5731 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5732 fs_info->dev_replace.tgtdev)
5734 up_read(&fs_info->dev_replace.rwsem);
5739 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5742 struct extent_map *em;
5743 struct map_lookup *map;
5744 unsigned long len = fs_info->sectorsize;
5746 em = btrfs_get_chunk_map(fs_info, logical, len);
5748 if (!WARN_ON(IS_ERR(em))) {
5749 map = em->map_lookup;
5750 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5751 len = map->stripe_len * nr_data_stripes(map);
5752 free_extent_map(em);
5757 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5759 struct extent_map *em;
5760 struct map_lookup *map;
5763 em = btrfs_get_chunk_map(fs_info, logical, len);
5765 if(!WARN_ON(IS_ERR(em))) {
5766 map = em->map_lookup;
5767 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5769 free_extent_map(em);
5774 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5775 struct map_lookup *map, int first,
5776 int dev_replace_is_ongoing)
5780 int preferred_mirror;
5782 struct btrfs_device *srcdev;
5785 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5787 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5788 num_stripes = map->sub_stripes;
5790 num_stripes = map->num_stripes;
5792 switch (fs_info->fs_devices->read_policy) {
5794 /* Shouldn't happen, just warn and use pid instead of failing */
5795 btrfs_warn_rl(fs_info,
5796 "unknown read_policy type %u, reset to pid",
5797 fs_info->fs_devices->read_policy);
5798 fs_info->fs_devices->read_policy = BTRFS_READ_POLICY_PID;
5800 case BTRFS_READ_POLICY_PID:
5801 preferred_mirror = first + (current->pid % num_stripes);
5805 if (dev_replace_is_ongoing &&
5806 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5807 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5808 srcdev = fs_info->dev_replace.srcdev;
5813 * try to avoid the drive that is the source drive for a
5814 * dev-replace procedure, only choose it if no other non-missing
5815 * mirror is available
5817 for (tolerance = 0; tolerance < 2; tolerance++) {
5818 if (map->stripes[preferred_mirror].dev->bdev &&
5819 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5820 return preferred_mirror;
5821 for (i = first; i < first + num_stripes; i++) {
5822 if (map->stripes[i].dev->bdev &&
5823 (tolerance || map->stripes[i].dev != srcdev))
5828 /* we couldn't find one that doesn't fail. Just return something
5829 * and the io error handling code will clean up eventually
5831 return preferred_mirror;
5834 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5835 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5842 for (i = 0; i < num_stripes - 1; i++) {
5843 /* Swap if parity is on a smaller index */
5844 if (bbio->raid_map[i] > bbio->raid_map[i + 1]) {
5845 swap(bbio->stripes[i], bbio->stripes[i + 1]);
5846 swap(bbio->raid_map[i], bbio->raid_map[i + 1]);
5853 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5855 struct btrfs_bio *bbio = kzalloc(
5856 /* the size of the btrfs_bio */
5857 sizeof(struct btrfs_bio) +
5858 /* plus the variable array for the stripes */
5859 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5860 /* plus the variable array for the tgt dev */
5861 sizeof(int) * (real_stripes) +
5863 * plus the raid_map, which includes both the tgt dev
5866 sizeof(u64) * (total_stripes),
5867 GFP_NOFS|__GFP_NOFAIL);
5869 atomic_set(&bbio->error, 0);
5870 refcount_set(&bbio->refs, 1);
5872 bbio->tgtdev_map = (int *)(bbio->stripes + total_stripes);
5873 bbio->raid_map = (u64 *)(bbio->tgtdev_map + real_stripes);
5878 void btrfs_get_bbio(struct btrfs_bio *bbio)
5880 WARN_ON(!refcount_read(&bbio->refs));
5881 refcount_inc(&bbio->refs);
5884 void btrfs_put_bbio(struct btrfs_bio *bbio)
5888 if (refcount_dec_and_test(&bbio->refs))
5892 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5894 * Please note that, discard won't be sent to target device of device
5897 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5898 u64 logical, u64 *length_ret,
5899 struct btrfs_bio **bbio_ret)
5901 struct extent_map *em;
5902 struct map_lookup *map;
5903 struct btrfs_bio *bbio;
5904 u64 length = *length_ret;
5908 u64 stripe_end_offset;
5915 u32 sub_stripes = 0;
5916 u64 stripes_per_dev = 0;
5917 u32 remaining_stripes = 0;
5918 u32 last_stripe = 0;
5922 /* discard always return a bbio */
5925 em = btrfs_get_chunk_map(fs_info, logical, length);
5929 map = em->map_lookup;
5930 /* we don't discard raid56 yet */
5931 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5936 offset = logical - em->start;
5937 length = min_t(u64, em->start + em->len - logical, length);
5938 *length_ret = length;
5940 stripe_len = map->stripe_len;
5942 * stripe_nr counts the total number of stripes we have to stride
5943 * to get to this block
5945 stripe_nr = div64_u64(offset, stripe_len);
5947 /* stripe_offset is the offset of this block in its stripe */
5948 stripe_offset = offset - stripe_nr * stripe_len;
5950 stripe_nr_end = round_up(offset + length, map->stripe_len);
5951 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5952 stripe_cnt = stripe_nr_end - stripe_nr;
5953 stripe_end_offset = stripe_nr_end * map->stripe_len -
5956 * after this, stripe_nr is the number of stripes on this
5957 * device we have to walk to find the data, and stripe_index is
5958 * the number of our device in the stripe array
5962 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5963 BTRFS_BLOCK_GROUP_RAID10)) {
5964 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5967 sub_stripes = map->sub_stripes;
5969 factor = map->num_stripes / sub_stripes;
5970 num_stripes = min_t(u64, map->num_stripes,
5971 sub_stripes * stripe_cnt);
5972 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5973 stripe_index *= sub_stripes;
5974 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5975 &remaining_stripes);
5976 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5977 last_stripe *= sub_stripes;
5978 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5979 BTRFS_BLOCK_GROUP_DUP)) {
5980 num_stripes = map->num_stripes;
5982 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5986 bbio = alloc_btrfs_bio(num_stripes, 0);
5992 for (i = 0; i < num_stripes; i++) {
5993 bbio->stripes[i].physical =
5994 map->stripes[stripe_index].physical +
5995 stripe_offset + stripe_nr * map->stripe_len;
5996 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5998 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5999 BTRFS_BLOCK_GROUP_RAID10)) {
6000 bbio->stripes[i].length = stripes_per_dev *
6003 if (i / sub_stripes < remaining_stripes)
6004 bbio->stripes[i].length +=
6008 * Special for the first stripe and
6011 * |-------|...|-------|
6015 if (i < sub_stripes)
6016 bbio->stripes[i].length -=
6019 if (stripe_index >= last_stripe &&
6020 stripe_index <= (last_stripe +
6022 bbio->stripes[i].length -=
6025 if (i == sub_stripes - 1)
6028 bbio->stripes[i].length = length;
6032 if (stripe_index == map->num_stripes) {
6039 bbio->map_type = map->type;
6040 bbio->num_stripes = num_stripes;
6042 free_extent_map(em);
6047 * In dev-replace case, for repair case (that's the only case where the mirror
6048 * is selected explicitly when calling btrfs_map_block), blocks left of the
6049 * left cursor can also be read from the target drive.
6051 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
6053 * For READ, it also needs to be supported using the same mirror number.
6055 * If the requested block is not left of the left cursor, EIO is returned. This
6056 * can happen because btrfs_num_copies() returns one more in the dev-replace
6059 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
6060 u64 logical, u64 length,
6061 u64 srcdev_devid, int *mirror_num,
6064 struct btrfs_bio *bbio = NULL;
6066 int index_srcdev = 0;
6068 u64 physical_of_found = 0;
6072 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
6073 logical, &length, &bbio, 0, 0);
6075 ASSERT(bbio == NULL);
6079 num_stripes = bbio->num_stripes;
6080 if (*mirror_num > num_stripes) {
6082 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
6083 * that means that the requested area is not left of the left
6086 btrfs_put_bbio(bbio);
6091 * process the rest of the function using the mirror_num of the source
6092 * drive. Therefore look it up first. At the end, patch the device
6093 * pointer to the one of the target drive.
6095 for (i = 0; i < num_stripes; i++) {
6096 if (bbio->stripes[i].dev->devid != srcdev_devid)
6100 * In case of DUP, in order to keep it simple, only add the
6101 * mirror with the lowest physical address
6104 physical_of_found <= bbio->stripes[i].physical)
6109 physical_of_found = bbio->stripes[i].physical;
6112 btrfs_put_bbio(bbio);
6118 *mirror_num = index_srcdev + 1;
6119 *physical = physical_of_found;
6123 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6125 struct btrfs_block_group *cache;
6128 /* Non zoned filesystem does not use "to_copy" flag */
6129 if (!btrfs_is_zoned(fs_info))
6132 cache = btrfs_lookup_block_group(fs_info, logical);
6134 spin_lock(&cache->lock);
6135 ret = cache->to_copy;
6136 spin_unlock(&cache->lock);
6138 btrfs_put_block_group(cache);
6142 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
6143 struct btrfs_bio **bbio_ret,
6144 struct btrfs_dev_replace *dev_replace,
6146 int *num_stripes_ret, int *max_errors_ret)
6148 struct btrfs_bio *bbio = *bbio_ret;
6149 u64 srcdev_devid = dev_replace->srcdev->devid;
6150 int tgtdev_indexes = 0;
6151 int num_stripes = *num_stripes_ret;
6152 int max_errors = *max_errors_ret;
6155 if (op == BTRFS_MAP_WRITE) {
6156 int index_where_to_add;
6159 * A block group which have "to_copy" set will eventually
6160 * copied by dev-replace process. We can avoid cloning IO here.
6162 if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6166 * duplicate the write operations while the dev replace
6167 * procedure is running. Since the copying of the old disk to
6168 * the new disk takes place at run time while the filesystem is
6169 * mounted writable, the regular write operations to the old
6170 * disk have to be duplicated to go to the new disk as well.
6172 * Note that device->missing is handled by the caller, and that
6173 * the write to the old disk is already set up in the stripes
6176 index_where_to_add = num_stripes;
6177 for (i = 0; i < num_stripes; i++) {
6178 if (bbio->stripes[i].dev->devid == srcdev_devid) {
6179 /* write to new disk, too */
6180 struct btrfs_bio_stripe *new =
6181 bbio->stripes + index_where_to_add;
6182 struct btrfs_bio_stripe *old =
6185 new->physical = old->physical;
6186 new->length = old->length;
6187 new->dev = dev_replace->tgtdev;
6188 bbio->tgtdev_map[i] = index_where_to_add;
6189 index_where_to_add++;
6194 num_stripes = index_where_to_add;
6195 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
6196 int index_srcdev = 0;
6198 u64 physical_of_found = 0;
6201 * During the dev-replace procedure, the target drive can also
6202 * be used to read data in case it is needed to repair a corrupt
6203 * block elsewhere. This is possible if the requested area is
6204 * left of the left cursor. In this area, the target drive is a
6205 * full copy of the source drive.
6207 for (i = 0; i < num_stripes; i++) {
6208 if (bbio->stripes[i].dev->devid == srcdev_devid) {
6210 * In case of DUP, in order to keep it simple,
6211 * only add the mirror with the lowest physical
6215 physical_of_found <=
6216 bbio->stripes[i].physical)
6220 physical_of_found = bbio->stripes[i].physical;
6224 struct btrfs_bio_stripe *tgtdev_stripe =
6225 bbio->stripes + num_stripes;
6227 tgtdev_stripe->physical = physical_of_found;
6228 tgtdev_stripe->length =
6229 bbio->stripes[index_srcdev].length;
6230 tgtdev_stripe->dev = dev_replace->tgtdev;
6231 bbio->tgtdev_map[index_srcdev] = num_stripes;
6238 *num_stripes_ret = num_stripes;
6239 *max_errors_ret = max_errors;
6240 bbio->num_tgtdevs = tgtdev_indexes;
6244 static bool need_full_stripe(enum btrfs_map_op op)
6246 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
6250 * Calculate the geometry of a particular (address, len) tuple. This
6251 * information is used to calculate how big a particular bio can get before it
6252 * straddles a stripe.
6254 * @fs_info: the filesystem
6255 * @em: mapping containing the logical extent
6256 * @op: type of operation - write or read
6257 * @logical: address that we want to figure out the geometry of
6258 * @io_geom: pointer used to return values
6260 * Returns < 0 in case a chunk for the given logical address cannot be found,
6261 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
6263 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, struct extent_map *em,
6264 enum btrfs_map_op op, u64 logical,
6265 struct btrfs_io_geometry *io_geom)
6267 struct map_lookup *map;
6273 u64 raid56_full_stripe_start = (u64)-1;
6276 ASSERT(op != BTRFS_MAP_DISCARD);
6278 map = em->map_lookup;
6279 /* Offset of this logical address in the chunk */
6280 offset = logical - em->start;
6281 /* Len of a stripe in a chunk */
6282 stripe_len = map->stripe_len;
6283 /* Stripe where this block falls in */
6284 stripe_nr = div64_u64(offset, stripe_len);
6285 /* Offset of stripe in the chunk */
6286 stripe_offset = stripe_nr * stripe_len;
6287 if (offset < stripe_offset) {
6289 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
6290 stripe_offset, offset, em->start, logical, stripe_len);
6294 /* stripe_offset is the offset of this block in its stripe */
6295 stripe_offset = offset - stripe_offset;
6296 data_stripes = nr_data_stripes(map);
6298 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6299 u64 max_len = stripe_len - stripe_offset;
6302 * In case of raid56, we need to know the stripe aligned start
6304 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6305 unsigned long full_stripe_len = stripe_len * data_stripes;
6306 raid56_full_stripe_start = offset;
6309 * Allow a write of a full stripe, but make sure we
6310 * don't allow straddling of stripes
6312 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6314 raid56_full_stripe_start *= full_stripe_len;
6317 * For writes to RAID[56], allow a full stripeset across
6318 * all disks. For other RAID types and for RAID[56]
6319 * reads, just allow a single stripe (on a single disk).
6321 if (op == BTRFS_MAP_WRITE) {
6322 max_len = stripe_len * data_stripes -
6323 (offset - raid56_full_stripe_start);
6326 len = min_t(u64, em->len - offset, max_len);
6328 len = em->len - offset;
6332 io_geom->offset = offset;
6333 io_geom->stripe_len = stripe_len;
6334 io_geom->stripe_nr = stripe_nr;
6335 io_geom->stripe_offset = stripe_offset;
6336 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6341 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6342 enum btrfs_map_op op,
6343 u64 logical, u64 *length,
6344 struct btrfs_bio **bbio_ret,
6345 int mirror_num, int need_raid_map)
6347 struct extent_map *em;
6348 struct map_lookup *map;
6358 int tgtdev_indexes = 0;
6359 struct btrfs_bio *bbio = NULL;
6360 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6361 int dev_replace_is_ongoing = 0;
6362 int num_alloc_stripes;
6363 int patch_the_first_stripe_for_dev_replace = 0;
6364 u64 physical_to_patch_in_first_stripe = 0;
6365 u64 raid56_full_stripe_start = (u64)-1;
6366 struct btrfs_io_geometry geom;
6369 ASSERT(op != BTRFS_MAP_DISCARD);
6371 em = btrfs_get_chunk_map(fs_info, logical, *length);
6372 ASSERT(!IS_ERR(em));
6374 ret = btrfs_get_io_geometry(fs_info, em, op, logical, &geom);
6378 map = em->map_lookup;
6381 stripe_len = geom.stripe_len;
6382 stripe_nr = geom.stripe_nr;
6383 stripe_offset = geom.stripe_offset;
6384 raid56_full_stripe_start = geom.raid56_stripe_offset;
6385 data_stripes = nr_data_stripes(map);
6387 down_read(&dev_replace->rwsem);
6388 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6390 * Hold the semaphore for read during the whole operation, write is
6391 * requested at commit time but must wait.
6393 if (!dev_replace_is_ongoing)
6394 up_read(&dev_replace->rwsem);
6396 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6397 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6398 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6399 dev_replace->srcdev->devid,
6401 &physical_to_patch_in_first_stripe);
6405 patch_the_first_stripe_for_dev_replace = 1;
6406 } else if (mirror_num > map->num_stripes) {
6412 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6413 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6415 if (!need_full_stripe(op))
6417 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6418 if (need_full_stripe(op))
6419 num_stripes = map->num_stripes;
6420 else if (mirror_num)
6421 stripe_index = mirror_num - 1;
6423 stripe_index = find_live_mirror(fs_info, map, 0,
6424 dev_replace_is_ongoing);
6425 mirror_num = stripe_index + 1;
6428 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6429 if (need_full_stripe(op)) {
6430 num_stripes = map->num_stripes;
6431 } else if (mirror_num) {
6432 stripe_index = mirror_num - 1;
6437 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6438 u32 factor = map->num_stripes / map->sub_stripes;
6440 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6441 stripe_index *= map->sub_stripes;
6443 if (need_full_stripe(op))
6444 num_stripes = map->sub_stripes;
6445 else if (mirror_num)
6446 stripe_index += mirror_num - 1;
6448 int old_stripe_index = stripe_index;
6449 stripe_index = find_live_mirror(fs_info, map,
6451 dev_replace_is_ongoing);
6452 mirror_num = stripe_index - old_stripe_index + 1;
6455 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6456 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6457 /* push stripe_nr back to the start of the full stripe */
6458 stripe_nr = div64_u64(raid56_full_stripe_start,
6459 stripe_len * data_stripes);
6461 /* RAID[56] write or recovery. Return all stripes */
6462 num_stripes = map->num_stripes;
6463 max_errors = nr_parity_stripes(map);
6465 *length = map->stripe_len;
6470 * Mirror #0 or #1 means the original data block.
6471 * Mirror #2 is RAID5 parity block.
6472 * Mirror #3 is RAID6 Q block.
6474 stripe_nr = div_u64_rem(stripe_nr,
6475 data_stripes, &stripe_index);
6477 stripe_index = data_stripes + mirror_num - 2;
6479 /* We distribute the parity blocks across stripes */
6480 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6482 if (!need_full_stripe(op) && mirror_num <= 1)
6487 * after this, stripe_nr is the number of stripes on this
6488 * device we have to walk to find the data, and stripe_index is
6489 * the number of our device in the stripe array
6491 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6493 mirror_num = stripe_index + 1;
6495 if (stripe_index >= map->num_stripes) {
6497 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6498 stripe_index, map->num_stripes);
6503 num_alloc_stripes = num_stripes;
6504 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6505 if (op == BTRFS_MAP_WRITE)
6506 num_alloc_stripes <<= 1;
6507 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6508 num_alloc_stripes++;
6509 tgtdev_indexes = num_stripes;
6512 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6518 for (i = 0; i < num_stripes; i++) {
6519 bbio->stripes[i].physical = map->stripes[stripe_index].physical +
6520 stripe_offset + stripe_nr * map->stripe_len;
6521 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
6525 /* build raid_map */
6526 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6527 (need_full_stripe(op) || mirror_num > 1)) {
6531 /* Work out the disk rotation on this stripe-set */
6532 div_u64_rem(stripe_nr, num_stripes, &rot);
6534 /* Fill in the logical address of each stripe */
6535 tmp = stripe_nr * data_stripes;
6536 for (i = 0; i < data_stripes; i++)
6537 bbio->raid_map[(i+rot) % num_stripes] =
6538 em->start + (tmp + i) * map->stripe_len;
6540 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6541 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6542 bbio->raid_map[(i+rot+1) % num_stripes] =
6545 sort_parity_stripes(bbio, num_stripes);
6548 if (need_full_stripe(op))
6549 max_errors = btrfs_chunk_max_errors(map);
6551 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6552 need_full_stripe(op)) {
6553 handle_ops_on_dev_replace(op, &bbio, dev_replace, logical,
6554 &num_stripes, &max_errors);
6558 bbio->map_type = map->type;
6559 bbio->num_stripes = num_stripes;
6560 bbio->max_errors = max_errors;
6561 bbio->mirror_num = mirror_num;
6564 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6565 * mirror_num == num_stripes + 1 && dev_replace target drive is
6566 * available as a mirror
6568 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6569 WARN_ON(num_stripes > 1);
6570 bbio->stripes[0].dev = dev_replace->tgtdev;
6571 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6572 bbio->mirror_num = map->num_stripes + 1;
6575 if (dev_replace_is_ongoing) {
6576 lockdep_assert_held(&dev_replace->rwsem);
6577 /* Unlock and let waiting writers proceed */
6578 up_read(&dev_replace->rwsem);
6580 free_extent_map(em);
6584 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6585 u64 logical, u64 *length,
6586 struct btrfs_bio **bbio_ret, int mirror_num)
6588 if (op == BTRFS_MAP_DISCARD)
6589 return __btrfs_map_block_for_discard(fs_info, logical,
6592 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6596 /* For Scrub/replace */
6597 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6598 u64 logical, u64 *length,
6599 struct btrfs_bio **bbio_ret)
6601 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6604 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6606 bio->bi_private = bbio->private;
6607 bio->bi_end_io = bbio->end_io;
6610 btrfs_put_bbio(bbio);
6613 static void btrfs_end_bio(struct bio *bio)
6615 struct btrfs_bio *bbio = bio->bi_private;
6616 int is_orig_bio = 0;
6618 if (bio->bi_status) {
6619 atomic_inc(&bbio->error);
6620 if (bio->bi_status == BLK_STS_IOERR ||
6621 bio->bi_status == BLK_STS_TARGET) {
6622 struct btrfs_device *dev = btrfs_io_bio(bio)->device;
6625 if (btrfs_op(bio) == BTRFS_MAP_WRITE)
6626 btrfs_dev_stat_inc_and_print(dev,
6627 BTRFS_DEV_STAT_WRITE_ERRS);
6628 else if (!(bio->bi_opf & REQ_RAHEAD))
6629 btrfs_dev_stat_inc_and_print(dev,
6630 BTRFS_DEV_STAT_READ_ERRS);
6631 if (bio->bi_opf & REQ_PREFLUSH)
6632 btrfs_dev_stat_inc_and_print(dev,
6633 BTRFS_DEV_STAT_FLUSH_ERRS);
6637 if (bio == bbio->orig_bio)
6640 btrfs_bio_counter_dec(bbio->fs_info);
6642 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6645 bio = bbio->orig_bio;
6648 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6649 /* only send an error to the higher layers if it is
6650 * beyond the tolerance of the btrfs bio
6652 if (atomic_read(&bbio->error) > bbio->max_errors) {
6653 bio->bi_status = BLK_STS_IOERR;
6656 * this bio is actually up to date, we didn't
6657 * go over the max number of errors
6659 bio->bi_status = BLK_STS_OK;
6662 btrfs_end_bbio(bbio, bio);
6663 } else if (!is_orig_bio) {
6668 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6669 u64 physical, struct btrfs_device *dev)
6671 struct btrfs_fs_info *fs_info = bbio->fs_info;
6673 bio->bi_private = bbio;
6674 btrfs_io_bio(bio)->device = dev;
6675 bio->bi_end_io = btrfs_end_bio;
6676 bio->bi_iter.bi_sector = physical >> 9;
6678 * For zone append writing, bi_sector must point the beginning of the
6681 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
6682 if (btrfs_dev_is_sequential(dev, physical)) {
6683 u64 zone_start = round_down(physical, fs_info->zone_size);
6685 bio->bi_iter.bi_sector = zone_start >> SECTOR_SHIFT;
6687 bio->bi_opf &= ~REQ_OP_ZONE_APPEND;
6688 bio->bi_opf |= REQ_OP_WRITE;
6691 btrfs_debug_in_rcu(fs_info,
6692 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6693 bio_op(bio), bio->bi_opf, bio->bi_iter.bi_sector,
6694 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6695 dev->devid, bio->bi_iter.bi_size);
6696 bio_set_dev(bio, dev->bdev);
6698 btrfs_bio_counter_inc_noblocked(fs_info);
6700 btrfsic_submit_bio(bio);
6703 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6705 atomic_inc(&bbio->error);
6706 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6707 /* Should be the original bio. */
6708 WARN_ON(bio != bbio->orig_bio);
6710 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6711 bio->bi_iter.bi_sector = logical >> 9;
6712 if (atomic_read(&bbio->error) > bbio->max_errors)
6713 bio->bi_status = BLK_STS_IOERR;
6715 bio->bi_status = BLK_STS_OK;
6716 btrfs_end_bbio(bbio, bio);
6720 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6723 struct btrfs_device *dev;
6724 struct bio *first_bio = bio;
6725 u64 logical = bio->bi_iter.bi_sector << 9;
6731 struct btrfs_bio *bbio = NULL;
6733 length = bio->bi_iter.bi_size;
6734 map_length = length;
6736 btrfs_bio_counter_inc_blocked(fs_info);
6737 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6738 &map_length, &bbio, mirror_num, 1);
6740 btrfs_bio_counter_dec(fs_info);
6741 return errno_to_blk_status(ret);
6744 total_devs = bbio->num_stripes;
6745 bbio->orig_bio = first_bio;
6746 bbio->private = first_bio->bi_private;
6747 bbio->end_io = first_bio->bi_end_io;
6748 bbio->fs_info = fs_info;
6749 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6751 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6752 ((btrfs_op(bio) == BTRFS_MAP_WRITE) || (mirror_num > 1))) {
6753 /* In this case, map_length has been set to the length of
6754 a single stripe; not the whole write */
6755 if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
6756 ret = raid56_parity_write(fs_info, bio, bbio,
6759 ret = raid56_parity_recover(fs_info, bio, bbio,
6760 map_length, mirror_num, 1);
6763 btrfs_bio_counter_dec(fs_info);
6764 return errno_to_blk_status(ret);
6767 if (map_length < length) {
6769 "mapping failed logical %llu bio len %llu len %llu",
6770 logical, length, map_length);
6774 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6775 dev = bbio->stripes[dev_nr].dev;
6776 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6778 (btrfs_op(first_bio) == BTRFS_MAP_WRITE &&
6779 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6780 bbio_error(bbio, first_bio, logical);
6784 if (dev_nr < total_devs - 1)
6785 bio = btrfs_bio_clone(first_bio);
6789 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical, dev);
6791 btrfs_bio_counter_dec(fs_info);
6796 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6799 * If devid and uuid are both specified, the match must be exact, otherwise
6800 * only devid is used.
6802 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6803 u64 devid, u8 *uuid, u8 *fsid)
6805 struct btrfs_device *device;
6806 struct btrfs_fs_devices *seed_devs;
6808 if (!fsid || !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6809 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6810 if (device->devid == devid &&
6811 (!uuid || memcmp(device->uuid, uuid,
6812 BTRFS_UUID_SIZE) == 0))
6817 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6819 !memcmp(seed_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6820 list_for_each_entry(device, &seed_devs->devices,
6822 if (device->devid == devid &&
6823 (!uuid || memcmp(device->uuid, uuid,
6824 BTRFS_UUID_SIZE) == 0))
6833 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6834 u64 devid, u8 *dev_uuid)
6836 struct btrfs_device *device;
6837 unsigned int nofs_flag;
6840 * We call this under the chunk_mutex, so we want to use NOFS for this
6841 * allocation, however we don't want to change btrfs_alloc_device() to
6842 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6845 nofs_flag = memalloc_nofs_save();
6846 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6847 memalloc_nofs_restore(nofs_flag);
6851 list_add(&device->dev_list, &fs_devices->devices);
6852 device->fs_devices = fs_devices;
6853 fs_devices->num_devices++;
6855 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6856 fs_devices->missing_devices++;
6862 * btrfs_alloc_device - allocate struct btrfs_device
6863 * @fs_info: used only for generating a new devid, can be NULL if
6864 * devid is provided (i.e. @devid != NULL).
6865 * @devid: a pointer to devid for this device. If NULL a new devid
6867 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6870 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6871 * on error. Returned struct is not linked onto any lists and must be
6872 * destroyed with btrfs_free_device.
6874 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6878 struct btrfs_device *dev;
6881 if (WARN_ON(!devid && !fs_info))
6882 return ERR_PTR(-EINVAL);
6884 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
6886 return ERR_PTR(-ENOMEM);
6889 * Preallocate a bio that's always going to be used for flushing device
6890 * barriers and matches the device lifespan
6892 dev->flush_bio = bio_kmalloc(GFP_KERNEL, 0);
6893 if (!dev->flush_bio) {
6895 return ERR_PTR(-ENOMEM);
6898 INIT_LIST_HEAD(&dev->dev_list);
6899 INIT_LIST_HEAD(&dev->dev_alloc_list);
6900 INIT_LIST_HEAD(&dev->post_commit_list);
6902 atomic_set(&dev->reada_in_flight, 0);
6903 atomic_set(&dev->dev_stats_ccnt, 0);
6904 btrfs_device_data_ordered_init(dev);
6905 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
6906 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
6907 extent_io_tree_init(fs_info, &dev->alloc_state,
6908 IO_TREE_DEVICE_ALLOC_STATE, NULL);
6915 ret = find_next_devid(fs_info, &tmp);
6917 btrfs_free_device(dev);
6918 return ERR_PTR(ret);
6924 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6926 generate_random_uuid(dev->uuid);
6931 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6932 u64 devid, u8 *uuid, bool error)
6935 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6938 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6942 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6944 const int data_stripes = calc_data_stripes(type, num_stripes);
6946 return div_u64(chunk_len, data_stripes);
6949 #if BITS_PER_LONG == 32
6951 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
6952 * can't be accessed on 32bit systems.
6954 * This function do mount time check to reject the fs if it already has
6955 * metadata chunk beyond that limit.
6957 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6958 u64 logical, u64 length, u64 type)
6960 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6963 if (logical + length < MAX_LFS_FILESIZE)
6966 btrfs_err_32bit_limit(fs_info);
6971 * This is to give early warning for any metadata chunk reaching
6972 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
6973 * Although we can still access the metadata, it's not going to be possible
6974 * once the limit is reached.
6976 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6977 u64 logical, u64 length, u64 type)
6979 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6982 if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6985 btrfs_warn_32bit_limit(fs_info);
6989 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6990 struct btrfs_chunk *chunk)
6992 struct btrfs_fs_info *fs_info = leaf->fs_info;
6993 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6994 struct map_lookup *map;
6995 struct extent_map *em;
7000 u8 uuid[BTRFS_UUID_SIZE];
7005 logical = key->offset;
7006 length = btrfs_chunk_length(leaf, chunk);
7007 type = btrfs_chunk_type(leaf, chunk);
7008 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
7010 #if BITS_PER_LONG == 32
7011 ret = check_32bit_meta_chunk(fs_info, logical, length, type);
7014 warn_32bit_meta_chunk(fs_info, logical, length, type);
7018 * Only need to verify chunk item if we're reading from sys chunk array,
7019 * as chunk item in tree block is already verified by tree-checker.
7021 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
7022 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
7027 read_lock(&map_tree->lock);
7028 em = lookup_extent_mapping(map_tree, logical, 1);
7029 read_unlock(&map_tree->lock);
7031 /* already mapped? */
7032 if (em && em->start <= logical && em->start + em->len > logical) {
7033 free_extent_map(em);
7036 free_extent_map(em);
7039 em = alloc_extent_map();
7042 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
7044 free_extent_map(em);
7048 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
7049 em->map_lookup = map;
7050 em->start = logical;
7053 em->block_start = 0;
7054 em->block_len = em->len;
7056 map->num_stripes = num_stripes;
7057 map->io_width = btrfs_chunk_io_width(leaf, chunk);
7058 map->io_align = btrfs_chunk_io_align(leaf, chunk);
7059 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
7061 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
7062 map->verified_stripes = 0;
7063 em->orig_block_len = calc_stripe_length(type, em->len,
7065 for (i = 0; i < num_stripes; i++) {
7066 map->stripes[i].physical =
7067 btrfs_stripe_offset_nr(leaf, chunk, i);
7068 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
7069 read_extent_buffer(leaf, uuid, (unsigned long)
7070 btrfs_stripe_dev_uuid_nr(chunk, i),
7072 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
7074 if (!map->stripes[i].dev &&
7075 !btrfs_test_opt(fs_info, DEGRADED)) {
7076 free_extent_map(em);
7077 btrfs_report_missing_device(fs_info, devid, uuid, true);
7080 if (!map->stripes[i].dev) {
7081 map->stripes[i].dev =
7082 add_missing_dev(fs_info->fs_devices, devid,
7084 if (IS_ERR(map->stripes[i].dev)) {
7085 free_extent_map(em);
7087 "failed to init missing dev %llu: %ld",
7088 devid, PTR_ERR(map->stripes[i].dev));
7089 return PTR_ERR(map->stripes[i].dev);
7091 btrfs_report_missing_device(fs_info, devid, uuid, false);
7093 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
7094 &(map->stripes[i].dev->dev_state));
7098 write_lock(&map_tree->lock);
7099 ret = add_extent_mapping(map_tree, em, 0);
7100 write_unlock(&map_tree->lock);
7103 "failed to add chunk map, start=%llu len=%llu: %d",
7104 em->start, em->len, ret);
7106 free_extent_map(em);
7111 static void fill_device_from_item(struct extent_buffer *leaf,
7112 struct btrfs_dev_item *dev_item,
7113 struct btrfs_device *device)
7117 device->devid = btrfs_device_id(leaf, dev_item);
7118 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7119 device->total_bytes = device->disk_total_bytes;
7120 device->commit_total_bytes = device->disk_total_bytes;
7121 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
7122 device->commit_bytes_used = device->bytes_used;
7123 device->type = btrfs_device_type(leaf, dev_item);
7124 device->io_align = btrfs_device_io_align(leaf, dev_item);
7125 device->io_width = btrfs_device_io_width(leaf, dev_item);
7126 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
7127 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
7128 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
7130 ptr = btrfs_device_uuid(dev_item);
7131 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
7134 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
7137 struct btrfs_fs_devices *fs_devices;
7140 lockdep_assert_held(&uuid_mutex);
7143 /* This will match only for multi-device seed fs */
7144 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
7145 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7149 fs_devices = find_fsid(fsid, NULL);
7151 if (!btrfs_test_opt(fs_info, DEGRADED))
7152 return ERR_PTR(-ENOENT);
7154 fs_devices = alloc_fs_devices(fsid, NULL);
7155 if (IS_ERR(fs_devices))
7158 fs_devices->seeding = true;
7159 fs_devices->opened = 1;
7164 * Upon first call for a seed fs fsid, just create a private copy of the
7165 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7167 fs_devices = clone_fs_devices(fs_devices);
7168 if (IS_ERR(fs_devices))
7171 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
7173 free_fs_devices(fs_devices);
7174 return ERR_PTR(ret);
7177 if (!fs_devices->seeding) {
7178 close_fs_devices(fs_devices);
7179 free_fs_devices(fs_devices);
7180 return ERR_PTR(-EINVAL);
7183 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7188 static int read_one_dev(struct extent_buffer *leaf,
7189 struct btrfs_dev_item *dev_item)
7191 struct btrfs_fs_info *fs_info = leaf->fs_info;
7192 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7193 struct btrfs_device *device;
7196 u8 fs_uuid[BTRFS_FSID_SIZE];
7197 u8 dev_uuid[BTRFS_UUID_SIZE];
7199 devid = btrfs_device_id(leaf, dev_item);
7200 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7202 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7205 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7206 fs_devices = open_seed_devices(fs_info, fs_uuid);
7207 if (IS_ERR(fs_devices))
7208 return PTR_ERR(fs_devices);
7211 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
7214 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7215 btrfs_report_missing_device(fs_info, devid,
7220 device = add_missing_dev(fs_devices, devid, dev_uuid);
7221 if (IS_ERR(device)) {
7223 "failed to add missing dev %llu: %ld",
7224 devid, PTR_ERR(device));
7225 return PTR_ERR(device);
7227 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7229 if (!device->bdev) {
7230 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7231 btrfs_report_missing_device(fs_info,
7232 devid, dev_uuid, true);
7235 btrfs_report_missing_device(fs_info, devid,
7239 if (!device->bdev &&
7240 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7242 * this happens when a device that was properly setup
7243 * in the device info lists suddenly goes bad.
7244 * device->bdev is NULL, and so we have to set
7245 * device->missing to one here
7247 device->fs_devices->missing_devices++;
7248 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7251 /* Move the device to its own fs_devices */
7252 if (device->fs_devices != fs_devices) {
7253 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7254 &device->dev_state));
7256 list_move(&device->dev_list, &fs_devices->devices);
7257 device->fs_devices->num_devices--;
7258 fs_devices->num_devices++;
7260 device->fs_devices->missing_devices--;
7261 fs_devices->missing_devices++;
7263 device->fs_devices = fs_devices;
7267 if (device->fs_devices != fs_info->fs_devices) {
7268 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7269 if (device->generation !=
7270 btrfs_device_generation(leaf, dev_item))
7274 fill_device_from_item(leaf, dev_item, device);
7276 u64 max_total_bytes = i_size_read(device->bdev->bd_inode);
7278 if (device->total_bytes > max_total_bytes) {
7280 "device total_bytes should be at most %llu but found %llu",
7281 max_total_bytes, device->total_bytes);
7285 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7286 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7287 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7288 device->fs_devices->total_rw_bytes += device->total_bytes;
7289 atomic64_add(device->total_bytes - device->bytes_used,
7290 &fs_info->free_chunk_space);
7296 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7298 struct btrfs_root *root = fs_info->tree_root;
7299 struct btrfs_super_block *super_copy = fs_info->super_copy;
7300 struct extent_buffer *sb;
7301 struct btrfs_disk_key *disk_key;
7302 struct btrfs_chunk *chunk;
7304 unsigned long sb_array_offset;
7311 struct btrfs_key key;
7313 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7315 * This will create extent buffer of nodesize, superblock size is
7316 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7317 * overallocate but we can keep it as-is, only the first page is used.
7319 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET,
7320 root->root_key.objectid, 0);
7323 set_extent_buffer_uptodate(sb);
7325 * The sb extent buffer is artificial and just used to read the system array.
7326 * set_extent_buffer_uptodate() call does not properly mark all it's
7327 * pages up-to-date when the page is larger: extent does not cover the
7328 * whole page and consequently check_page_uptodate does not find all
7329 * the page's extents up-to-date (the hole beyond sb),
7330 * write_extent_buffer then triggers a WARN_ON.
7332 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7333 * but sb spans only this function. Add an explicit SetPageUptodate call
7334 * to silence the warning eg. on PowerPC 64.
7336 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
7337 SetPageUptodate(sb->pages[0]);
7339 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7340 array_size = btrfs_super_sys_array_size(super_copy);
7342 array_ptr = super_copy->sys_chunk_array;
7343 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7346 while (cur_offset < array_size) {
7347 disk_key = (struct btrfs_disk_key *)array_ptr;
7348 len = sizeof(*disk_key);
7349 if (cur_offset + len > array_size)
7350 goto out_short_read;
7352 btrfs_disk_key_to_cpu(&key, disk_key);
7355 sb_array_offset += len;
7358 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
7360 "unexpected item type %u in sys_array at offset %u",
7361 (u32)key.type, cur_offset);
7366 chunk = (struct btrfs_chunk *)sb_array_offset;
7368 * At least one btrfs_chunk with one stripe must be present,
7369 * exact stripe count check comes afterwards
7371 len = btrfs_chunk_item_size(1);
7372 if (cur_offset + len > array_size)
7373 goto out_short_read;
7375 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7378 "invalid number of stripes %u in sys_array at offset %u",
7379 num_stripes, cur_offset);
7384 type = btrfs_chunk_type(sb, chunk);
7385 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7387 "invalid chunk type %llu in sys_array at offset %u",
7393 len = btrfs_chunk_item_size(num_stripes);
7394 if (cur_offset + len > array_size)
7395 goto out_short_read;
7397 ret = read_one_chunk(&key, sb, chunk);
7402 sb_array_offset += len;
7405 clear_extent_buffer_uptodate(sb);
7406 free_extent_buffer_stale(sb);
7410 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7412 clear_extent_buffer_uptodate(sb);
7413 free_extent_buffer_stale(sb);
7418 * Check if all chunks in the fs are OK for read-write degraded mount
7420 * If the @failing_dev is specified, it's accounted as missing.
7422 * Return true if all chunks meet the minimal RW mount requirements.
7423 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7425 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7426 struct btrfs_device *failing_dev)
7428 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7429 struct extent_map *em;
7433 read_lock(&map_tree->lock);
7434 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7435 read_unlock(&map_tree->lock);
7436 /* No chunk at all? Return false anyway */
7442 struct map_lookup *map;
7447 map = em->map_lookup;
7449 btrfs_get_num_tolerated_disk_barrier_failures(
7451 for (i = 0; i < map->num_stripes; i++) {
7452 struct btrfs_device *dev = map->stripes[i].dev;
7454 if (!dev || !dev->bdev ||
7455 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7456 dev->last_flush_error)
7458 else if (failing_dev && failing_dev == dev)
7461 if (missing > max_tolerated) {
7464 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7465 em->start, missing, max_tolerated);
7466 free_extent_map(em);
7470 next_start = extent_map_end(em);
7471 free_extent_map(em);
7473 read_lock(&map_tree->lock);
7474 em = lookup_extent_mapping(map_tree, next_start,
7475 (u64)(-1) - next_start);
7476 read_unlock(&map_tree->lock);
7482 static void readahead_tree_node_children(struct extent_buffer *node)
7485 const int nr_items = btrfs_header_nritems(node);
7487 for (i = 0; i < nr_items; i++)
7488 btrfs_readahead_node_child(node, i);
7491 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7493 struct btrfs_root *root = fs_info->chunk_root;
7494 struct btrfs_path *path;
7495 struct extent_buffer *leaf;
7496 struct btrfs_key key;
7497 struct btrfs_key found_key;
7501 u64 last_ra_node = 0;
7503 path = btrfs_alloc_path();
7508 * uuid_mutex is needed only if we are mounting a sprout FS
7509 * otherwise we don't need it.
7511 mutex_lock(&uuid_mutex);
7514 * It is possible for mount and umount to race in such a way that
7515 * we execute this code path, but open_fs_devices failed to clear
7516 * total_rw_bytes. We certainly want it cleared before reading the
7517 * device items, so clear it here.
7519 fs_info->fs_devices->total_rw_bytes = 0;
7522 * Lockdep complains about possible circular locking dependency between
7523 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7524 * used for freeze procection of a fs (struct super_block.s_writers),
7525 * which we take when starting a transaction, and extent buffers of the
7526 * chunk tree if we call read_one_dev() while holding a lock on an
7527 * extent buffer of the chunk tree. Since we are mounting the filesystem
7528 * and at this point there can't be any concurrent task modifying the
7529 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7531 ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
7532 path->skip_locking = 1;
7535 * Read all device items, and then all the chunk items. All
7536 * device items are found before any chunk item (their object id
7537 * is smaller than the lowest possible object id for a chunk
7538 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7540 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7543 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7547 struct extent_buffer *node;
7549 leaf = path->nodes[0];
7550 slot = path->slots[0];
7551 if (slot >= btrfs_header_nritems(leaf)) {
7552 ret = btrfs_next_leaf(root, path);
7559 node = path->nodes[1];
7561 if (last_ra_node != node->start) {
7562 readahead_tree_node_children(node);
7563 last_ra_node = node->start;
7566 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7567 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7568 struct btrfs_dev_item *dev_item;
7569 dev_item = btrfs_item_ptr(leaf, slot,
7570 struct btrfs_dev_item);
7571 ret = read_one_dev(leaf, dev_item);
7575 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7576 struct btrfs_chunk *chunk;
7579 * We are only called at mount time, so no need to take
7580 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7581 * we always lock first fs_info->chunk_mutex before
7582 * acquiring any locks on the chunk tree. This is a
7583 * requirement for chunk allocation, see the comment on
7584 * top of btrfs_chunk_alloc() for details.
7586 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7587 ret = read_one_chunk(&found_key, leaf, chunk);
7595 * After loading chunk tree, we've got all device information,
7596 * do another round of validation checks.
7598 if (total_dev != fs_info->fs_devices->total_devices) {
7600 "super_num_devices %llu mismatch with num_devices %llu found here",
7601 btrfs_super_num_devices(fs_info->super_copy),
7606 if (btrfs_super_total_bytes(fs_info->super_copy) <
7607 fs_info->fs_devices->total_rw_bytes) {
7609 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7610 btrfs_super_total_bytes(fs_info->super_copy),
7611 fs_info->fs_devices->total_rw_bytes);
7617 mutex_unlock(&uuid_mutex);
7619 btrfs_free_path(path);
7623 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7625 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7626 struct btrfs_device *device;
7628 fs_devices->fs_info = fs_info;
7630 mutex_lock(&fs_devices->device_list_mutex);
7631 list_for_each_entry(device, &fs_devices->devices, dev_list)
7632 device->fs_info = fs_info;
7634 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7635 list_for_each_entry(device, &seed_devs->devices, dev_list)
7636 device->fs_info = fs_info;
7638 seed_devs->fs_info = fs_info;
7640 mutex_unlock(&fs_devices->device_list_mutex);
7643 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7644 const struct btrfs_dev_stats_item *ptr,
7649 read_extent_buffer(eb, &val,
7650 offsetof(struct btrfs_dev_stats_item, values) +
7651 ((unsigned long)ptr) + (index * sizeof(u64)),
7656 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7657 struct btrfs_dev_stats_item *ptr,
7660 write_extent_buffer(eb, &val,
7661 offsetof(struct btrfs_dev_stats_item, values) +
7662 ((unsigned long)ptr) + (index * sizeof(u64)),
7666 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7667 struct btrfs_path *path)
7669 struct btrfs_dev_stats_item *ptr;
7670 struct extent_buffer *eb;
7671 struct btrfs_key key;
7675 if (!device->fs_info->dev_root)
7678 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7679 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7680 key.offset = device->devid;
7681 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7683 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7684 btrfs_dev_stat_set(device, i, 0);
7685 device->dev_stats_valid = 1;
7686 btrfs_release_path(path);
7687 return ret < 0 ? ret : 0;
7689 slot = path->slots[0];
7690 eb = path->nodes[0];
7691 item_size = btrfs_item_size_nr(eb, slot);
7693 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7695 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7696 if (item_size >= (1 + i) * sizeof(__le64))
7697 btrfs_dev_stat_set(device, i,
7698 btrfs_dev_stats_value(eb, ptr, i));
7700 btrfs_dev_stat_set(device, i, 0);
7703 device->dev_stats_valid = 1;
7704 btrfs_dev_stat_print_on_load(device);
7705 btrfs_release_path(path);
7710 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7712 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7713 struct btrfs_device *device;
7714 struct btrfs_path *path = NULL;
7717 path = btrfs_alloc_path();
7721 mutex_lock(&fs_devices->device_list_mutex);
7722 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7723 ret = btrfs_device_init_dev_stats(device, path);
7727 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7728 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7729 ret = btrfs_device_init_dev_stats(device, path);
7735 mutex_unlock(&fs_devices->device_list_mutex);
7737 btrfs_free_path(path);
7741 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7742 struct btrfs_device *device)
7744 struct btrfs_fs_info *fs_info = trans->fs_info;
7745 struct btrfs_root *dev_root = fs_info->dev_root;
7746 struct btrfs_path *path;
7747 struct btrfs_key key;
7748 struct extent_buffer *eb;
7749 struct btrfs_dev_stats_item *ptr;
7753 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7754 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7755 key.offset = device->devid;
7757 path = btrfs_alloc_path();
7760 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7762 btrfs_warn_in_rcu(fs_info,
7763 "error %d while searching for dev_stats item for device %s",
7764 ret, rcu_str_deref(device->name));
7769 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7770 /* need to delete old one and insert a new one */
7771 ret = btrfs_del_item(trans, dev_root, path);
7773 btrfs_warn_in_rcu(fs_info,
7774 "delete too small dev_stats item for device %s failed %d",
7775 rcu_str_deref(device->name), ret);
7782 /* need to insert a new item */
7783 btrfs_release_path(path);
7784 ret = btrfs_insert_empty_item(trans, dev_root, path,
7785 &key, sizeof(*ptr));
7787 btrfs_warn_in_rcu(fs_info,
7788 "insert dev_stats item for device %s failed %d",
7789 rcu_str_deref(device->name), ret);
7794 eb = path->nodes[0];
7795 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7796 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7797 btrfs_set_dev_stats_value(eb, ptr, i,
7798 btrfs_dev_stat_read(device, i));
7799 btrfs_mark_buffer_dirty(eb);
7802 btrfs_free_path(path);
7807 * called from commit_transaction. Writes all changed device stats to disk.
7809 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7811 struct btrfs_fs_info *fs_info = trans->fs_info;
7812 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7813 struct btrfs_device *device;
7817 mutex_lock(&fs_devices->device_list_mutex);
7818 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7819 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7820 if (!device->dev_stats_valid || stats_cnt == 0)
7825 * There is a LOAD-LOAD control dependency between the value of
7826 * dev_stats_ccnt and updating the on-disk values which requires
7827 * reading the in-memory counters. Such control dependencies
7828 * require explicit read memory barriers.
7830 * This memory barriers pairs with smp_mb__before_atomic in
7831 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7832 * barrier implied by atomic_xchg in
7833 * btrfs_dev_stats_read_and_reset
7837 ret = update_dev_stat_item(trans, device);
7839 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7841 mutex_unlock(&fs_devices->device_list_mutex);
7846 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7848 btrfs_dev_stat_inc(dev, index);
7849 btrfs_dev_stat_print_on_error(dev);
7852 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7854 if (!dev->dev_stats_valid)
7856 btrfs_err_rl_in_rcu(dev->fs_info,
7857 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7858 rcu_str_deref(dev->name),
7859 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7860 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7861 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7862 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7863 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7866 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7870 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7871 if (btrfs_dev_stat_read(dev, i) != 0)
7873 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7874 return; /* all values == 0, suppress message */
7876 btrfs_info_in_rcu(dev->fs_info,
7877 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7878 rcu_str_deref(dev->name),
7879 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7880 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7881 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7882 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7883 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7886 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7887 struct btrfs_ioctl_get_dev_stats *stats)
7889 struct btrfs_device *dev;
7890 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7893 mutex_lock(&fs_devices->device_list_mutex);
7894 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL);
7895 mutex_unlock(&fs_devices->device_list_mutex);
7898 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7900 } else if (!dev->dev_stats_valid) {
7901 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7903 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7904 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7905 if (stats->nr_items > i)
7907 btrfs_dev_stat_read_and_reset(dev, i);
7909 btrfs_dev_stat_set(dev, i, 0);
7911 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7912 current->comm, task_pid_nr(current));
7914 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7915 if (stats->nr_items > i)
7916 stats->values[i] = btrfs_dev_stat_read(dev, i);
7918 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7919 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7924 * Update the size and bytes used for each device where it changed. This is
7925 * delayed since we would otherwise get errors while writing out the
7928 * Must be invoked during transaction commit.
7930 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7932 struct btrfs_device *curr, *next;
7934 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7936 if (list_empty(&trans->dev_update_list))
7940 * We don't need the device_list_mutex here. This list is owned by the
7941 * transaction and the transaction must complete before the device is
7944 mutex_lock(&trans->fs_info->chunk_mutex);
7945 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7947 list_del_init(&curr->post_commit_list);
7948 curr->commit_total_bytes = curr->disk_total_bytes;
7949 curr->commit_bytes_used = curr->bytes_used;
7951 mutex_unlock(&trans->fs_info->chunk_mutex);
7955 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7957 int btrfs_bg_type_to_factor(u64 flags)
7959 const int index = btrfs_bg_flags_to_raid_index(flags);
7961 return btrfs_raid_array[index].ncopies;
7966 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7967 u64 chunk_offset, u64 devid,
7968 u64 physical_offset, u64 physical_len)
7970 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7971 struct extent_map *em;
7972 struct map_lookup *map;
7973 struct btrfs_device *dev;
7979 read_lock(&em_tree->lock);
7980 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7981 read_unlock(&em_tree->lock);
7985 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7986 physical_offset, devid);
7991 map = em->map_lookup;
7992 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7993 if (physical_len != stripe_len) {
7995 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7996 physical_offset, devid, em->start, physical_len,
8002 for (i = 0; i < map->num_stripes; i++) {
8003 if (map->stripes[i].dev->devid == devid &&
8004 map->stripes[i].physical == physical_offset) {
8006 if (map->verified_stripes >= map->num_stripes) {
8008 "too many dev extents for chunk %llu found",
8013 map->verified_stripes++;
8019 "dev extent physical offset %llu devid %llu has no corresponding chunk",
8020 physical_offset, devid);
8024 /* Make sure no dev extent is beyond device boundary */
8025 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL);
8027 btrfs_err(fs_info, "failed to find devid %llu", devid);
8032 if (physical_offset + physical_len > dev->disk_total_bytes) {
8034 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
8035 devid, physical_offset, physical_len,
8036 dev->disk_total_bytes);
8041 if (dev->zone_info) {
8042 u64 zone_size = dev->zone_info->zone_size;
8044 if (!IS_ALIGNED(physical_offset, zone_size) ||
8045 !IS_ALIGNED(physical_len, zone_size)) {
8047 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
8048 devid, physical_offset, physical_len);
8055 free_extent_map(em);
8059 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
8061 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
8062 struct extent_map *em;
8063 struct rb_node *node;
8066 read_lock(&em_tree->lock);
8067 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
8068 em = rb_entry(node, struct extent_map, rb_node);
8069 if (em->map_lookup->num_stripes !=
8070 em->map_lookup->verified_stripes) {
8072 "chunk %llu has missing dev extent, have %d expect %d",
8073 em->start, em->map_lookup->verified_stripes,
8074 em->map_lookup->num_stripes);
8080 read_unlock(&em_tree->lock);
8085 * Ensure that all dev extents are mapped to correct chunk, otherwise
8086 * later chunk allocation/free would cause unexpected behavior.
8088 * NOTE: This will iterate through the whole device tree, which should be of
8089 * the same size level as the chunk tree. This slightly increases mount time.
8091 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
8093 struct btrfs_path *path;
8094 struct btrfs_root *root = fs_info->dev_root;
8095 struct btrfs_key key;
8097 u64 prev_dev_ext_end = 0;
8101 * We don't have a dev_root because we mounted with ignorebadroots and
8102 * failed to load the root, so we want to skip the verification in this
8105 * However if the dev root is fine, but the tree itself is corrupted
8106 * we'd still fail to mount. This verification is only to make sure
8107 * writes can happen safely, so instead just bypass this check
8108 * completely in the case of IGNOREBADROOTS.
8110 if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
8114 key.type = BTRFS_DEV_EXTENT_KEY;
8117 path = btrfs_alloc_path();
8121 path->reada = READA_FORWARD;
8122 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8126 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8127 ret = btrfs_next_leaf(root, path);
8130 /* No dev extents at all? Not good */
8137 struct extent_buffer *leaf = path->nodes[0];
8138 struct btrfs_dev_extent *dext;
8139 int slot = path->slots[0];
8141 u64 physical_offset;
8145 btrfs_item_key_to_cpu(leaf, &key, slot);
8146 if (key.type != BTRFS_DEV_EXTENT_KEY)
8148 devid = key.objectid;
8149 physical_offset = key.offset;
8151 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
8152 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
8153 physical_len = btrfs_dev_extent_length(leaf, dext);
8155 /* Check if this dev extent overlaps with the previous one */
8156 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
8158 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8159 devid, physical_offset, prev_dev_ext_end);
8164 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8165 physical_offset, physical_len);
8169 prev_dev_ext_end = physical_offset + physical_len;
8171 ret = btrfs_next_item(root, path);
8180 /* Ensure all chunks have corresponding dev extents */
8181 ret = verify_chunk_dev_extent_mapping(fs_info);
8183 btrfs_free_path(path);
8188 * Check whether the given block group or device is pinned by any inode being
8189 * used as a swapfile.
8191 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8193 struct btrfs_swapfile_pin *sp;
8194 struct rb_node *node;
8196 spin_lock(&fs_info->swapfile_pins_lock);
8197 node = fs_info->swapfile_pins.rb_node;
8199 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8201 node = node->rb_left;
8202 else if (ptr > sp->ptr)
8203 node = node->rb_right;
8207 spin_unlock(&fs_info->swapfile_pins_lock);
8208 return node != NULL;
8211 static int relocating_repair_kthread(void *data)
8213 struct btrfs_block_group *cache = (struct btrfs_block_group *)data;
8214 struct btrfs_fs_info *fs_info = cache->fs_info;
8218 target = cache->start;
8219 btrfs_put_block_group(cache);
8221 sb_start_write(fs_info->sb);
8222 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8224 "zoned: skip relocating block group %llu to repair: EBUSY",
8226 sb_end_write(fs_info->sb);
8230 mutex_lock(&fs_info->reclaim_bgs_lock);
8232 /* Ensure block group still exists */
8233 cache = btrfs_lookup_block_group(fs_info, target);
8237 if (!cache->relocating_repair)
8240 ret = btrfs_may_alloc_data_chunk(fs_info, target);
8245 "zoned: relocating block group %llu to repair IO failure",
8247 ret = btrfs_relocate_chunk(fs_info, target);
8251 btrfs_put_block_group(cache);
8252 mutex_unlock(&fs_info->reclaim_bgs_lock);
8253 btrfs_exclop_finish(fs_info);
8254 sb_end_write(fs_info->sb);
8259 int btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8261 struct btrfs_block_group *cache;
8263 /* Do not attempt to repair in degraded state */
8264 if (btrfs_test_opt(fs_info, DEGRADED))
8267 cache = btrfs_lookup_block_group(fs_info, logical);
8271 spin_lock(&cache->lock);
8272 if (cache->relocating_repair) {
8273 spin_unlock(&cache->lock);
8274 btrfs_put_block_group(cache);
8277 cache->relocating_repair = 1;
8278 spin_unlock(&cache->lock);
8280 kthread_run(relocating_repair_kthread, cache,
8281 "btrfs-relocating-repair");