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>
19 #include "extent_map.h"
21 #include "transaction.h"
22 #include "print-tree.h"
25 #include "async-thread.h"
26 #include "check-integrity.h"
27 #include "rcu-string.h"
28 #include "dev-replace.h"
30 #include "tree-checker.h"
31 #include "space-info.h"
32 #include "block-group.h"
36 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
37 [BTRFS_RAID_RAID10] = {
40 .devs_max = 0, /* 0 == as many as possible */
42 .tolerated_failures = 1,
46 .raid_name = "raid10",
47 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
48 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
50 [BTRFS_RAID_RAID1] = {
55 .tolerated_failures = 1,
60 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
61 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
63 [BTRFS_RAID_RAID1C3] = {
68 .tolerated_failures = 2,
72 .raid_name = "raid1c3",
73 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
74 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
76 [BTRFS_RAID_RAID1C4] = {
81 .tolerated_failures = 3,
85 .raid_name = "raid1c4",
86 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
87 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
94 .tolerated_failures = 0,
99 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
102 [BTRFS_RAID_RAID0] = {
107 .tolerated_failures = 0,
111 .raid_name = "raid0",
112 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
115 [BTRFS_RAID_SINGLE] = {
120 .tolerated_failures = 0,
124 .raid_name = "single",
128 [BTRFS_RAID_RAID5] = {
133 .tolerated_failures = 1,
137 .raid_name = "raid5",
138 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
139 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
141 [BTRFS_RAID_RAID6] = {
146 .tolerated_failures = 2,
150 .raid_name = "raid6",
151 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
152 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
156 const char *btrfs_bg_type_to_raid_name(u64 flags)
158 const int index = btrfs_bg_flags_to_raid_index(flags);
160 if (index >= BTRFS_NR_RAID_TYPES)
163 return btrfs_raid_array[index].raid_name;
167 * Fill @buf with textual description of @bg_flags, no more than @size_buf
168 * bytes including terminating null byte.
170 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
175 u64 flags = bg_flags;
176 u32 size_bp = size_buf;
183 #define DESCRIBE_FLAG(flag, desc) \
185 if (flags & (flag)) { \
186 ret = snprintf(bp, size_bp, "%s|", (desc)); \
187 if (ret < 0 || ret >= size_bp) \
195 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
196 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
197 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
199 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
200 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
201 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
202 btrfs_raid_array[i].raid_name);
206 ret = snprintf(bp, size_bp, "0x%llx|", flags);
210 if (size_bp < size_buf)
211 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
214 * The text is trimmed, it's up to the caller to provide sufficiently
220 static int init_first_rw_device(struct btrfs_trans_handle *trans);
221 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
222 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
223 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
224 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
225 enum btrfs_map_op op,
226 u64 logical, u64 *length,
227 struct btrfs_bio **bbio_ret,
228 int mirror_num, int need_raid_map);
234 * There are several mutexes that protect manipulation of devices and low-level
235 * structures like chunks but not block groups, extents or files
237 * uuid_mutex (global lock)
238 * ------------------------
239 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
240 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
241 * device) or requested by the device= mount option
243 * the mutex can be very coarse and can cover long-running operations
245 * protects: updates to fs_devices counters like missing devices, rw devices,
246 * seeding, structure cloning, opening/closing devices at mount/umount time
248 * global::fs_devs - add, remove, updates to the global list
250 * does not protect: manipulation of the fs_devices::devices list in general
251 * but in mount context it could be used to exclude list modifications by eg.
254 * btrfs_device::name - renames (write side), read is RCU
256 * fs_devices::device_list_mutex (per-fs, with RCU)
257 * ------------------------------------------------
258 * protects updates to fs_devices::devices, ie. adding and deleting
260 * simple list traversal with read-only actions can be done with RCU protection
262 * may be used to exclude some operations from running concurrently without any
263 * modifications to the list (see write_all_supers)
265 * Is not required at mount and close times, because our device list is
266 * protected by the uuid_mutex at that point.
270 * protects balance structures (status, state) and context accessed from
271 * several places (internally, ioctl)
275 * protects chunks, adding or removing during allocation, trim or when a new
276 * device is added/removed. Additionally it also protects post_commit_list of
277 * individual devices, since they can be added to the transaction's
278 * post_commit_list only with chunk_mutex held.
282 * a big lock that is held by the cleaner thread and prevents running subvolume
283 * cleaning together with relocation or delayed iputs
295 * Exclusive operations
296 * ====================
298 * Maintains the exclusivity of the following operations that apply to the
299 * whole filesystem and cannot run in parallel.
304 * - Device replace (*)
307 * The device operations (as above) can be in one of the following states:
313 * Only device operations marked with (*) can go into the Paused state for the
316 * - ioctl (only Balance can be Paused through ioctl)
317 * - filesystem remounted as read-only
318 * - filesystem unmounted and mounted as read-only
319 * - system power-cycle and filesystem mounted as read-only
320 * - filesystem or device errors leading to forced read-only
322 * The status of exclusive operation is set and cleared atomically.
323 * During the course of Paused state, fs_info::exclusive_operation remains set.
324 * A device operation in Paused or Running state can be canceled or resumed
325 * either by ioctl (Balance only) or when remounted as read-write.
326 * The exclusive status is cleared when the device operation is canceled or
330 DEFINE_MUTEX(uuid_mutex);
331 static LIST_HEAD(fs_uuids);
332 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
338 * alloc_fs_devices - allocate struct btrfs_fs_devices
339 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
340 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
342 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
343 * The returned struct is not linked onto any lists and can be destroyed with
344 * kfree() right away.
346 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
347 const u8 *metadata_fsid)
349 struct btrfs_fs_devices *fs_devs;
351 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
353 return ERR_PTR(-ENOMEM);
355 mutex_init(&fs_devs->device_list_mutex);
357 INIT_LIST_HEAD(&fs_devs->devices);
358 INIT_LIST_HEAD(&fs_devs->alloc_list);
359 INIT_LIST_HEAD(&fs_devs->fs_list);
360 INIT_LIST_HEAD(&fs_devs->seed_list);
362 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
365 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
367 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
372 void btrfs_free_device(struct btrfs_device *device)
374 WARN_ON(!list_empty(&device->post_commit_list));
375 rcu_string_free(device->name);
376 extent_io_tree_release(&device->alloc_state);
377 bio_put(device->flush_bio);
378 btrfs_destroy_dev_zone_info(device);
382 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
384 struct btrfs_device *device;
385 WARN_ON(fs_devices->opened);
386 while (!list_empty(&fs_devices->devices)) {
387 device = list_entry(fs_devices->devices.next,
388 struct btrfs_device, dev_list);
389 list_del(&device->dev_list);
390 btrfs_free_device(device);
395 void __exit btrfs_cleanup_fs_uuids(void)
397 struct btrfs_fs_devices *fs_devices;
399 while (!list_empty(&fs_uuids)) {
400 fs_devices = list_entry(fs_uuids.next,
401 struct btrfs_fs_devices, fs_list);
402 list_del(&fs_devices->fs_list);
403 free_fs_devices(fs_devices);
408 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
409 * Returned struct is not linked onto any lists and must be destroyed using
412 static struct btrfs_device *__alloc_device(struct btrfs_fs_info *fs_info)
414 struct btrfs_device *dev;
416 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
418 return ERR_PTR(-ENOMEM);
421 * Preallocate a bio that's always going to be used for flushing device
422 * barriers and matches the device lifespan
424 dev->flush_bio = bio_kmalloc(GFP_KERNEL, 0);
425 if (!dev->flush_bio) {
427 return ERR_PTR(-ENOMEM);
430 INIT_LIST_HEAD(&dev->dev_list);
431 INIT_LIST_HEAD(&dev->dev_alloc_list);
432 INIT_LIST_HEAD(&dev->post_commit_list);
434 atomic_set(&dev->reada_in_flight, 0);
435 atomic_set(&dev->dev_stats_ccnt, 0);
436 btrfs_device_data_ordered_init(dev);
437 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
438 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
439 extent_io_tree_init(fs_info, &dev->alloc_state,
440 IO_TREE_DEVICE_ALLOC_STATE, NULL);
445 static noinline struct btrfs_fs_devices *find_fsid(
446 const u8 *fsid, const u8 *metadata_fsid)
448 struct btrfs_fs_devices *fs_devices;
452 /* Handle non-split brain cases */
453 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
455 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
456 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
457 BTRFS_FSID_SIZE) == 0)
460 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
467 static struct btrfs_fs_devices *find_fsid_with_metadata_uuid(
468 struct btrfs_super_block *disk_super)
471 struct btrfs_fs_devices *fs_devices;
474 * Handle scanned device having completed its fsid change but
475 * belonging to a fs_devices that was created by first scanning
476 * a device which didn't have its fsid/metadata_uuid changed
477 * at all and the CHANGING_FSID_V2 flag set.
479 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
480 if (fs_devices->fsid_change &&
481 memcmp(disk_super->metadata_uuid, fs_devices->fsid,
482 BTRFS_FSID_SIZE) == 0 &&
483 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
484 BTRFS_FSID_SIZE) == 0) {
489 * Handle scanned device having completed its fsid change but
490 * belonging to a fs_devices that was created by a device that
491 * has an outdated pair of fsid/metadata_uuid and
492 * CHANGING_FSID_V2 flag set.
494 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
495 if (fs_devices->fsid_change &&
496 memcmp(fs_devices->metadata_uuid,
497 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
498 memcmp(disk_super->metadata_uuid, fs_devices->metadata_uuid,
499 BTRFS_FSID_SIZE) == 0) {
504 return find_fsid(disk_super->fsid, disk_super->metadata_uuid);
509 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
510 int flush, struct block_device **bdev,
511 struct btrfs_super_block **disk_super)
515 *bdev = blkdev_get_by_path(device_path, flags, holder);
518 ret = PTR_ERR(*bdev);
523 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
524 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
526 blkdev_put(*bdev, flags);
529 invalidate_bdev(*bdev);
530 *disk_super = btrfs_read_dev_super(*bdev);
531 if (IS_ERR(*disk_super)) {
532 ret = PTR_ERR(*disk_super);
533 blkdev_put(*bdev, flags);
544 static bool device_path_matched(const char *path, struct btrfs_device *device)
549 found = strcmp(rcu_str_deref(device->name), path);
556 * Search and remove all stale (devices which are not mounted) devices.
557 * When both inputs are NULL, it will search and release all stale devices.
558 * path: Optional. When provided will it release all unmounted devices
559 * matching this path only.
560 * skip_dev: Optional. Will skip this device when searching for the stale
562 * Return: 0 for success or if @path is NULL.
563 * -EBUSY if @path is a mounted device.
564 * -ENOENT if @path does not match any device in the list.
566 static int btrfs_free_stale_devices(const char *path,
567 struct btrfs_device *skip_device)
569 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
570 struct btrfs_device *device, *tmp_device;
576 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
578 mutex_lock(&fs_devices->device_list_mutex);
579 list_for_each_entry_safe(device, tmp_device,
580 &fs_devices->devices, dev_list) {
581 if (skip_device && skip_device == device)
583 if (path && !device->name)
585 if (path && !device_path_matched(path, device))
587 if (fs_devices->opened) {
588 /* for an already deleted device return 0 */
589 if (path && ret != 0)
594 /* delete the stale device */
595 fs_devices->num_devices--;
596 list_del(&device->dev_list);
597 btrfs_free_device(device);
601 mutex_unlock(&fs_devices->device_list_mutex);
603 if (fs_devices->num_devices == 0) {
604 btrfs_sysfs_remove_fsid(fs_devices);
605 list_del(&fs_devices->fs_list);
606 free_fs_devices(fs_devices);
614 * This is only used on mount, and we are protected from competing things
615 * messing with our fs_devices by the uuid_mutex, thus we do not need the
616 * fs_devices->device_list_mutex here.
618 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
619 struct btrfs_device *device, fmode_t flags,
622 struct request_queue *q;
623 struct block_device *bdev;
624 struct btrfs_super_block *disk_super;
633 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
638 devid = btrfs_stack_device_id(&disk_super->dev_item);
639 if (devid != device->devid)
640 goto error_free_page;
642 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
643 goto error_free_page;
645 device->generation = btrfs_super_generation(disk_super);
647 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
648 if (btrfs_super_incompat_flags(disk_super) &
649 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
651 "BTRFS: Invalid seeding and uuid-changed device detected\n");
652 goto error_free_page;
655 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
656 fs_devices->seeding = true;
658 if (bdev_read_only(bdev))
659 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
661 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
664 q = bdev_get_queue(bdev);
665 if (!blk_queue_nonrot(q))
666 fs_devices->rotating = true;
669 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
670 device->mode = flags;
672 fs_devices->open_devices++;
673 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
674 device->devid != BTRFS_DEV_REPLACE_DEVID) {
675 fs_devices->rw_devices++;
676 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
678 btrfs_release_disk_super(disk_super);
683 btrfs_release_disk_super(disk_super);
684 blkdev_put(bdev, flags);
690 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
691 * being created with a disk that has already completed its fsid change. Such
692 * disk can belong to an fs which has its FSID changed or to one which doesn't.
693 * Handle both cases here.
695 static struct btrfs_fs_devices *find_fsid_inprogress(
696 struct btrfs_super_block *disk_super)
698 struct btrfs_fs_devices *fs_devices;
700 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
701 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
702 BTRFS_FSID_SIZE) != 0 &&
703 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
704 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
709 return find_fsid(disk_super->fsid, NULL);
713 static struct btrfs_fs_devices *find_fsid_changed(
714 struct btrfs_super_block *disk_super)
716 struct btrfs_fs_devices *fs_devices;
719 * Handles the case where scanned device is part of an fs that had
720 * multiple successful changes of FSID but curently device didn't
721 * observe it. Meaning our fsid will be different than theirs. We need
722 * to handle two subcases :
723 * 1 - The fs still continues to have different METADATA/FSID uuids.
724 * 2 - The fs is switched back to its original FSID (METADATA/FSID
727 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
729 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
730 BTRFS_FSID_SIZE) != 0 &&
731 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
732 BTRFS_FSID_SIZE) == 0 &&
733 memcmp(fs_devices->fsid, disk_super->fsid,
734 BTRFS_FSID_SIZE) != 0)
737 /* Unchanged UUIDs */
738 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
739 BTRFS_FSID_SIZE) == 0 &&
740 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
741 BTRFS_FSID_SIZE) == 0)
748 static struct btrfs_fs_devices *find_fsid_reverted_metadata(
749 struct btrfs_super_block *disk_super)
751 struct btrfs_fs_devices *fs_devices;
754 * Handle the case where the scanned device is part of an fs whose last
755 * metadata UUID change reverted it to the original FSID. At the same
756 * time * fs_devices was first created by another constitutent device
757 * which didn't fully observe the operation. This results in an
758 * btrfs_fs_devices created with metadata/fsid different AND
759 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
760 * fs_devices equal to the FSID of the disk.
762 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
763 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
764 BTRFS_FSID_SIZE) != 0 &&
765 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
766 BTRFS_FSID_SIZE) == 0 &&
767 fs_devices->fsid_change)
774 * Add new device to list of registered devices
777 * device pointer which was just added or updated when successful
778 * error pointer when failed
780 static noinline struct btrfs_device *device_list_add(const char *path,
781 struct btrfs_super_block *disk_super,
782 bool *new_device_added)
784 struct btrfs_device *device;
785 struct btrfs_fs_devices *fs_devices = NULL;
786 struct rcu_string *name;
787 u64 found_transid = btrfs_super_generation(disk_super);
788 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
789 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
790 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
791 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
792 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
794 if (fsid_change_in_progress) {
795 if (!has_metadata_uuid)
796 fs_devices = find_fsid_inprogress(disk_super);
798 fs_devices = find_fsid_changed(disk_super);
799 } else if (has_metadata_uuid) {
800 fs_devices = find_fsid_with_metadata_uuid(disk_super);
802 fs_devices = find_fsid_reverted_metadata(disk_super);
804 fs_devices = find_fsid(disk_super->fsid, NULL);
809 if (has_metadata_uuid)
810 fs_devices = alloc_fs_devices(disk_super->fsid,
811 disk_super->metadata_uuid);
813 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
815 if (IS_ERR(fs_devices))
816 return ERR_CAST(fs_devices);
818 fs_devices->fsid_change = fsid_change_in_progress;
820 mutex_lock(&fs_devices->device_list_mutex);
821 list_add(&fs_devices->fs_list, &fs_uuids);
825 mutex_lock(&fs_devices->device_list_mutex);
826 device = btrfs_find_device(fs_devices, devid,
827 disk_super->dev_item.uuid, NULL);
830 * If this disk has been pulled into an fs devices created by
831 * a device which had the CHANGING_FSID_V2 flag then replace the
832 * metadata_uuid/fsid values of the fs_devices.
834 if (fs_devices->fsid_change &&
835 found_transid > fs_devices->latest_generation) {
836 memcpy(fs_devices->fsid, disk_super->fsid,
839 if (has_metadata_uuid)
840 memcpy(fs_devices->metadata_uuid,
841 disk_super->metadata_uuid,
844 memcpy(fs_devices->metadata_uuid,
845 disk_super->fsid, BTRFS_FSID_SIZE);
847 fs_devices->fsid_change = false;
852 if (fs_devices->opened) {
853 mutex_unlock(&fs_devices->device_list_mutex);
854 return ERR_PTR(-EBUSY);
857 device = btrfs_alloc_device(NULL, &devid,
858 disk_super->dev_item.uuid);
859 if (IS_ERR(device)) {
860 mutex_unlock(&fs_devices->device_list_mutex);
861 /* we can safely leave the fs_devices entry around */
865 name = rcu_string_strdup(path, GFP_NOFS);
867 btrfs_free_device(device);
868 mutex_unlock(&fs_devices->device_list_mutex);
869 return ERR_PTR(-ENOMEM);
871 rcu_assign_pointer(device->name, name);
873 list_add_rcu(&device->dev_list, &fs_devices->devices);
874 fs_devices->num_devices++;
876 device->fs_devices = fs_devices;
877 *new_device_added = true;
879 if (disk_super->label[0])
881 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
882 disk_super->label, devid, found_transid, path,
883 current->comm, task_pid_nr(current));
886 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
887 disk_super->fsid, devid, found_transid, path,
888 current->comm, task_pid_nr(current));
890 } else if (!device->name || strcmp(device->name->str, path)) {
892 * When FS is already mounted.
893 * 1. If you are here and if the device->name is NULL that
894 * means this device was missing at time of FS mount.
895 * 2. If you are here and if the device->name is different
896 * from 'path' that means either
897 * a. The same device disappeared and reappeared with
899 * b. The missing-disk-which-was-replaced, has
902 * We must allow 1 and 2a above. But 2b would be a spurious
905 * Further in case of 1 and 2a above, the disk at 'path'
906 * would have missed some transaction when it was away and
907 * in case of 2a the stale bdev has to be updated as well.
908 * 2b must not be allowed at all time.
912 * For now, we do allow update to btrfs_fs_device through the
913 * btrfs dev scan cli after FS has been mounted. We're still
914 * tracking a problem where systems fail mount by subvolume id
915 * when we reject replacement on a mounted FS.
917 if (!fs_devices->opened && found_transid < device->generation) {
919 * That is if the FS is _not_ mounted and if you
920 * are here, that means there is more than one
921 * disk with same uuid and devid.We keep the one
922 * with larger generation number or the last-in if
923 * generation are equal.
925 mutex_unlock(&fs_devices->device_list_mutex);
926 return ERR_PTR(-EEXIST);
930 * We are going to replace the device path for a given devid,
931 * make sure it's the same device if the device is mounted
937 error = lookup_bdev(path, &path_dev);
939 mutex_unlock(&fs_devices->device_list_mutex);
940 return ERR_PTR(error);
943 if (device->bdev->bd_dev != path_dev) {
944 mutex_unlock(&fs_devices->device_list_mutex);
946 * device->fs_info may not be reliable here, so
947 * pass in a NULL instead. This avoids a
948 * possible use-after-free when the fs_info and
949 * fs_info->sb are already torn down.
951 btrfs_warn_in_rcu(NULL,
952 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
953 path, devid, found_transid,
955 task_pid_nr(current));
956 return ERR_PTR(-EEXIST);
958 btrfs_info_in_rcu(device->fs_info,
959 "devid %llu device path %s changed to %s scanned by %s (%d)",
960 devid, rcu_str_deref(device->name),
962 task_pid_nr(current));
965 name = rcu_string_strdup(path, GFP_NOFS);
967 mutex_unlock(&fs_devices->device_list_mutex);
968 return ERR_PTR(-ENOMEM);
970 rcu_string_free(device->name);
971 rcu_assign_pointer(device->name, name);
972 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
973 fs_devices->missing_devices--;
974 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
979 * Unmount does not free the btrfs_device struct but would zero
980 * generation along with most of the other members. So just update
981 * it back. We need it to pick the disk with largest generation
984 if (!fs_devices->opened) {
985 device->generation = found_transid;
986 fs_devices->latest_generation = max_t(u64, found_transid,
987 fs_devices->latest_generation);
990 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
992 mutex_unlock(&fs_devices->device_list_mutex);
996 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
998 struct btrfs_fs_devices *fs_devices;
999 struct btrfs_device *device;
1000 struct btrfs_device *orig_dev;
1003 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1004 if (IS_ERR(fs_devices))
1007 mutex_lock(&orig->device_list_mutex);
1008 fs_devices->total_devices = orig->total_devices;
1010 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1011 struct rcu_string *name;
1013 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1015 if (IS_ERR(device)) {
1016 ret = PTR_ERR(device);
1021 * This is ok to do without rcu read locked because we hold the
1022 * uuid mutex so nothing we touch in here is going to disappear.
1024 if (orig_dev->name) {
1025 name = rcu_string_strdup(orig_dev->name->str,
1028 btrfs_free_device(device);
1032 rcu_assign_pointer(device->name, name);
1035 list_add(&device->dev_list, &fs_devices->devices);
1036 device->fs_devices = fs_devices;
1037 fs_devices->num_devices++;
1039 mutex_unlock(&orig->device_list_mutex);
1042 mutex_unlock(&orig->device_list_mutex);
1043 free_fs_devices(fs_devices);
1044 return ERR_PTR(ret);
1047 static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
1048 struct btrfs_device **latest_dev)
1050 struct btrfs_device *device, *next;
1052 /* This is the initialized path, it is safe to release the devices. */
1053 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1054 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
1055 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1056 &device->dev_state) &&
1057 !test_bit(BTRFS_DEV_STATE_MISSING,
1058 &device->dev_state) &&
1060 device->generation > (*latest_dev)->generation)) {
1061 *latest_dev = device;
1067 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1068 * in btrfs_init_dev_replace() so just continue.
1070 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1074 blkdev_put(device->bdev, device->mode);
1075 device->bdev = NULL;
1076 fs_devices->open_devices--;
1078 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1079 list_del_init(&device->dev_alloc_list);
1080 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1082 list_del_init(&device->dev_list);
1083 fs_devices->num_devices--;
1084 btrfs_free_device(device);
1090 * After we have read the system tree and know devids belonging to this
1091 * filesystem, remove the device which does not belong there.
1093 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices)
1095 struct btrfs_device *latest_dev = NULL;
1096 struct btrfs_fs_devices *seed_dev;
1098 mutex_lock(&uuid_mutex);
1099 __btrfs_free_extra_devids(fs_devices, &latest_dev);
1101 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1102 __btrfs_free_extra_devids(seed_dev, &latest_dev);
1104 fs_devices->latest_bdev = latest_dev->bdev;
1106 mutex_unlock(&uuid_mutex);
1109 static void btrfs_close_bdev(struct btrfs_device *device)
1114 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1115 sync_blockdev(device->bdev);
1116 invalidate_bdev(device->bdev);
1119 blkdev_put(device->bdev, device->mode);
1122 static void btrfs_close_one_device(struct btrfs_device *device)
1124 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1126 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1127 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1128 list_del_init(&device->dev_alloc_list);
1129 fs_devices->rw_devices--;
1132 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1133 fs_devices->missing_devices--;
1135 btrfs_close_bdev(device);
1137 fs_devices->open_devices--;
1138 device->bdev = NULL;
1140 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1141 btrfs_destroy_dev_zone_info(device);
1143 device->fs_info = NULL;
1144 atomic_set(&device->dev_stats_ccnt, 0);
1145 extent_io_tree_release(&device->alloc_state);
1147 /* Verify the device is back in a pristine state */
1148 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1149 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1150 ASSERT(list_empty(&device->dev_alloc_list));
1151 ASSERT(list_empty(&device->post_commit_list));
1152 ASSERT(atomic_read(&device->reada_in_flight) == 0);
1155 static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
1157 struct btrfs_device *device, *tmp;
1159 lockdep_assert_held(&uuid_mutex);
1161 if (--fs_devices->opened > 0)
1164 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
1165 btrfs_close_one_device(device);
1167 WARN_ON(fs_devices->open_devices);
1168 WARN_ON(fs_devices->rw_devices);
1169 fs_devices->opened = 0;
1170 fs_devices->seeding = false;
1171 fs_devices->fs_info = NULL;
1174 void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1177 struct btrfs_fs_devices *tmp;
1179 mutex_lock(&uuid_mutex);
1180 close_fs_devices(fs_devices);
1181 if (!fs_devices->opened)
1182 list_splice_init(&fs_devices->seed_list, &list);
1184 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
1185 close_fs_devices(fs_devices);
1186 list_del(&fs_devices->seed_list);
1187 free_fs_devices(fs_devices);
1189 mutex_unlock(&uuid_mutex);
1192 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1193 fmode_t flags, void *holder)
1195 struct btrfs_device *device;
1196 struct btrfs_device *latest_dev = NULL;
1197 struct btrfs_device *tmp_device;
1199 flags |= FMODE_EXCL;
1201 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1205 ret = btrfs_open_one_device(fs_devices, device, flags, holder);
1207 (!latest_dev || device->generation > latest_dev->generation)) {
1208 latest_dev = device;
1209 } else if (ret == -ENODATA) {
1210 fs_devices->num_devices--;
1211 list_del(&device->dev_list);
1212 btrfs_free_device(device);
1215 if (fs_devices->open_devices == 0)
1218 fs_devices->opened = 1;
1219 fs_devices->latest_bdev = latest_dev->bdev;
1220 fs_devices->total_rw_bytes = 0;
1221 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1222 fs_devices->read_policy = BTRFS_READ_POLICY_PID;
1227 static int devid_cmp(void *priv, const struct list_head *a,
1228 const struct list_head *b)
1230 struct btrfs_device *dev1, *dev2;
1232 dev1 = list_entry(a, struct btrfs_device, dev_list);
1233 dev2 = list_entry(b, struct btrfs_device, dev_list);
1235 if (dev1->devid < dev2->devid)
1237 else if (dev1->devid > dev2->devid)
1242 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1243 fmode_t flags, void *holder)
1247 lockdep_assert_held(&uuid_mutex);
1249 * The device_list_mutex cannot be taken here in case opening the
1250 * underlying device takes further locks like bd_mutex.
1252 * We also don't need the lock here as this is called during mount and
1253 * exclusion is provided by uuid_mutex
1256 if (fs_devices->opened) {
1257 fs_devices->opened++;
1260 list_sort(NULL, &fs_devices->devices, devid_cmp);
1261 ret = open_fs_devices(fs_devices, flags, holder);
1267 void btrfs_release_disk_super(struct btrfs_super_block *super)
1269 struct page *page = virt_to_page(super);
1274 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1275 u64 bytenr, u64 bytenr_orig)
1277 struct btrfs_super_block *disk_super;
1282 /* make sure our super fits in the device */
1283 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1284 return ERR_PTR(-EINVAL);
1286 /* make sure our super fits in the page */
1287 if (sizeof(*disk_super) > PAGE_SIZE)
1288 return ERR_PTR(-EINVAL);
1290 /* make sure our super doesn't straddle pages on disk */
1291 index = bytenr >> PAGE_SHIFT;
1292 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1293 return ERR_PTR(-EINVAL);
1295 /* pull in the page with our super */
1296 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1299 return ERR_CAST(page);
1301 p = page_address(page);
1303 /* align our pointer to the offset of the super block */
1304 disk_super = p + offset_in_page(bytenr);
1306 if (btrfs_super_bytenr(disk_super) != bytenr_orig ||
1307 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1308 btrfs_release_disk_super(p);
1309 return ERR_PTR(-EINVAL);
1312 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1313 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1318 int btrfs_forget_devices(const char *path)
1322 mutex_lock(&uuid_mutex);
1323 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1324 mutex_unlock(&uuid_mutex);
1330 * Look for a btrfs signature on a device. This may be called out of the mount path
1331 * and we are not allowed to call set_blocksize during the scan. The superblock
1332 * is read via pagecache
1334 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1337 struct btrfs_super_block *disk_super;
1338 bool new_device_added = false;
1339 struct btrfs_device *device = NULL;
1340 struct block_device *bdev;
1341 u64 bytenr, bytenr_orig;
1344 lockdep_assert_held(&uuid_mutex);
1347 * we would like to check all the supers, but that would make
1348 * a btrfs mount succeed after a mkfs from a different FS.
1349 * So, we need to add a special mount option to scan for
1350 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1352 flags |= FMODE_EXCL;
1354 bdev = blkdev_get_by_path(path, flags, holder);
1356 return ERR_CAST(bdev);
1358 bytenr_orig = btrfs_sb_offset(0);
1359 ret = btrfs_sb_log_location_bdev(bdev, 0, READ, &bytenr);
1361 return ERR_PTR(ret);
1363 disk_super = btrfs_read_disk_super(bdev, bytenr, bytenr_orig);
1364 if (IS_ERR(disk_super)) {
1365 device = ERR_CAST(disk_super);
1366 goto error_bdev_put;
1369 device = device_list_add(path, disk_super, &new_device_added);
1370 if (!IS_ERR(device)) {
1371 if (new_device_added)
1372 btrfs_free_stale_devices(path, device);
1375 btrfs_release_disk_super(disk_super);
1378 blkdev_put(bdev, flags);
1384 * Try to find a chunk that intersects [start, start + len] range and when one
1385 * such is found, record the end of it in *start
1387 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1390 u64 physical_start, physical_end;
1392 lockdep_assert_held(&device->fs_info->chunk_mutex);
1394 if (!find_first_extent_bit(&device->alloc_state, *start,
1395 &physical_start, &physical_end,
1396 CHUNK_ALLOCATED, NULL)) {
1398 if (in_range(physical_start, *start, len) ||
1399 in_range(*start, physical_start,
1400 physical_end - physical_start)) {
1401 *start = physical_end + 1;
1408 static u64 dev_extent_search_start(struct btrfs_device *device, u64 start)
1410 switch (device->fs_devices->chunk_alloc_policy) {
1411 case BTRFS_CHUNK_ALLOC_REGULAR:
1413 * We don't want to overwrite the superblock on the drive nor
1414 * any area used by the boot loader (grub for example), so we
1415 * make sure to start at an offset of at least 1MB.
1417 return max_t(u64, start, SZ_1M);
1418 case BTRFS_CHUNK_ALLOC_ZONED:
1420 * We don't care about the starting region like regular
1421 * allocator, because we anyway use/reserve the first two zones
1422 * for superblock logging.
1424 return ALIGN(start, device->zone_info->zone_size);
1430 static bool dev_extent_hole_check_zoned(struct btrfs_device *device,
1431 u64 *hole_start, u64 *hole_size,
1434 u64 zone_size = device->zone_info->zone_size;
1437 bool changed = false;
1439 ASSERT(IS_ALIGNED(*hole_start, zone_size));
1441 while (*hole_size > 0) {
1442 pos = btrfs_find_allocatable_zones(device, *hole_start,
1443 *hole_start + *hole_size,
1445 if (pos != *hole_start) {
1446 *hole_size = *hole_start + *hole_size - pos;
1449 if (*hole_size < num_bytes)
1453 ret = btrfs_ensure_empty_zones(device, pos, num_bytes);
1455 /* Range is ensured to be empty */
1459 /* Given hole range was invalid (outside of device) */
1460 if (ret == -ERANGE) {
1461 *hole_start += *hole_size;
1466 *hole_start += zone_size;
1467 *hole_size -= zone_size;
1475 * dev_extent_hole_check - check if specified hole is suitable for allocation
1476 * @device: the device which we have the hole
1477 * @hole_start: starting position of the hole
1478 * @hole_size: the size of the hole
1479 * @num_bytes: the size of the free space that we need
1481 * This function may modify @hole_start and @hole_size to reflect the suitable
1482 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1484 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1485 u64 *hole_size, u64 num_bytes)
1487 bool changed = false;
1488 u64 hole_end = *hole_start + *hole_size;
1492 * Check before we set max_hole_start, otherwise we could end up
1493 * sending back this offset anyway.
1495 if (contains_pending_extent(device, hole_start, *hole_size)) {
1496 if (hole_end >= *hole_start)
1497 *hole_size = hole_end - *hole_start;
1503 switch (device->fs_devices->chunk_alloc_policy) {
1504 case BTRFS_CHUNK_ALLOC_REGULAR:
1505 /* No extra check */
1507 case BTRFS_CHUNK_ALLOC_ZONED:
1508 if (dev_extent_hole_check_zoned(device, hole_start,
1509 hole_size, num_bytes)) {
1512 * The changed hole can contain pending extent.
1513 * Loop again to check that.
1529 * find_free_dev_extent_start - find free space in the specified device
1530 * @device: the device which we search the free space in
1531 * @num_bytes: the size of the free space that we need
1532 * @search_start: the position from which to begin the search
1533 * @start: store the start of the free space.
1534 * @len: the size of the free space. that we find, or the size
1535 * of the max free space if we don't find suitable free space
1537 * this uses a pretty simple search, the expectation is that it is
1538 * called very infrequently and that a given device has a small number
1541 * @start is used to store the start of the free space if we find. But if we
1542 * don't find suitable free space, it will be used to store the start position
1543 * of the max free space.
1545 * @len is used to store the size of the free space that we find.
1546 * But if we don't find suitable free space, it is used to store the size of
1547 * the max free space.
1549 * NOTE: This function will search *commit* root of device tree, and does extra
1550 * check to ensure dev extents are not double allocated.
1551 * This makes the function safe to allocate dev extents but may not report
1552 * correct usable device space, as device extent freed in current transaction
1553 * is not reported as avaiable.
1555 static int find_free_dev_extent_start(struct btrfs_device *device,
1556 u64 num_bytes, u64 search_start, u64 *start,
1559 struct btrfs_fs_info *fs_info = device->fs_info;
1560 struct btrfs_root *root = fs_info->dev_root;
1561 struct btrfs_key key;
1562 struct btrfs_dev_extent *dev_extent;
1563 struct btrfs_path *path;
1568 u64 search_end = device->total_bytes;
1571 struct extent_buffer *l;
1573 search_start = dev_extent_search_start(device, search_start);
1575 WARN_ON(device->zone_info &&
1576 !IS_ALIGNED(num_bytes, device->zone_info->zone_size));
1578 path = btrfs_alloc_path();
1582 max_hole_start = search_start;
1586 if (search_start >= search_end ||
1587 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1592 path->reada = READA_FORWARD;
1593 path->search_commit_root = 1;
1594 path->skip_locking = 1;
1596 key.objectid = device->devid;
1597 key.offset = search_start;
1598 key.type = BTRFS_DEV_EXTENT_KEY;
1600 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1604 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1611 slot = path->slots[0];
1612 if (slot >= btrfs_header_nritems(l)) {
1613 ret = btrfs_next_leaf(root, path);
1621 btrfs_item_key_to_cpu(l, &key, slot);
1623 if (key.objectid < device->devid)
1626 if (key.objectid > device->devid)
1629 if (key.type != BTRFS_DEV_EXTENT_KEY)
1632 if (key.offset > search_start) {
1633 hole_size = key.offset - search_start;
1634 dev_extent_hole_check(device, &search_start, &hole_size,
1637 if (hole_size > max_hole_size) {
1638 max_hole_start = search_start;
1639 max_hole_size = hole_size;
1643 * If this free space is greater than which we need,
1644 * it must be the max free space that we have found
1645 * until now, so max_hole_start must point to the start
1646 * of this free space and the length of this free space
1647 * is stored in max_hole_size. Thus, we return
1648 * max_hole_start and max_hole_size and go back to the
1651 if (hole_size >= num_bytes) {
1657 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1658 extent_end = key.offset + btrfs_dev_extent_length(l,
1660 if (extent_end > search_start)
1661 search_start = extent_end;
1668 * At this point, search_start should be the end of
1669 * allocated dev extents, and when shrinking the device,
1670 * search_end may be smaller than search_start.
1672 if (search_end > search_start) {
1673 hole_size = search_end - search_start;
1674 if (dev_extent_hole_check(device, &search_start, &hole_size,
1676 btrfs_release_path(path);
1680 if (hole_size > max_hole_size) {
1681 max_hole_start = search_start;
1682 max_hole_size = hole_size;
1687 if (max_hole_size < num_bytes)
1693 btrfs_free_path(path);
1694 *start = max_hole_start;
1696 *len = max_hole_size;
1700 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1701 u64 *start, u64 *len)
1703 /* FIXME use last free of some kind */
1704 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1707 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1708 struct btrfs_device *device,
1709 u64 start, u64 *dev_extent_len)
1711 struct btrfs_fs_info *fs_info = device->fs_info;
1712 struct btrfs_root *root = fs_info->dev_root;
1714 struct btrfs_path *path;
1715 struct btrfs_key key;
1716 struct btrfs_key found_key;
1717 struct extent_buffer *leaf = NULL;
1718 struct btrfs_dev_extent *extent = NULL;
1720 path = btrfs_alloc_path();
1724 key.objectid = device->devid;
1726 key.type = BTRFS_DEV_EXTENT_KEY;
1728 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1730 ret = btrfs_previous_item(root, path, key.objectid,
1731 BTRFS_DEV_EXTENT_KEY);
1734 leaf = path->nodes[0];
1735 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1736 extent = btrfs_item_ptr(leaf, path->slots[0],
1737 struct btrfs_dev_extent);
1738 BUG_ON(found_key.offset > start || found_key.offset +
1739 btrfs_dev_extent_length(leaf, extent) < start);
1741 btrfs_release_path(path);
1743 } else if (ret == 0) {
1744 leaf = path->nodes[0];
1745 extent = btrfs_item_ptr(leaf, path->slots[0],
1746 struct btrfs_dev_extent);
1748 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1752 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1754 ret = btrfs_del_item(trans, root, path);
1756 btrfs_handle_fs_error(fs_info, ret,
1757 "Failed to remove dev extent item");
1759 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1762 btrfs_free_path(path);
1766 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1767 struct btrfs_device *device,
1768 u64 chunk_offset, u64 start, u64 num_bytes)
1771 struct btrfs_path *path;
1772 struct btrfs_fs_info *fs_info = device->fs_info;
1773 struct btrfs_root *root = fs_info->dev_root;
1774 struct btrfs_dev_extent *extent;
1775 struct extent_buffer *leaf;
1776 struct btrfs_key key;
1778 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1779 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1780 path = btrfs_alloc_path();
1784 key.objectid = device->devid;
1786 key.type = BTRFS_DEV_EXTENT_KEY;
1787 ret = btrfs_insert_empty_item(trans, root, path, &key,
1792 leaf = path->nodes[0];
1793 extent = btrfs_item_ptr(leaf, path->slots[0],
1794 struct btrfs_dev_extent);
1795 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1796 BTRFS_CHUNK_TREE_OBJECTID);
1797 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1798 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1799 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1801 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1802 btrfs_mark_buffer_dirty(leaf);
1804 btrfs_free_path(path);
1808 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1810 struct extent_map_tree *em_tree;
1811 struct extent_map *em;
1815 em_tree = &fs_info->mapping_tree;
1816 read_lock(&em_tree->lock);
1817 n = rb_last(&em_tree->map.rb_root);
1819 em = rb_entry(n, struct extent_map, rb_node);
1820 ret = em->start + em->len;
1822 read_unlock(&em_tree->lock);
1827 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1831 struct btrfs_key key;
1832 struct btrfs_key found_key;
1833 struct btrfs_path *path;
1835 path = btrfs_alloc_path();
1839 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1840 key.type = BTRFS_DEV_ITEM_KEY;
1841 key.offset = (u64)-1;
1843 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1849 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1854 ret = btrfs_previous_item(fs_info->chunk_root, path,
1855 BTRFS_DEV_ITEMS_OBJECTID,
1856 BTRFS_DEV_ITEM_KEY);
1860 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1862 *devid_ret = found_key.offset + 1;
1866 btrfs_free_path(path);
1871 * the device information is stored in the chunk root
1872 * the btrfs_device struct should be fully filled in
1874 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1875 struct btrfs_device *device)
1878 struct btrfs_path *path;
1879 struct btrfs_dev_item *dev_item;
1880 struct extent_buffer *leaf;
1881 struct btrfs_key key;
1884 path = btrfs_alloc_path();
1888 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1889 key.type = BTRFS_DEV_ITEM_KEY;
1890 key.offset = device->devid;
1892 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1893 &key, sizeof(*dev_item));
1897 leaf = path->nodes[0];
1898 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1900 btrfs_set_device_id(leaf, dev_item, device->devid);
1901 btrfs_set_device_generation(leaf, dev_item, 0);
1902 btrfs_set_device_type(leaf, dev_item, device->type);
1903 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1904 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1905 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1906 btrfs_set_device_total_bytes(leaf, dev_item,
1907 btrfs_device_get_disk_total_bytes(device));
1908 btrfs_set_device_bytes_used(leaf, dev_item,
1909 btrfs_device_get_bytes_used(device));
1910 btrfs_set_device_group(leaf, dev_item, 0);
1911 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1912 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1913 btrfs_set_device_start_offset(leaf, dev_item, 0);
1915 ptr = btrfs_device_uuid(dev_item);
1916 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1917 ptr = btrfs_device_fsid(dev_item);
1918 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1919 ptr, BTRFS_FSID_SIZE);
1920 btrfs_mark_buffer_dirty(leaf);
1924 btrfs_free_path(path);
1929 * Function to update ctime/mtime for a given device path.
1930 * Mainly used for ctime/mtime based probe like libblkid.
1932 static void update_dev_time(const char *path_name)
1936 filp = filp_open(path_name, O_RDWR, 0);
1939 file_update_time(filp);
1940 filp_close(filp, NULL);
1943 static int btrfs_rm_dev_item(struct btrfs_device *device)
1945 struct btrfs_root *root = device->fs_info->chunk_root;
1947 struct btrfs_path *path;
1948 struct btrfs_key key;
1949 struct btrfs_trans_handle *trans;
1951 path = btrfs_alloc_path();
1955 trans = btrfs_start_transaction(root, 0);
1956 if (IS_ERR(trans)) {
1957 btrfs_free_path(path);
1958 return PTR_ERR(trans);
1960 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1961 key.type = BTRFS_DEV_ITEM_KEY;
1962 key.offset = device->devid;
1964 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1968 btrfs_abort_transaction(trans, ret);
1969 btrfs_end_transaction(trans);
1973 ret = btrfs_del_item(trans, root, path);
1975 btrfs_abort_transaction(trans, ret);
1976 btrfs_end_transaction(trans);
1980 btrfs_free_path(path);
1982 ret = btrfs_commit_transaction(trans);
1987 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1988 * filesystem. It's up to the caller to adjust that number regarding eg. device
1991 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1999 seq = read_seqbegin(&fs_info->profiles_lock);
2001 all_avail = fs_info->avail_data_alloc_bits |
2002 fs_info->avail_system_alloc_bits |
2003 fs_info->avail_metadata_alloc_bits;
2004 } while (read_seqretry(&fs_info->profiles_lock, seq));
2006 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2007 if (!(all_avail & btrfs_raid_array[i].bg_flag))
2010 if (num_devices < btrfs_raid_array[i].devs_min) {
2011 int ret = btrfs_raid_array[i].mindev_error;
2021 static struct btrfs_device * btrfs_find_next_active_device(
2022 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2024 struct btrfs_device *next_device;
2026 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2027 if (next_device != device &&
2028 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2029 && next_device->bdev)
2037 * Helper function to check if the given device is part of s_bdev / latest_bdev
2038 * and replace it with the provided or the next active device, in the context
2039 * where this function called, there should be always be another device (or
2040 * this_dev) which is active.
2042 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
2043 struct btrfs_device *next_device)
2045 struct btrfs_fs_info *fs_info = device->fs_info;
2048 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2050 ASSERT(next_device);
2052 if (fs_info->sb->s_bdev &&
2053 (fs_info->sb->s_bdev == device->bdev))
2054 fs_info->sb->s_bdev = next_device->bdev;
2056 if (fs_info->fs_devices->latest_bdev == device->bdev)
2057 fs_info->fs_devices->latest_bdev = next_device->bdev;
2061 * Return btrfs_fs_devices::num_devices excluding the device that's being
2062 * currently replaced.
2064 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2066 u64 num_devices = fs_info->fs_devices->num_devices;
2068 down_read(&fs_info->dev_replace.rwsem);
2069 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2070 ASSERT(num_devices > 1);
2073 up_read(&fs_info->dev_replace.rwsem);
2078 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2079 struct block_device *bdev,
2080 const char *device_path)
2082 struct btrfs_super_block *disk_super;
2088 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2092 disk_super = btrfs_read_dev_one_super(bdev, copy_num);
2093 if (IS_ERR(disk_super))
2096 if (bdev_is_zoned(bdev)) {
2097 btrfs_reset_sb_log_zones(bdev, copy_num);
2101 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
2103 page = virt_to_page(disk_super);
2104 set_page_dirty(page);
2106 /* write_on_page() unlocks the page */
2107 ret = write_one_page(page);
2110 "error clearing superblock number %d (%d)",
2112 btrfs_release_disk_super(disk_super);
2116 /* Notify udev that device has changed */
2117 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2119 /* Update ctime/mtime for device path for libblkid */
2120 update_dev_time(device_path);
2123 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2126 struct btrfs_device *device;
2127 struct btrfs_fs_devices *cur_devices;
2128 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2132 mutex_lock(&uuid_mutex);
2134 num_devices = btrfs_num_devices(fs_info);
2136 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2140 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2142 if (IS_ERR(device)) {
2143 if (PTR_ERR(device) == -ENOENT &&
2144 strcmp(device_path, "missing") == 0)
2145 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2147 ret = PTR_ERR(device);
2151 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2152 btrfs_warn_in_rcu(fs_info,
2153 "cannot remove device %s (devid %llu) due to active swapfile",
2154 rcu_str_deref(device->name), device->devid);
2159 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2160 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2164 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2165 fs_info->fs_devices->rw_devices == 1) {
2166 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2170 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2171 mutex_lock(&fs_info->chunk_mutex);
2172 list_del_init(&device->dev_alloc_list);
2173 device->fs_devices->rw_devices--;
2174 mutex_unlock(&fs_info->chunk_mutex);
2177 mutex_unlock(&uuid_mutex);
2178 ret = btrfs_shrink_device(device, 0);
2180 btrfs_reada_remove_dev(device);
2181 mutex_lock(&uuid_mutex);
2186 * TODO: the superblock still includes this device in its num_devices
2187 * counter although write_all_supers() is not locked out. This
2188 * could give a filesystem state which requires a degraded mount.
2190 ret = btrfs_rm_dev_item(device);
2194 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2195 btrfs_scrub_cancel_dev(device);
2198 * the device list mutex makes sure that we don't change
2199 * the device list while someone else is writing out all
2200 * the device supers. Whoever is writing all supers, should
2201 * lock the device list mutex before getting the number of
2202 * devices in the super block (super_copy). Conversely,
2203 * whoever updates the number of devices in the super block
2204 * (super_copy) should hold the device list mutex.
2208 * In normal cases the cur_devices == fs_devices. But in case
2209 * of deleting a seed device, the cur_devices should point to
2210 * its own fs_devices listed under the fs_devices->seed.
2212 cur_devices = device->fs_devices;
2213 mutex_lock(&fs_devices->device_list_mutex);
2214 list_del_rcu(&device->dev_list);
2216 cur_devices->num_devices--;
2217 cur_devices->total_devices--;
2218 /* Update total_devices of the parent fs_devices if it's seed */
2219 if (cur_devices != fs_devices)
2220 fs_devices->total_devices--;
2222 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2223 cur_devices->missing_devices--;
2225 btrfs_assign_next_active_device(device, NULL);
2228 cur_devices->open_devices--;
2229 /* remove sysfs entry */
2230 btrfs_sysfs_remove_device(device);
2233 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2234 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2235 mutex_unlock(&fs_devices->device_list_mutex);
2238 * at this point, the device is zero sized and detached from
2239 * the devices list. All that's left is to zero out the old
2240 * supers and free the device.
2242 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2243 btrfs_scratch_superblocks(fs_info, device->bdev,
2246 btrfs_close_bdev(device);
2248 btrfs_free_device(device);
2250 if (cur_devices->open_devices == 0) {
2251 list_del_init(&cur_devices->seed_list);
2252 close_fs_devices(cur_devices);
2253 free_fs_devices(cur_devices);
2257 mutex_unlock(&uuid_mutex);
2261 btrfs_reada_undo_remove_dev(device);
2262 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2263 mutex_lock(&fs_info->chunk_mutex);
2264 list_add(&device->dev_alloc_list,
2265 &fs_devices->alloc_list);
2266 device->fs_devices->rw_devices++;
2267 mutex_unlock(&fs_info->chunk_mutex);
2272 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2274 struct btrfs_fs_devices *fs_devices;
2276 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2279 * in case of fs with no seed, srcdev->fs_devices will point
2280 * to fs_devices of fs_info. However when the dev being replaced is
2281 * a seed dev it will point to the seed's local fs_devices. In short
2282 * srcdev will have its correct fs_devices in both the cases.
2284 fs_devices = srcdev->fs_devices;
2286 list_del_rcu(&srcdev->dev_list);
2287 list_del(&srcdev->dev_alloc_list);
2288 fs_devices->num_devices--;
2289 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2290 fs_devices->missing_devices--;
2292 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2293 fs_devices->rw_devices--;
2296 fs_devices->open_devices--;
2299 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2301 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2303 mutex_lock(&uuid_mutex);
2305 btrfs_close_bdev(srcdev);
2307 btrfs_free_device(srcdev);
2309 /* if this is no devs we rather delete the fs_devices */
2310 if (!fs_devices->num_devices) {
2312 * On a mounted FS, num_devices can't be zero unless it's a
2313 * seed. In case of a seed device being replaced, the replace
2314 * target added to the sprout FS, so there will be no more
2315 * device left under the seed FS.
2317 ASSERT(fs_devices->seeding);
2319 list_del_init(&fs_devices->seed_list);
2320 close_fs_devices(fs_devices);
2321 free_fs_devices(fs_devices);
2323 mutex_unlock(&uuid_mutex);
2326 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2328 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2330 mutex_lock(&fs_devices->device_list_mutex);
2332 btrfs_sysfs_remove_device(tgtdev);
2335 fs_devices->open_devices--;
2337 fs_devices->num_devices--;
2339 btrfs_assign_next_active_device(tgtdev, NULL);
2341 list_del_rcu(&tgtdev->dev_list);
2343 mutex_unlock(&fs_devices->device_list_mutex);
2346 * The update_dev_time() with in btrfs_scratch_superblocks()
2347 * may lead to a call to btrfs_show_devname() which will try
2348 * to hold device_list_mutex. And here this device
2349 * is already out of device list, so we don't have to hold
2350 * the device_list_mutex lock.
2352 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2355 btrfs_close_bdev(tgtdev);
2357 btrfs_free_device(tgtdev);
2360 static struct btrfs_device *btrfs_find_device_by_path(
2361 struct btrfs_fs_info *fs_info, const char *device_path)
2364 struct btrfs_super_block *disk_super;
2367 struct block_device *bdev;
2368 struct btrfs_device *device;
2370 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2371 fs_info->bdev_holder, 0, &bdev, &disk_super);
2373 return ERR_PTR(ret);
2375 devid = btrfs_stack_device_id(&disk_super->dev_item);
2376 dev_uuid = disk_super->dev_item.uuid;
2377 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2378 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2379 disk_super->metadata_uuid);
2381 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2384 btrfs_release_disk_super(disk_super);
2386 device = ERR_PTR(-ENOENT);
2387 blkdev_put(bdev, FMODE_READ);
2392 * Lookup a device given by device id, or the path if the id is 0.
2394 struct btrfs_device *btrfs_find_device_by_devspec(
2395 struct btrfs_fs_info *fs_info, u64 devid,
2396 const char *device_path)
2398 struct btrfs_device *device;
2401 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2404 return ERR_PTR(-ENOENT);
2408 if (!device_path || !device_path[0])
2409 return ERR_PTR(-EINVAL);
2411 if (strcmp(device_path, "missing") == 0) {
2412 /* Find first missing device */
2413 list_for_each_entry(device, &fs_info->fs_devices->devices,
2415 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2416 &device->dev_state) && !device->bdev)
2419 return ERR_PTR(-ENOENT);
2422 return btrfs_find_device_by_path(fs_info, device_path);
2426 * does all the dirty work required for changing file system's UUID.
2428 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2430 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2431 struct btrfs_fs_devices *old_devices;
2432 struct btrfs_fs_devices *seed_devices;
2433 struct btrfs_super_block *disk_super = fs_info->super_copy;
2434 struct btrfs_device *device;
2437 lockdep_assert_held(&uuid_mutex);
2438 if (!fs_devices->seeding)
2442 * Private copy of the seed devices, anchored at
2443 * fs_info->fs_devices->seed_list
2445 seed_devices = alloc_fs_devices(NULL, NULL);
2446 if (IS_ERR(seed_devices))
2447 return PTR_ERR(seed_devices);
2450 * It's necessary to retain a copy of the original seed fs_devices in
2451 * fs_uuids so that filesystems which have been seeded can successfully
2452 * reference the seed device from open_seed_devices. This also supports
2455 old_devices = clone_fs_devices(fs_devices);
2456 if (IS_ERR(old_devices)) {
2457 kfree(seed_devices);
2458 return PTR_ERR(old_devices);
2461 list_add(&old_devices->fs_list, &fs_uuids);
2463 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2464 seed_devices->opened = 1;
2465 INIT_LIST_HEAD(&seed_devices->devices);
2466 INIT_LIST_HEAD(&seed_devices->alloc_list);
2467 mutex_init(&seed_devices->device_list_mutex);
2469 mutex_lock(&fs_devices->device_list_mutex);
2470 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2472 list_for_each_entry(device, &seed_devices->devices, dev_list)
2473 device->fs_devices = seed_devices;
2475 fs_devices->seeding = false;
2476 fs_devices->num_devices = 0;
2477 fs_devices->open_devices = 0;
2478 fs_devices->missing_devices = 0;
2479 fs_devices->rotating = false;
2480 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2482 generate_random_uuid(fs_devices->fsid);
2483 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2484 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2485 mutex_unlock(&fs_devices->device_list_mutex);
2487 super_flags = btrfs_super_flags(disk_super) &
2488 ~BTRFS_SUPER_FLAG_SEEDING;
2489 btrfs_set_super_flags(disk_super, super_flags);
2495 * Store the expected generation for seed devices in device items.
2497 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2499 struct btrfs_fs_info *fs_info = trans->fs_info;
2500 struct btrfs_root *root = fs_info->chunk_root;
2501 struct btrfs_path *path;
2502 struct extent_buffer *leaf;
2503 struct btrfs_dev_item *dev_item;
2504 struct btrfs_device *device;
2505 struct btrfs_key key;
2506 u8 fs_uuid[BTRFS_FSID_SIZE];
2507 u8 dev_uuid[BTRFS_UUID_SIZE];
2511 path = btrfs_alloc_path();
2515 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2517 key.type = BTRFS_DEV_ITEM_KEY;
2520 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2524 leaf = path->nodes[0];
2526 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2527 ret = btrfs_next_leaf(root, path);
2532 leaf = path->nodes[0];
2533 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2534 btrfs_release_path(path);
2538 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2539 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2540 key.type != BTRFS_DEV_ITEM_KEY)
2543 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2544 struct btrfs_dev_item);
2545 devid = btrfs_device_id(leaf, dev_item);
2546 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2548 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2550 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2552 BUG_ON(!device); /* Logic error */
2554 if (device->fs_devices->seeding) {
2555 btrfs_set_device_generation(leaf, dev_item,
2556 device->generation);
2557 btrfs_mark_buffer_dirty(leaf);
2565 btrfs_free_path(path);
2569 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2571 struct btrfs_root *root = fs_info->dev_root;
2572 struct request_queue *q;
2573 struct btrfs_trans_handle *trans;
2574 struct btrfs_device *device;
2575 struct block_device *bdev;
2576 struct super_block *sb = fs_info->sb;
2577 struct rcu_string *name;
2578 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2579 u64 orig_super_total_bytes;
2580 u64 orig_super_num_devices;
2581 int seeding_dev = 0;
2583 bool locked = false;
2585 if (sb_rdonly(sb) && !fs_devices->seeding)
2588 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2589 fs_info->bdev_holder);
2591 return PTR_ERR(bdev);
2593 if (!btrfs_check_device_zone_type(fs_info, bdev)) {
2598 if (fs_devices->seeding) {
2600 down_write(&sb->s_umount);
2601 mutex_lock(&uuid_mutex);
2605 sync_blockdev(bdev);
2608 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2609 if (device->bdev == bdev) {
2617 device = btrfs_alloc_device(fs_info, NULL, NULL);
2618 if (IS_ERR(device)) {
2619 /* we can safely leave the fs_devices entry around */
2620 ret = PTR_ERR(device);
2624 name = rcu_string_strdup(device_path, GFP_KERNEL);
2627 goto error_free_device;
2629 rcu_assign_pointer(device->name, name);
2631 device->fs_info = fs_info;
2632 device->bdev = bdev;
2634 ret = btrfs_get_dev_zone_info(device);
2636 goto error_free_device;
2638 trans = btrfs_start_transaction(root, 0);
2639 if (IS_ERR(trans)) {
2640 ret = PTR_ERR(trans);
2641 goto error_free_zone;
2644 q = bdev_get_queue(bdev);
2645 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2646 device->generation = trans->transid;
2647 device->io_width = fs_info->sectorsize;
2648 device->io_align = fs_info->sectorsize;
2649 device->sector_size = fs_info->sectorsize;
2650 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2651 fs_info->sectorsize);
2652 device->disk_total_bytes = device->total_bytes;
2653 device->commit_total_bytes = device->total_bytes;
2654 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2655 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2656 device->mode = FMODE_EXCL;
2657 device->dev_stats_valid = 1;
2658 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2661 btrfs_clear_sb_rdonly(sb);
2662 ret = btrfs_prepare_sprout(fs_info);
2664 btrfs_abort_transaction(trans, ret);
2669 device->fs_devices = fs_devices;
2671 mutex_lock(&fs_devices->device_list_mutex);
2672 mutex_lock(&fs_info->chunk_mutex);
2673 list_add_rcu(&device->dev_list, &fs_devices->devices);
2674 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2675 fs_devices->num_devices++;
2676 fs_devices->open_devices++;
2677 fs_devices->rw_devices++;
2678 fs_devices->total_devices++;
2679 fs_devices->total_rw_bytes += device->total_bytes;
2681 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2683 if (!blk_queue_nonrot(q))
2684 fs_devices->rotating = true;
2686 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2687 btrfs_set_super_total_bytes(fs_info->super_copy,
2688 round_down(orig_super_total_bytes + device->total_bytes,
2689 fs_info->sectorsize));
2691 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2692 btrfs_set_super_num_devices(fs_info->super_copy,
2693 orig_super_num_devices + 1);
2696 * we've got more storage, clear any full flags on the space
2699 btrfs_clear_space_info_full(fs_info);
2701 mutex_unlock(&fs_info->chunk_mutex);
2703 /* Add sysfs device entry */
2704 btrfs_sysfs_add_device(device);
2706 mutex_unlock(&fs_devices->device_list_mutex);
2709 mutex_lock(&fs_info->chunk_mutex);
2710 ret = init_first_rw_device(trans);
2711 mutex_unlock(&fs_info->chunk_mutex);
2713 btrfs_abort_transaction(trans, ret);
2718 ret = btrfs_add_dev_item(trans, device);
2720 btrfs_abort_transaction(trans, ret);
2725 ret = btrfs_finish_sprout(trans);
2727 btrfs_abort_transaction(trans, ret);
2732 * fs_devices now represents the newly sprouted filesystem and
2733 * its fsid has been changed by btrfs_prepare_sprout
2735 btrfs_sysfs_update_sprout_fsid(fs_devices);
2738 ret = btrfs_commit_transaction(trans);
2741 mutex_unlock(&uuid_mutex);
2742 up_write(&sb->s_umount);
2745 if (ret) /* transaction commit */
2748 ret = btrfs_relocate_sys_chunks(fs_info);
2750 btrfs_handle_fs_error(fs_info, ret,
2751 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2752 trans = btrfs_attach_transaction(root);
2753 if (IS_ERR(trans)) {
2754 if (PTR_ERR(trans) == -ENOENT)
2756 ret = PTR_ERR(trans);
2760 ret = btrfs_commit_transaction(trans);
2764 * Now that we have written a new super block to this device, check all
2765 * other fs_devices list if device_path alienates any other scanned
2767 * We can ignore the return value as it typically returns -EINVAL and
2768 * only succeeds if the device was an alien.
2770 btrfs_forget_devices(device_path);
2772 /* Update ctime/mtime for blkid or udev */
2773 update_dev_time(device_path);
2778 btrfs_sysfs_remove_device(device);
2779 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2780 mutex_lock(&fs_info->chunk_mutex);
2781 list_del_rcu(&device->dev_list);
2782 list_del(&device->dev_alloc_list);
2783 fs_info->fs_devices->num_devices--;
2784 fs_info->fs_devices->open_devices--;
2785 fs_info->fs_devices->rw_devices--;
2786 fs_info->fs_devices->total_devices--;
2787 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2788 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2789 btrfs_set_super_total_bytes(fs_info->super_copy,
2790 orig_super_total_bytes);
2791 btrfs_set_super_num_devices(fs_info->super_copy,
2792 orig_super_num_devices);
2793 mutex_unlock(&fs_info->chunk_mutex);
2794 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2797 btrfs_set_sb_rdonly(sb);
2799 btrfs_end_transaction(trans);
2801 btrfs_destroy_dev_zone_info(device);
2803 btrfs_free_device(device);
2805 blkdev_put(bdev, FMODE_EXCL);
2807 mutex_unlock(&uuid_mutex);
2808 up_write(&sb->s_umount);
2813 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2814 struct btrfs_device *device)
2817 struct btrfs_path *path;
2818 struct btrfs_root *root = device->fs_info->chunk_root;
2819 struct btrfs_dev_item *dev_item;
2820 struct extent_buffer *leaf;
2821 struct btrfs_key key;
2823 path = btrfs_alloc_path();
2827 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2828 key.type = BTRFS_DEV_ITEM_KEY;
2829 key.offset = device->devid;
2831 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2840 leaf = path->nodes[0];
2841 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2843 btrfs_set_device_id(leaf, dev_item, device->devid);
2844 btrfs_set_device_type(leaf, dev_item, device->type);
2845 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2846 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2847 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2848 btrfs_set_device_total_bytes(leaf, dev_item,
2849 btrfs_device_get_disk_total_bytes(device));
2850 btrfs_set_device_bytes_used(leaf, dev_item,
2851 btrfs_device_get_bytes_used(device));
2852 btrfs_mark_buffer_dirty(leaf);
2855 btrfs_free_path(path);
2859 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2860 struct btrfs_device *device, u64 new_size)
2862 struct btrfs_fs_info *fs_info = device->fs_info;
2863 struct btrfs_super_block *super_copy = fs_info->super_copy;
2867 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2870 new_size = round_down(new_size, fs_info->sectorsize);
2872 mutex_lock(&fs_info->chunk_mutex);
2873 old_total = btrfs_super_total_bytes(super_copy);
2874 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2876 if (new_size <= device->total_bytes ||
2877 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2878 mutex_unlock(&fs_info->chunk_mutex);
2882 btrfs_set_super_total_bytes(super_copy,
2883 round_down(old_total + diff, fs_info->sectorsize));
2884 device->fs_devices->total_rw_bytes += diff;
2886 btrfs_device_set_total_bytes(device, new_size);
2887 btrfs_device_set_disk_total_bytes(device, new_size);
2888 btrfs_clear_space_info_full(device->fs_info);
2889 if (list_empty(&device->post_commit_list))
2890 list_add_tail(&device->post_commit_list,
2891 &trans->transaction->dev_update_list);
2892 mutex_unlock(&fs_info->chunk_mutex);
2894 return btrfs_update_device(trans, device);
2897 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2899 struct btrfs_fs_info *fs_info = trans->fs_info;
2900 struct btrfs_root *root = fs_info->chunk_root;
2902 struct btrfs_path *path;
2903 struct btrfs_key key;
2905 path = btrfs_alloc_path();
2909 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2910 key.offset = chunk_offset;
2911 key.type = BTRFS_CHUNK_ITEM_KEY;
2913 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2916 else if (ret > 0) { /* Logic error or corruption */
2917 btrfs_handle_fs_error(fs_info, -ENOENT,
2918 "Failed lookup while freeing chunk.");
2923 ret = btrfs_del_item(trans, root, path);
2925 btrfs_handle_fs_error(fs_info, ret,
2926 "Failed to delete chunk item.");
2928 btrfs_free_path(path);
2932 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2934 struct btrfs_super_block *super_copy = fs_info->super_copy;
2935 struct btrfs_disk_key *disk_key;
2936 struct btrfs_chunk *chunk;
2943 struct btrfs_key key;
2945 mutex_lock(&fs_info->chunk_mutex);
2946 array_size = btrfs_super_sys_array_size(super_copy);
2948 ptr = super_copy->sys_chunk_array;
2951 while (cur < array_size) {
2952 disk_key = (struct btrfs_disk_key *)ptr;
2953 btrfs_disk_key_to_cpu(&key, disk_key);
2955 len = sizeof(*disk_key);
2957 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2958 chunk = (struct btrfs_chunk *)(ptr + len);
2959 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2960 len += btrfs_chunk_item_size(num_stripes);
2965 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2966 key.offset == chunk_offset) {
2967 memmove(ptr, ptr + len, array_size - (cur + len));
2969 btrfs_set_super_sys_array_size(super_copy, array_size);
2975 mutex_unlock(&fs_info->chunk_mutex);
2980 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2981 * @logical: Logical block offset in bytes.
2982 * @length: Length of extent in bytes.
2984 * Return: Chunk mapping or ERR_PTR.
2986 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2987 u64 logical, u64 length)
2989 struct extent_map_tree *em_tree;
2990 struct extent_map *em;
2992 em_tree = &fs_info->mapping_tree;
2993 read_lock(&em_tree->lock);
2994 em = lookup_extent_mapping(em_tree, logical, length);
2995 read_unlock(&em_tree->lock);
2998 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
3000 return ERR_PTR(-EINVAL);
3003 if (em->start > logical || em->start + em->len < logical) {
3005 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
3006 logical, length, em->start, em->start + em->len);
3007 free_extent_map(em);
3008 return ERR_PTR(-EINVAL);
3011 /* callers are responsible for dropping em's ref. */
3015 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3017 struct btrfs_fs_info *fs_info = trans->fs_info;
3018 struct extent_map *em;
3019 struct map_lookup *map;
3020 u64 dev_extent_len = 0;
3022 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3024 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3027 * This is a logic error, but we don't want to just rely on the
3028 * user having built with ASSERT enabled, so if ASSERT doesn't
3029 * do anything we still error out.
3034 map = em->map_lookup;
3035 mutex_lock(&fs_info->chunk_mutex);
3036 check_system_chunk(trans, map->type);
3037 mutex_unlock(&fs_info->chunk_mutex);
3040 * Take the device list mutex to prevent races with the final phase of
3041 * a device replace operation that replaces the device object associated
3042 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
3044 mutex_lock(&fs_devices->device_list_mutex);
3045 for (i = 0; i < map->num_stripes; i++) {
3046 struct btrfs_device *device = map->stripes[i].dev;
3047 ret = btrfs_free_dev_extent(trans, device,
3048 map->stripes[i].physical,
3051 mutex_unlock(&fs_devices->device_list_mutex);
3052 btrfs_abort_transaction(trans, ret);
3056 if (device->bytes_used > 0) {
3057 mutex_lock(&fs_info->chunk_mutex);
3058 btrfs_device_set_bytes_used(device,
3059 device->bytes_used - dev_extent_len);
3060 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3061 btrfs_clear_space_info_full(fs_info);
3062 mutex_unlock(&fs_info->chunk_mutex);
3065 ret = btrfs_update_device(trans, device);
3067 mutex_unlock(&fs_devices->device_list_mutex);
3068 btrfs_abort_transaction(trans, ret);
3072 mutex_unlock(&fs_devices->device_list_mutex);
3074 ret = btrfs_free_chunk(trans, chunk_offset);
3076 btrfs_abort_transaction(trans, ret);
3080 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3082 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3083 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3085 btrfs_abort_transaction(trans, ret);
3090 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3092 btrfs_abort_transaction(trans, ret);
3098 free_extent_map(em);
3102 int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3104 struct btrfs_root *root = fs_info->chunk_root;
3105 struct btrfs_trans_handle *trans;
3106 struct btrfs_block_group *block_group;
3111 * Prevent races with automatic removal of unused block groups.
3112 * After we relocate and before we remove the chunk with offset
3113 * chunk_offset, automatic removal of the block group can kick in,
3114 * resulting in a failure when calling btrfs_remove_chunk() below.
3116 * Make sure to acquire this mutex before doing a tree search (dev
3117 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3118 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3119 * we release the path used to search the chunk/dev tree and before
3120 * the current task acquires this mutex and calls us.
3122 lockdep_assert_held(&fs_info->reclaim_bgs_lock);
3124 /* step one, relocate all the extents inside this chunk */
3125 btrfs_scrub_pause(fs_info);
3126 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3127 btrfs_scrub_continue(fs_info);
3131 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3134 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3135 length = block_group->length;
3136 btrfs_put_block_group(block_group);
3139 * On a zoned file system, discard the whole block group, this will
3140 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3141 * resetting the zone fails, don't treat it as a fatal problem from the
3142 * filesystem's point of view.
3144 if (btrfs_is_zoned(fs_info)) {
3145 ret = btrfs_discard_extent(fs_info, chunk_offset, length, NULL);
3148 "failed to reset zone %llu after relocation",
3152 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3154 if (IS_ERR(trans)) {
3155 ret = PTR_ERR(trans);
3156 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3161 * step two, delete the device extents and the
3162 * chunk tree entries
3164 ret = btrfs_remove_chunk(trans, chunk_offset);
3165 btrfs_end_transaction(trans);
3169 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3171 struct btrfs_root *chunk_root = fs_info->chunk_root;
3172 struct btrfs_path *path;
3173 struct extent_buffer *leaf;
3174 struct btrfs_chunk *chunk;
3175 struct btrfs_key key;
3176 struct btrfs_key found_key;
3178 bool retried = false;
3182 path = btrfs_alloc_path();
3187 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3188 key.offset = (u64)-1;
3189 key.type = BTRFS_CHUNK_ITEM_KEY;
3192 mutex_lock(&fs_info->reclaim_bgs_lock);
3193 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3195 mutex_unlock(&fs_info->reclaim_bgs_lock);
3198 BUG_ON(ret == 0); /* Corruption */
3200 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3203 mutex_unlock(&fs_info->reclaim_bgs_lock);
3209 leaf = path->nodes[0];
3210 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3212 chunk = btrfs_item_ptr(leaf, path->slots[0],
3213 struct btrfs_chunk);
3214 chunk_type = btrfs_chunk_type(leaf, chunk);
3215 btrfs_release_path(path);
3217 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3218 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3224 mutex_unlock(&fs_info->reclaim_bgs_lock);
3226 if (found_key.offset == 0)
3228 key.offset = found_key.offset - 1;
3231 if (failed && !retried) {
3235 } else if (WARN_ON(failed && retried)) {
3239 btrfs_free_path(path);
3244 * return 1 : allocate a data chunk successfully,
3245 * return <0: errors during allocating a data chunk,
3246 * return 0 : no need to allocate a data chunk.
3248 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3251 struct btrfs_block_group *cache;
3255 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3257 chunk_type = cache->flags;
3258 btrfs_put_block_group(cache);
3260 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3263 spin_lock(&fs_info->data_sinfo->lock);
3264 bytes_used = fs_info->data_sinfo->bytes_used;
3265 spin_unlock(&fs_info->data_sinfo->lock);
3268 struct btrfs_trans_handle *trans;
3271 trans = btrfs_join_transaction(fs_info->tree_root);
3273 return PTR_ERR(trans);
3275 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3276 btrfs_end_transaction(trans);
3285 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3286 struct btrfs_balance_control *bctl)
3288 struct btrfs_root *root = fs_info->tree_root;
3289 struct btrfs_trans_handle *trans;
3290 struct btrfs_balance_item *item;
3291 struct btrfs_disk_balance_args disk_bargs;
3292 struct btrfs_path *path;
3293 struct extent_buffer *leaf;
3294 struct btrfs_key key;
3297 path = btrfs_alloc_path();
3301 trans = btrfs_start_transaction(root, 0);
3302 if (IS_ERR(trans)) {
3303 btrfs_free_path(path);
3304 return PTR_ERR(trans);
3307 key.objectid = BTRFS_BALANCE_OBJECTID;
3308 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3311 ret = btrfs_insert_empty_item(trans, root, path, &key,
3316 leaf = path->nodes[0];
3317 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3319 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3321 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3322 btrfs_set_balance_data(leaf, item, &disk_bargs);
3323 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3324 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3325 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3326 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3328 btrfs_set_balance_flags(leaf, item, bctl->flags);
3330 btrfs_mark_buffer_dirty(leaf);
3332 btrfs_free_path(path);
3333 err = btrfs_commit_transaction(trans);
3339 static int del_balance_item(struct btrfs_fs_info *fs_info)
3341 struct btrfs_root *root = fs_info->tree_root;
3342 struct btrfs_trans_handle *trans;
3343 struct btrfs_path *path;
3344 struct btrfs_key key;
3347 path = btrfs_alloc_path();
3351 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3352 if (IS_ERR(trans)) {
3353 btrfs_free_path(path);
3354 return PTR_ERR(trans);
3357 key.objectid = BTRFS_BALANCE_OBJECTID;
3358 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3361 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3369 ret = btrfs_del_item(trans, root, path);
3371 btrfs_free_path(path);
3372 err = btrfs_commit_transaction(trans);
3379 * This is a heuristic used to reduce the number of chunks balanced on
3380 * resume after balance was interrupted.
3382 static void update_balance_args(struct btrfs_balance_control *bctl)
3385 * Turn on soft mode for chunk types that were being converted.
3387 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3388 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3389 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3390 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3391 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3392 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3395 * Turn on usage filter if is not already used. The idea is
3396 * that chunks that we have already balanced should be
3397 * reasonably full. Don't do it for chunks that are being
3398 * converted - that will keep us from relocating unconverted
3399 * (albeit full) chunks.
3401 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3402 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3403 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3404 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3405 bctl->data.usage = 90;
3407 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3408 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3409 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3410 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3411 bctl->sys.usage = 90;
3413 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3414 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3415 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3416 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3417 bctl->meta.usage = 90;
3422 * Clear the balance status in fs_info and delete the balance item from disk.
3424 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3426 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3429 BUG_ON(!fs_info->balance_ctl);
3431 spin_lock(&fs_info->balance_lock);
3432 fs_info->balance_ctl = NULL;
3433 spin_unlock(&fs_info->balance_lock);
3436 ret = del_balance_item(fs_info);
3438 btrfs_handle_fs_error(fs_info, ret, NULL);
3442 * Balance filters. Return 1 if chunk should be filtered out
3443 * (should not be balanced).
3445 static int chunk_profiles_filter(u64 chunk_type,
3446 struct btrfs_balance_args *bargs)
3448 chunk_type = chunk_to_extended(chunk_type) &
3449 BTRFS_EXTENDED_PROFILE_MASK;
3451 if (bargs->profiles & chunk_type)
3457 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3458 struct btrfs_balance_args *bargs)
3460 struct btrfs_block_group *cache;
3462 u64 user_thresh_min;
3463 u64 user_thresh_max;
3466 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3467 chunk_used = cache->used;
3469 if (bargs->usage_min == 0)
3470 user_thresh_min = 0;
3472 user_thresh_min = div_factor_fine(cache->length,
3475 if (bargs->usage_max == 0)
3476 user_thresh_max = 1;
3477 else if (bargs->usage_max > 100)
3478 user_thresh_max = cache->length;
3480 user_thresh_max = div_factor_fine(cache->length,
3483 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3486 btrfs_put_block_group(cache);
3490 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3491 u64 chunk_offset, struct btrfs_balance_args *bargs)
3493 struct btrfs_block_group *cache;
3494 u64 chunk_used, user_thresh;
3497 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3498 chunk_used = cache->used;
3500 if (bargs->usage_min == 0)
3502 else if (bargs->usage > 100)
3503 user_thresh = cache->length;
3505 user_thresh = div_factor_fine(cache->length, bargs->usage);
3507 if (chunk_used < user_thresh)
3510 btrfs_put_block_group(cache);
3514 static int chunk_devid_filter(struct extent_buffer *leaf,
3515 struct btrfs_chunk *chunk,
3516 struct btrfs_balance_args *bargs)
3518 struct btrfs_stripe *stripe;
3519 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3522 for (i = 0; i < num_stripes; i++) {
3523 stripe = btrfs_stripe_nr(chunk, i);
3524 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3531 static u64 calc_data_stripes(u64 type, int num_stripes)
3533 const int index = btrfs_bg_flags_to_raid_index(type);
3534 const int ncopies = btrfs_raid_array[index].ncopies;
3535 const int nparity = btrfs_raid_array[index].nparity;
3538 return num_stripes - nparity;
3540 return num_stripes / ncopies;
3543 /* [pstart, pend) */
3544 static int chunk_drange_filter(struct extent_buffer *leaf,
3545 struct btrfs_chunk *chunk,
3546 struct btrfs_balance_args *bargs)
3548 struct btrfs_stripe *stripe;
3549 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3556 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3559 type = btrfs_chunk_type(leaf, chunk);
3560 factor = calc_data_stripes(type, num_stripes);
3562 for (i = 0; i < num_stripes; i++) {
3563 stripe = btrfs_stripe_nr(chunk, i);
3564 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3567 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3568 stripe_length = btrfs_chunk_length(leaf, chunk);
3569 stripe_length = div_u64(stripe_length, factor);
3571 if (stripe_offset < bargs->pend &&
3572 stripe_offset + stripe_length > bargs->pstart)
3579 /* [vstart, vend) */
3580 static int chunk_vrange_filter(struct extent_buffer *leaf,
3581 struct btrfs_chunk *chunk,
3583 struct btrfs_balance_args *bargs)
3585 if (chunk_offset < bargs->vend &&
3586 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3587 /* at least part of the chunk is inside this vrange */
3593 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3594 struct btrfs_chunk *chunk,
3595 struct btrfs_balance_args *bargs)
3597 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3599 if (bargs->stripes_min <= num_stripes
3600 && num_stripes <= bargs->stripes_max)
3606 static int chunk_soft_convert_filter(u64 chunk_type,
3607 struct btrfs_balance_args *bargs)
3609 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3612 chunk_type = chunk_to_extended(chunk_type) &
3613 BTRFS_EXTENDED_PROFILE_MASK;
3615 if (bargs->target == chunk_type)
3621 static int should_balance_chunk(struct extent_buffer *leaf,
3622 struct btrfs_chunk *chunk, u64 chunk_offset)
3624 struct btrfs_fs_info *fs_info = leaf->fs_info;
3625 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3626 struct btrfs_balance_args *bargs = NULL;
3627 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3630 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3631 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3635 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3636 bargs = &bctl->data;
3637 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3639 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3640 bargs = &bctl->meta;
3642 /* profiles filter */
3643 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3644 chunk_profiles_filter(chunk_type, bargs)) {
3649 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3650 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3652 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3653 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3658 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3659 chunk_devid_filter(leaf, chunk, bargs)) {
3663 /* drange filter, makes sense only with devid filter */
3664 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3665 chunk_drange_filter(leaf, chunk, bargs)) {
3670 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3671 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3675 /* stripes filter */
3676 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3677 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3681 /* soft profile changing mode */
3682 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3683 chunk_soft_convert_filter(chunk_type, bargs)) {
3688 * limited by count, must be the last filter
3690 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3691 if (bargs->limit == 0)
3695 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3697 * Same logic as the 'limit' filter; the minimum cannot be
3698 * determined here because we do not have the global information
3699 * about the count of all chunks that satisfy the filters.
3701 if (bargs->limit_max == 0)
3710 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3712 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3713 struct btrfs_root *chunk_root = fs_info->chunk_root;
3715 struct btrfs_chunk *chunk;
3716 struct btrfs_path *path = NULL;
3717 struct btrfs_key key;
3718 struct btrfs_key found_key;
3719 struct extent_buffer *leaf;
3722 int enospc_errors = 0;
3723 bool counting = true;
3724 /* The single value limit and min/max limits use the same bytes in the */
3725 u64 limit_data = bctl->data.limit;
3726 u64 limit_meta = bctl->meta.limit;
3727 u64 limit_sys = bctl->sys.limit;
3731 int chunk_reserved = 0;
3733 path = btrfs_alloc_path();
3739 /* zero out stat counters */
3740 spin_lock(&fs_info->balance_lock);
3741 memset(&bctl->stat, 0, sizeof(bctl->stat));
3742 spin_unlock(&fs_info->balance_lock);
3746 * The single value limit and min/max limits use the same bytes
3749 bctl->data.limit = limit_data;
3750 bctl->meta.limit = limit_meta;
3751 bctl->sys.limit = limit_sys;
3753 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3754 key.offset = (u64)-1;
3755 key.type = BTRFS_CHUNK_ITEM_KEY;
3758 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3759 atomic_read(&fs_info->balance_cancel_req)) {
3764 mutex_lock(&fs_info->reclaim_bgs_lock);
3765 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3767 mutex_unlock(&fs_info->reclaim_bgs_lock);
3772 * this shouldn't happen, it means the last relocate
3776 BUG(); /* FIXME break ? */
3778 ret = btrfs_previous_item(chunk_root, path, 0,
3779 BTRFS_CHUNK_ITEM_KEY);
3781 mutex_unlock(&fs_info->reclaim_bgs_lock);
3786 leaf = path->nodes[0];
3787 slot = path->slots[0];
3788 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3790 if (found_key.objectid != key.objectid) {
3791 mutex_unlock(&fs_info->reclaim_bgs_lock);
3795 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3796 chunk_type = btrfs_chunk_type(leaf, chunk);
3799 spin_lock(&fs_info->balance_lock);
3800 bctl->stat.considered++;
3801 spin_unlock(&fs_info->balance_lock);
3804 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3806 btrfs_release_path(path);
3808 mutex_unlock(&fs_info->reclaim_bgs_lock);
3813 mutex_unlock(&fs_info->reclaim_bgs_lock);
3814 spin_lock(&fs_info->balance_lock);
3815 bctl->stat.expected++;
3816 spin_unlock(&fs_info->balance_lock);
3818 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3820 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3822 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3829 * Apply limit_min filter, no need to check if the LIMITS
3830 * filter is used, limit_min is 0 by default
3832 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3833 count_data < bctl->data.limit_min)
3834 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3835 count_meta < bctl->meta.limit_min)
3836 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3837 count_sys < bctl->sys.limit_min)) {
3838 mutex_unlock(&fs_info->reclaim_bgs_lock);
3842 if (!chunk_reserved) {
3844 * We may be relocating the only data chunk we have,
3845 * which could potentially end up with losing data's
3846 * raid profile, so lets allocate an empty one in
3849 ret = btrfs_may_alloc_data_chunk(fs_info,
3852 mutex_unlock(&fs_info->reclaim_bgs_lock);
3854 } else if (ret == 1) {
3859 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3860 mutex_unlock(&fs_info->reclaim_bgs_lock);
3861 if (ret == -ENOSPC) {
3863 } else if (ret == -ETXTBSY) {
3865 "skipping relocation of block group %llu due to active swapfile",
3871 spin_lock(&fs_info->balance_lock);
3872 bctl->stat.completed++;
3873 spin_unlock(&fs_info->balance_lock);
3876 if (found_key.offset == 0)
3878 key.offset = found_key.offset - 1;
3882 btrfs_release_path(path);
3887 btrfs_free_path(path);
3888 if (enospc_errors) {
3889 btrfs_info(fs_info, "%d enospc errors during balance",
3899 * alloc_profile_is_valid - see if a given profile is valid and reduced
3900 * @flags: profile to validate
3901 * @extended: if true @flags is treated as an extended profile
3903 static int alloc_profile_is_valid(u64 flags, int extended)
3905 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3906 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3908 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3910 /* 1) check that all other bits are zeroed */
3914 /* 2) see if profile is reduced */
3916 return !extended; /* "0" is valid for usual profiles */
3918 return has_single_bit_set(flags);
3921 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3923 /* cancel requested || normal exit path */
3924 return atomic_read(&fs_info->balance_cancel_req) ||
3925 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3926 atomic_read(&fs_info->balance_cancel_req) == 0);
3930 * Validate target profile against allowed profiles and return true if it's OK.
3931 * Otherwise print the error message and return false.
3933 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
3934 const struct btrfs_balance_args *bargs,
3935 u64 allowed, const char *type)
3937 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3940 /* Profile is valid and does not have bits outside of the allowed set */
3941 if (alloc_profile_is_valid(bargs->target, 1) &&
3942 (bargs->target & ~allowed) == 0)
3945 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
3946 type, btrfs_bg_type_to_raid_name(bargs->target));
3951 * Fill @buf with textual description of balance filter flags @bargs, up to
3952 * @size_buf including the terminating null. The output may be trimmed if it
3953 * does not fit into the provided buffer.
3955 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3959 u32 size_bp = size_buf;
3961 u64 flags = bargs->flags;
3962 char tmp_buf[128] = {'\0'};
3967 #define CHECK_APPEND_NOARG(a) \
3969 ret = snprintf(bp, size_bp, (a)); \
3970 if (ret < 0 || ret >= size_bp) \
3971 goto out_overflow; \
3976 #define CHECK_APPEND_1ARG(a, v1) \
3978 ret = snprintf(bp, size_bp, (a), (v1)); \
3979 if (ret < 0 || ret >= size_bp) \
3980 goto out_overflow; \
3985 #define CHECK_APPEND_2ARG(a, v1, v2) \
3987 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3988 if (ret < 0 || ret >= size_bp) \
3989 goto out_overflow; \
3994 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
3995 CHECK_APPEND_1ARG("convert=%s,",
3996 btrfs_bg_type_to_raid_name(bargs->target));
3998 if (flags & BTRFS_BALANCE_ARGS_SOFT)
3999 CHECK_APPEND_NOARG("soft,");
4001 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4002 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4004 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4007 if (flags & BTRFS_BALANCE_ARGS_USAGE)
4008 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4010 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4011 CHECK_APPEND_2ARG("usage=%u..%u,",
4012 bargs->usage_min, bargs->usage_max);
4014 if (flags & BTRFS_BALANCE_ARGS_DEVID)
4015 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4017 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4018 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4019 bargs->pstart, bargs->pend);
4021 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4022 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4023 bargs->vstart, bargs->vend);
4025 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4026 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4028 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4029 CHECK_APPEND_2ARG("limit=%u..%u,",
4030 bargs->limit_min, bargs->limit_max);
4032 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4033 CHECK_APPEND_2ARG("stripes=%u..%u,",
4034 bargs->stripes_min, bargs->stripes_max);
4036 #undef CHECK_APPEND_2ARG
4037 #undef CHECK_APPEND_1ARG
4038 #undef CHECK_APPEND_NOARG
4042 if (size_bp < size_buf)
4043 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4048 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4050 u32 size_buf = 1024;
4051 char tmp_buf[192] = {'\0'};
4054 u32 size_bp = size_buf;
4056 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4058 buf = kzalloc(size_buf, GFP_KERNEL);
4064 #define CHECK_APPEND_1ARG(a, v1) \
4066 ret = snprintf(bp, size_bp, (a), (v1)); \
4067 if (ret < 0 || ret >= size_bp) \
4068 goto out_overflow; \
4073 if (bctl->flags & BTRFS_BALANCE_FORCE)
4074 CHECK_APPEND_1ARG("%s", "-f ");
4076 if (bctl->flags & BTRFS_BALANCE_DATA) {
4077 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4078 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4081 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4082 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4083 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4086 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4087 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4088 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4091 #undef CHECK_APPEND_1ARG
4095 if (size_bp < size_buf)
4096 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4097 btrfs_info(fs_info, "balance: %s %s",
4098 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4099 "resume" : "start", buf);
4105 * Should be called with balance mutexe held
4107 int btrfs_balance(struct btrfs_fs_info *fs_info,
4108 struct btrfs_balance_control *bctl,
4109 struct btrfs_ioctl_balance_args *bargs)
4111 u64 meta_target, data_target;
4117 bool reducing_redundancy;
4120 if (btrfs_fs_closing(fs_info) ||
4121 atomic_read(&fs_info->balance_pause_req) ||
4122 btrfs_should_cancel_balance(fs_info)) {
4127 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4128 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4132 * In case of mixed groups both data and meta should be picked,
4133 * and identical options should be given for both of them.
4135 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4136 if (mixed && (bctl->flags & allowed)) {
4137 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4138 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4139 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4141 "balance: mixed groups data and metadata options must be the same");
4148 * rw_devices will not change at the moment, device add/delete/replace
4151 num_devices = fs_info->fs_devices->rw_devices;
4154 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4155 * special bit for it, to make it easier to distinguish. Thus we need
4156 * to set it manually, or balance would refuse the profile.
4158 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4159 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4160 if (num_devices >= btrfs_raid_array[i].devs_min)
4161 allowed |= btrfs_raid_array[i].bg_flag;
4163 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4164 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4165 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
4171 * Allow to reduce metadata or system integrity only if force set for
4172 * profiles with redundancy (copies, parity)
4175 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4176 if (btrfs_raid_array[i].ncopies >= 2 ||
4177 btrfs_raid_array[i].tolerated_failures >= 1)
4178 allowed |= btrfs_raid_array[i].bg_flag;
4181 seq = read_seqbegin(&fs_info->profiles_lock);
4183 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4184 (fs_info->avail_system_alloc_bits & allowed) &&
4185 !(bctl->sys.target & allowed)) ||
4186 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4187 (fs_info->avail_metadata_alloc_bits & allowed) &&
4188 !(bctl->meta.target & allowed)))
4189 reducing_redundancy = true;
4191 reducing_redundancy = false;
4193 /* if we're not converting, the target field is uninitialized */
4194 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4195 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4196 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4197 bctl->data.target : fs_info->avail_data_alloc_bits;
4198 } while (read_seqretry(&fs_info->profiles_lock, seq));
4200 if (reducing_redundancy) {
4201 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4203 "balance: force reducing metadata redundancy");
4206 "balance: reduces metadata redundancy, use --force if you want this");
4212 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4213 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4215 "balance: metadata profile %s has lower redundancy than data profile %s",
4216 btrfs_bg_type_to_raid_name(meta_target),
4217 btrfs_bg_type_to_raid_name(data_target));
4220 if (fs_info->send_in_progress) {
4221 btrfs_warn_rl(fs_info,
4222 "cannot run balance while send operations are in progress (%d in progress)",
4223 fs_info->send_in_progress);
4228 ret = insert_balance_item(fs_info, bctl);
4229 if (ret && ret != -EEXIST)
4232 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4233 BUG_ON(ret == -EEXIST);
4234 BUG_ON(fs_info->balance_ctl);
4235 spin_lock(&fs_info->balance_lock);
4236 fs_info->balance_ctl = bctl;
4237 spin_unlock(&fs_info->balance_lock);
4239 BUG_ON(ret != -EEXIST);
4240 spin_lock(&fs_info->balance_lock);
4241 update_balance_args(bctl);
4242 spin_unlock(&fs_info->balance_lock);
4245 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4246 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4247 describe_balance_start_or_resume(fs_info);
4248 mutex_unlock(&fs_info->balance_mutex);
4250 ret = __btrfs_balance(fs_info);
4252 mutex_lock(&fs_info->balance_mutex);
4253 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4254 btrfs_info(fs_info, "balance: paused");
4256 * Balance can be canceled by:
4258 * - Regular cancel request
4259 * Then ret == -ECANCELED and balance_cancel_req > 0
4261 * - Fatal signal to "btrfs" process
4262 * Either the signal caught by wait_reserve_ticket() and callers
4263 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4265 * Either way, in this case balance_cancel_req = 0, and
4266 * ret == -EINTR or ret == -ECANCELED.
4268 * So here we only check the return value to catch canceled balance.
4270 else if (ret == -ECANCELED || ret == -EINTR)
4271 btrfs_info(fs_info, "balance: canceled");
4273 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4275 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4278 memset(bargs, 0, sizeof(*bargs));
4279 btrfs_update_ioctl_balance_args(fs_info, bargs);
4282 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4283 balance_need_close(fs_info)) {
4284 reset_balance_state(fs_info);
4285 btrfs_exclop_finish(fs_info);
4288 wake_up(&fs_info->balance_wait_q);
4292 if (bctl->flags & BTRFS_BALANCE_RESUME)
4293 reset_balance_state(fs_info);
4296 btrfs_exclop_finish(fs_info);
4301 static int balance_kthread(void *data)
4303 struct btrfs_fs_info *fs_info = data;
4306 mutex_lock(&fs_info->balance_mutex);
4307 if (fs_info->balance_ctl)
4308 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4309 mutex_unlock(&fs_info->balance_mutex);
4314 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4316 struct task_struct *tsk;
4318 mutex_lock(&fs_info->balance_mutex);
4319 if (!fs_info->balance_ctl) {
4320 mutex_unlock(&fs_info->balance_mutex);
4323 mutex_unlock(&fs_info->balance_mutex);
4325 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4326 btrfs_info(fs_info, "balance: resume skipped");
4331 * A ro->rw remount sequence should continue with the paused balance
4332 * regardless of who pauses it, system or the user as of now, so set
4335 spin_lock(&fs_info->balance_lock);
4336 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4337 spin_unlock(&fs_info->balance_lock);
4339 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4340 return PTR_ERR_OR_ZERO(tsk);
4343 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4345 struct btrfs_balance_control *bctl;
4346 struct btrfs_balance_item *item;
4347 struct btrfs_disk_balance_args disk_bargs;
4348 struct btrfs_path *path;
4349 struct extent_buffer *leaf;
4350 struct btrfs_key key;
4353 path = btrfs_alloc_path();
4357 key.objectid = BTRFS_BALANCE_OBJECTID;
4358 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4361 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4364 if (ret > 0) { /* ret = -ENOENT; */
4369 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4375 leaf = path->nodes[0];
4376 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4378 bctl->flags = btrfs_balance_flags(leaf, item);
4379 bctl->flags |= BTRFS_BALANCE_RESUME;
4381 btrfs_balance_data(leaf, item, &disk_bargs);
4382 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4383 btrfs_balance_meta(leaf, item, &disk_bargs);
4384 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4385 btrfs_balance_sys(leaf, item, &disk_bargs);
4386 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4389 * This should never happen, as the paused balance state is recovered
4390 * during mount without any chance of other exclusive ops to collide.
4392 * This gives the exclusive op status to balance and keeps in paused
4393 * state until user intervention (cancel or umount). If the ownership
4394 * cannot be assigned, show a message but do not fail. The balance
4395 * is in a paused state and must have fs_info::balance_ctl properly
4398 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
4400 "balance: cannot set exclusive op status, resume manually");
4402 btrfs_release_path(path);
4404 mutex_lock(&fs_info->balance_mutex);
4405 BUG_ON(fs_info->balance_ctl);
4406 spin_lock(&fs_info->balance_lock);
4407 fs_info->balance_ctl = bctl;
4408 spin_unlock(&fs_info->balance_lock);
4409 mutex_unlock(&fs_info->balance_mutex);
4411 btrfs_free_path(path);
4415 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4419 mutex_lock(&fs_info->balance_mutex);
4420 if (!fs_info->balance_ctl) {
4421 mutex_unlock(&fs_info->balance_mutex);
4425 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4426 atomic_inc(&fs_info->balance_pause_req);
4427 mutex_unlock(&fs_info->balance_mutex);
4429 wait_event(fs_info->balance_wait_q,
4430 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4432 mutex_lock(&fs_info->balance_mutex);
4433 /* we are good with balance_ctl ripped off from under us */
4434 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4435 atomic_dec(&fs_info->balance_pause_req);
4440 mutex_unlock(&fs_info->balance_mutex);
4444 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4446 mutex_lock(&fs_info->balance_mutex);
4447 if (!fs_info->balance_ctl) {
4448 mutex_unlock(&fs_info->balance_mutex);
4453 * A paused balance with the item stored on disk can be resumed at
4454 * mount time if the mount is read-write. Otherwise it's still paused
4455 * and we must not allow cancelling as it deletes the item.
4457 if (sb_rdonly(fs_info->sb)) {
4458 mutex_unlock(&fs_info->balance_mutex);
4462 atomic_inc(&fs_info->balance_cancel_req);
4464 * if we are running just wait and return, balance item is
4465 * deleted in btrfs_balance in this case
4467 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4468 mutex_unlock(&fs_info->balance_mutex);
4469 wait_event(fs_info->balance_wait_q,
4470 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4471 mutex_lock(&fs_info->balance_mutex);
4473 mutex_unlock(&fs_info->balance_mutex);
4475 * Lock released to allow other waiters to continue, we'll
4476 * reexamine the status again.
4478 mutex_lock(&fs_info->balance_mutex);
4480 if (fs_info->balance_ctl) {
4481 reset_balance_state(fs_info);
4482 btrfs_exclop_finish(fs_info);
4483 btrfs_info(fs_info, "balance: canceled");
4487 BUG_ON(fs_info->balance_ctl ||
4488 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4489 atomic_dec(&fs_info->balance_cancel_req);
4490 mutex_unlock(&fs_info->balance_mutex);
4494 int btrfs_uuid_scan_kthread(void *data)
4496 struct btrfs_fs_info *fs_info = data;
4497 struct btrfs_root *root = fs_info->tree_root;
4498 struct btrfs_key key;
4499 struct btrfs_path *path = NULL;
4501 struct extent_buffer *eb;
4503 struct btrfs_root_item root_item;
4505 struct btrfs_trans_handle *trans = NULL;
4506 bool closing = false;
4508 path = btrfs_alloc_path();
4515 key.type = BTRFS_ROOT_ITEM_KEY;
4519 if (btrfs_fs_closing(fs_info)) {
4523 ret = btrfs_search_forward(root, &key, path,
4524 BTRFS_OLDEST_GENERATION);
4531 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4532 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4533 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4534 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4537 eb = path->nodes[0];
4538 slot = path->slots[0];
4539 item_size = btrfs_item_size_nr(eb, slot);
4540 if (item_size < sizeof(root_item))
4543 read_extent_buffer(eb, &root_item,
4544 btrfs_item_ptr_offset(eb, slot),
4545 (int)sizeof(root_item));
4546 if (btrfs_root_refs(&root_item) == 0)
4549 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4550 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4554 btrfs_release_path(path);
4556 * 1 - subvol uuid item
4557 * 1 - received_subvol uuid item
4559 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4560 if (IS_ERR(trans)) {
4561 ret = PTR_ERR(trans);
4569 btrfs_release_path(path);
4570 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4571 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4572 BTRFS_UUID_KEY_SUBVOL,
4575 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4581 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4582 ret = btrfs_uuid_tree_add(trans,
4583 root_item.received_uuid,
4584 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4587 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4594 btrfs_release_path(path);
4596 ret = btrfs_end_transaction(trans);
4602 if (key.offset < (u64)-1) {
4604 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4606 key.type = BTRFS_ROOT_ITEM_KEY;
4607 } else if (key.objectid < (u64)-1) {
4609 key.type = BTRFS_ROOT_ITEM_KEY;
4618 btrfs_free_path(path);
4619 if (trans && !IS_ERR(trans))
4620 btrfs_end_transaction(trans);
4622 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4624 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4625 up(&fs_info->uuid_tree_rescan_sem);
4629 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4631 struct btrfs_trans_handle *trans;
4632 struct btrfs_root *tree_root = fs_info->tree_root;
4633 struct btrfs_root *uuid_root;
4634 struct task_struct *task;
4641 trans = btrfs_start_transaction(tree_root, 2);
4643 return PTR_ERR(trans);
4645 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4646 if (IS_ERR(uuid_root)) {
4647 ret = PTR_ERR(uuid_root);
4648 btrfs_abort_transaction(trans, ret);
4649 btrfs_end_transaction(trans);
4653 fs_info->uuid_root = uuid_root;
4655 ret = btrfs_commit_transaction(trans);
4659 down(&fs_info->uuid_tree_rescan_sem);
4660 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4662 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4663 btrfs_warn(fs_info, "failed to start uuid_scan task");
4664 up(&fs_info->uuid_tree_rescan_sem);
4665 return PTR_ERR(task);
4672 * shrinking a device means finding all of the device extents past
4673 * the new size, and then following the back refs to the chunks.
4674 * The chunk relocation code actually frees the device extent
4676 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4678 struct btrfs_fs_info *fs_info = device->fs_info;
4679 struct btrfs_root *root = fs_info->dev_root;
4680 struct btrfs_trans_handle *trans;
4681 struct btrfs_dev_extent *dev_extent = NULL;
4682 struct btrfs_path *path;
4688 bool retried = false;
4689 struct extent_buffer *l;
4690 struct btrfs_key key;
4691 struct btrfs_super_block *super_copy = fs_info->super_copy;
4692 u64 old_total = btrfs_super_total_bytes(super_copy);
4693 u64 old_size = btrfs_device_get_total_bytes(device);
4697 new_size = round_down(new_size, fs_info->sectorsize);
4699 diff = round_down(old_size - new_size, fs_info->sectorsize);
4701 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4704 path = btrfs_alloc_path();
4708 path->reada = READA_BACK;
4710 trans = btrfs_start_transaction(root, 0);
4711 if (IS_ERR(trans)) {
4712 btrfs_free_path(path);
4713 return PTR_ERR(trans);
4716 mutex_lock(&fs_info->chunk_mutex);
4718 btrfs_device_set_total_bytes(device, new_size);
4719 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4720 device->fs_devices->total_rw_bytes -= diff;
4721 atomic64_sub(diff, &fs_info->free_chunk_space);
4725 * Once the device's size has been set to the new size, ensure all
4726 * in-memory chunks are synced to disk so that the loop below sees them
4727 * and relocates them accordingly.
4729 if (contains_pending_extent(device, &start, diff)) {
4730 mutex_unlock(&fs_info->chunk_mutex);
4731 ret = btrfs_commit_transaction(trans);
4735 mutex_unlock(&fs_info->chunk_mutex);
4736 btrfs_end_transaction(trans);
4740 key.objectid = device->devid;
4741 key.offset = (u64)-1;
4742 key.type = BTRFS_DEV_EXTENT_KEY;
4745 mutex_lock(&fs_info->reclaim_bgs_lock);
4746 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4748 mutex_unlock(&fs_info->reclaim_bgs_lock);
4752 ret = btrfs_previous_item(root, path, 0, key.type);
4754 mutex_unlock(&fs_info->reclaim_bgs_lock);
4758 btrfs_release_path(path);
4763 slot = path->slots[0];
4764 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4766 if (key.objectid != device->devid) {
4767 mutex_unlock(&fs_info->reclaim_bgs_lock);
4768 btrfs_release_path(path);
4772 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4773 length = btrfs_dev_extent_length(l, dev_extent);
4775 if (key.offset + length <= new_size) {
4776 mutex_unlock(&fs_info->reclaim_bgs_lock);
4777 btrfs_release_path(path);
4781 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4782 btrfs_release_path(path);
4785 * We may be relocating the only data chunk we have,
4786 * which could potentially end up with losing data's
4787 * raid profile, so lets allocate an empty one in
4790 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4792 mutex_unlock(&fs_info->reclaim_bgs_lock);
4796 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4797 mutex_unlock(&fs_info->reclaim_bgs_lock);
4798 if (ret == -ENOSPC) {
4801 if (ret == -ETXTBSY) {
4803 "could not shrink block group %llu due to active swapfile",
4808 } while (key.offset-- > 0);
4810 if (failed && !retried) {
4814 } else if (failed && retried) {
4819 /* Shrinking succeeded, else we would be at "done". */
4820 trans = btrfs_start_transaction(root, 0);
4821 if (IS_ERR(trans)) {
4822 ret = PTR_ERR(trans);
4826 mutex_lock(&fs_info->chunk_mutex);
4827 /* Clear all state bits beyond the shrunk device size */
4828 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4831 btrfs_device_set_disk_total_bytes(device, new_size);
4832 if (list_empty(&device->post_commit_list))
4833 list_add_tail(&device->post_commit_list,
4834 &trans->transaction->dev_update_list);
4836 WARN_ON(diff > old_total);
4837 btrfs_set_super_total_bytes(super_copy,
4838 round_down(old_total - diff, fs_info->sectorsize));
4839 mutex_unlock(&fs_info->chunk_mutex);
4841 /* Now btrfs_update_device() will change the on-disk size. */
4842 ret = btrfs_update_device(trans, device);
4844 btrfs_abort_transaction(trans, ret);
4845 btrfs_end_transaction(trans);
4847 ret = btrfs_commit_transaction(trans);
4850 btrfs_free_path(path);
4852 mutex_lock(&fs_info->chunk_mutex);
4853 btrfs_device_set_total_bytes(device, old_size);
4854 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4855 device->fs_devices->total_rw_bytes += diff;
4856 atomic64_add(diff, &fs_info->free_chunk_space);
4857 mutex_unlock(&fs_info->chunk_mutex);
4862 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4863 struct btrfs_key *key,
4864 struct btrfs_chunk *chunk, int item_size)
4866 struct btrfs_super_block *super_copy = fs_info->super_copy;
4867 struct btrfs_disk_key disk_key;
4871 mutex_lock(&fs_info->chunk_mutex);
4872 array_size = btrfs_super_sys_array_size(super_copy);
4873 if (array_size + item_size + sizeof(disk_key)
4874 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4875 mutex_unlock(&fs_info->chunk_mutex);
4879 ptr = super_copy->sys_chunk_array + array_size;
4880 btrfs_cpu_key_to_disk(&disk_key, key);
4881 memcpy(ptr, &disk_key, sizeof(disk_key));
4882 ptr += sizeof(disk_key);
4883 memcpy(ptr, chunk, item_size);
4884 item_size += sizeof(disk_key);
4885 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4886 mutex_unlock(&fs_info->chunk_mutex);
4892 * sort the devices in descending order by max_avail, total_avail
4894 static int btrfs_cmp_device_info(const void *a, const void *b)
4896 const struct btrfs_device_info *di_a = a;
4897 const struct btrfs_device_info *di_b = b;
4899 if (di_a->max_avail > di_b->max_avail)
4901 if (di_a->max_avail < di_b->max_avail)
4903 if (di_a->total_avail > di_b->total_avail)
4905 if (di_a->total_avail < di_b->total_avail)
4910 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4912 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4915 btrfs_set_fs_incompat(info, RAID56);
4918 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
4920 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
4923 btrfs_set_fs_incompat(info, RAID1C34);
4927 * Structure used internally for __btrfs_alloc_chunk() function.
4928 * Wraps needed parameters.
4930 struct alloc_chunk_ctl {
4933 /* Total number of stripes to allocate */
4935 /* sub_stripes info for map */
4937 /* Stripes per device */
4939 /* Maximum number of devices to use */
4941 /* Minimum number of devices to use */
4943 /* ndevs has to be a multiple of this */
4945 /* Number of copies */
4947 /* Number of stripes worth of bytes to store parity information */
4949 u64 max_stripe_size;
4957 static void init_alloc_chunk_ctl_policy_regular(
4958 struct btrfs_fs_devices *fs_devices,
4959 struct alloc_chunk_ctl *ctl)
4961 u64 type = ctl->type;
4963 if (type & BTRFS_BLOCK_GROUP_DATA) {
4964 ctl->max_stripe_size = SZ_1G;
4965 ctl->max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4966 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4967 /* For larger filesystems, use larger metadata chunks */
4968 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4969 ctl->max_stripe_size = SZ_1G;
4971 ctl->max_stripe_size = SZ_256M;
4972 ctl->max_chunk_size = ctl->max_stripe_size;
4973 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4974 ctl->max_stripe_size = SZ_32M;
4975 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
4976 ctl->devs_max = min_t(int, ctl->devs_max,
4977 BTRFS_MAX_DEVS_SYS_CHUNK);
4982 /* We don't want a chunk larger than 10% of writable space */
4983 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4984 ctl->max_chunk_size);
4985 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
4988 static void init_alloc_chunk_ctl_policy_zoned(
4989 struct btrfs_fs_devices *fs_devices,
4990 struct alloc_chunk_ctl *ctl)
4992 u64 zone_size = fs_devices->fs_info->zone_size;
4994 int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
4995 int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
4996 u64 min_chunk_size = min_data_stripes * zone_size;
4997 u64 type = ctl->type;
4999 ctl->max_stripe_size = zone_size;
5000 if (type & BTRFS_BLOCK_GROUP_DATA) {
5001 ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5003 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5004 ctl->max_chunk_size = ctl->max_stripe_size;
5005 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5006 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5007 ctl->devs_max = min_t(int, ctl->devs_max,
5008 BTRFS_MAX_DEVS_SYS_CHUNK);
5013 /* We don't want a chunk larger than 10% of writable space */
5014 limit = max(round_down(div_factor(fs_devices->total_rw_bytes, 1),
5017 ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5018 ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5021 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5022 struct alloc_chunk_ctl *ctl)
5024 int index = btrfs_bg_flags_to_raid_index(ctl->type);
5026 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5027 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5028 ctl->devs_max = btrfs_raid_array[index].devs_max;
5030 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5031 ctl->devs_min = btrfs_raid_array[index].devs_min;
5032 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5033 ctl->ncopies = btrfs_raid_array[index].ncopies;
5034 ctl->nparity = btrfs_raid_array[index].nparity;
5037 switch (fs_devices->chunk_alloc_policy) {
5038 case BTRFS_CHUNK_ALLOC_REGULAR:
5039 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5041 case BTRFS_CHUNK_ALLOC_ZONED:
5042 init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5049 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5050 struct alloc_chunk_ctl *ctl,
5051 struct btrfs_device_info *devices_info)
5053 struct btrfs_fs_info *info = fs_devices->fs_info;
5054 struct btrfs_device *device;
5056 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5063 * in the first pass through the devices list, we gather information
5064 * about the available holes on each device.
5066 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5067 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5069 "BTRFS: read-only device in alloc_list\n");
5073 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5074 &device->dev_state) ||
5075 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5078 if (device->total_bytes > device->bytes_used)
5079 total_avail = device->total_bytes - device->bytes_used;
5083 /* If there is no space on this device, skip it. */
5084 if (total_avail < ctl->dev_extent_min)
5087 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5089 if (ret && ret != -ENOSPC)
5093 max_avail = dev_extent_want;
5095 if (max_avail < ctl->dev_extent_min) {
5096 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5098 "%s: devid %llu has no free space, have=%llu want=%llu",
5099 __func__, device->devid, max_avail,
5100 ctl->dev_extent_min);
5104 if (ndevs == fs_devices->rw_devices) {
5105 WARN(1, "%s: found more than %llu devices\n",
5106 __func__, fs_devices->rw_devices);
5109 devices_info[ndevs].dev_offset = dev_offset;
5110 devices_info[ndevs].max_avail = max_avail;
5111 devices_info[ndevs].total_avail = total_avail;
5112 devices_info[ndevs].dev = device;
5118 * now sort the devices by hole size / available space
5120 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5121 btrfs_cmp_device_info, NULL);
5126 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5127 struct btrfs_device_info *devices_info)
5129 /* Number of stripes that count for block group size */
5133 * The primary goal is to maximize the number of stripes, so use as
5134 * many devices as possible, even if the stripes are not maximum sized.
5136 * The DUP profile stores more than one stripe per device, the
5137 * max_avail is the total size so we have to adjust.
5139 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5141 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5143 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5144 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5147 * Use the number of data stripes to figure out how big this chunk is
5148 * really going to be in terms of logical address space, and compare
5149 * that answer with the max chunk size. If it's higher, we try to
5150 * reduce stripe_size.
5152 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5154 * Reduce stripe_size, round it up to a 16MB boundary again and
5155 * then use it, unless it ends up being even bigger than the
5156 * previous value we had already.
5158 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5159 data_stripes), SZ_16M),
5163 /* Align to BTRFS_STRIPE_LEN */
5164 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5165 ctl->chunk_size = ctl->stripe_size * data_stripes;
5170 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5171 struct btrfs_device_info *devices_info)
5173 u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5174 /* Number of stripes that count for block group size */
5178 * It should hold because:
5179 * dev_extent_min == dev_extent_want == zone_size * dev_stripes
5181 ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min);
5183 ctl->stripe_size = zone_size;
5184 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5185 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5187 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */
5188 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5189 ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5190 ctl->stripe_size) + ctl->nparity,
5192 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5193 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5194 ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size);
5197 ctl->chunk_size = ctl->stripe_size * data_stripes;
5202 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5203 struct alloc_chunk_ctl *ctl,
5204 struct btrfs_device_info *devices_info)
5206 struct btrfs_fs_info *info = fs_devices->fs_info;
5209 * Round down to number of usable stripes, devs_increment can be any
5210 * number so we can't use round_down() that requires power of 2, while
5211 * rounddown is safe.
5213 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5215 if (ctl->ndevs < ctl->devs_min) {
5216 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5218 "%s: not enough devices with free space: have=%d minimum required=%d",
5219 __func__, ctl->ndevs, ctl->devs_min);
5224 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5226 switch (fs_devices->chunk_alloc_policy) {
5227 case BTRFS_CHUNK_ALLOC_REGULAR:
5228 return decide_stripe_size_regular(ctl, devices_info);
5229 case BTRFS_CHUNK_ALLOC_ZONED:
5230 return decide_stripe_size_zoned(ctl, devices_info);
5236 static int create_chunk(struct btrfs_trans_handle *trans,
5237 struct alloc_chunk_ctl *ctl,
5238 struct btrfs_device_info *devices_info)
5240 struct btrfs_fs_info *info = trans->fs_info;
5241 struct map_lookup *map = NULL;
5242 struct extent_map_tree *em_tree;
5243 struct extent_map *em;
5244 u64 start = ctl->start;
5245 u64 type = ctl->type;
5250 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5253 map->num_stripes = ctl->num_stripes;
5255 for (i = 0; i < ctl->ndevs; ++i) {
5256 for (j = 0; j < ctl->dev_stripes; ++j) {
5257 int s = i * ctl->dev_stripes + j;
5258 map->stripes[s].dev = devices_info[i].dev;
5259 map->stripes[s].physical = devices_info[i].dev_offset +
5260 j * ctl->stripe_size;
5263 map->stripe_len = BTRFS_STRIPE_LEN;
5264 map->io_align = BTRFS_STRIPE_LEN;
5265 map->io_width = BTRFS_STRIPE_LEN;
5267 map->sub_stripes = ctl->sub_stripes;
5269 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5271 em = alloc_extent_map();
5276 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5277 em->map_lookup = map;
5279 em->len = ctl->chunk_size;
5280 em->block_start = 0;
5281 em->block_len = em->len;
5282 em->orig_block_len = ctl->stripe_size;
5284 em_tree = &info->mapping_tree;
5285 write_lock(&em_tree->lock);
5286 ret = add_extent_mapping(em_tree, em, 0);
5288 write_unlock(&em_tree->lock);
5289 free_extent_map(em);
5292 write_unlock(&em_tree->lock);
5294 ret = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5296 goto error_del_extent;
5298 for (i = 0; i < map->num_stripes; i++) {
5299 struct btrfs_device *dev = map->stripes[i].dev;
5301 btrfs_device_set_bytes_used(dev,
5302 dev->bytes_used + ctl->stripe_size);
5303 if (list_empty(&dev->post_commit_list))
5304 list_add_tail(&dev->post_commit_list,
5305 &trans->transaction->dev_update_list);
5308 atomic64_sub(ctl->stripe_size * map->num_stripes,
5309 &info->free_chunk_space);
5311 free_extent_map(em);
5312 check_raid56_incompat_flag(info, type);
5313 check_raid1c34_incompat_flag(info, type);
5318 write_lock(&em_tree->lock);
5319 remove_extent_mapping(em_tree, em);
5320 write_unlock(&em_tree->lock);
5322 /* One for our allocation */
5323 free_extent_map(em);
5324 /* One for the tree reference */
5325 free_extent_map(em);
5330 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5332 struct btrfs_fs_info *info = trans->fs_info;
5333 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5334 struct btrfs_device_info *devices_info = NULL;
5335 struct alloc_chunk_ctl ctl;
5338 lockdep_assert_held(&info->chunk_mutex);
5340 if (!alloc_profile_is_valid(type, 0)) {
5345 if (list_empty(&fs_devices->alloc_list)) {
5346 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5347 btrfs_debug(info, "%s: no writable device", __func__);
5351 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5352 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5357 ctl.start = find_next_chunk(info);
5359 init_alloc_chunk_ctl(fs_devices, &ctl);
5361 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5366 ret = gather_device_info(fs_devices, &ctl, devices_info);
5370 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5374 ret = create_chunk(trans, &ctl, devices_info);
5377 kfree(devices_info);
5382 * Chunk allocation falls into two parts. The first part does work
5383 * that makes the new allocated chunk usable, but does not do any operation
5384 * that modifies the chunk tree. The second part does the work that
5385 * requires modifying the chunk tree. This division is important for the
5386 * bootstrap process of adding storage to a seed btrfs.
5388 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5389 u64 chunk_offset, u64 chunk_size)
5391 struct btrfs_fs_info *fs_info = trans->fs_info;
5392 struct btrfs_root *extent_root = fs_info->extent_root;
5393 struct btrfs_root *chunk_root = fs_info->chunk_root;
5394 struct btrfs_key key;
5395 struct btrfs_device *device;
5396 struct btrfs_chunk *chunk;
5397 struct btrfs_stripe *stripe;
5398 struct extent_map *em;
5399 struct map_lookup *map;
5406 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5410 map = em->map_lookup;
5411 item_size = btrfs_chunk_item_size(map->num_stripes);
5412 stripe_size = em->orig_block_len;
5414 chunk = kzalloc(item_size, GFP_NOFS);
5421 * Take the device list mutex to prevent races with the final phase of
5422 * a device replace operation that replaces the device object associated
5423 * with the map's stripes, because the device object's id can change
5424 * at any time during that final phase of the device replace operation
5425 * (dev-replace.c:btrfs_dev_replace_finishing()).
5427 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5428 for (i = 0; i < map->num_stripes; i++) {
5429 device = map->stripes[i].dev;
5430 dev_offset = map->stripes[i].physical;
5432 ret = btrfs_update_device(trans, device);
5435 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5436 dev_offset, stripe_size);
5441 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5445 stripe = &chunk->stripe;
5446 for (i = 0; i < map->num_stripes; i++) {
5447 device = map->stripes[i].dev;
5448 dev_offset = map->stripes[i].physical;
5450 btrfs_set_stack_stripe_devid(stripe, device->devid);
5451 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5452 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5455 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5457 btrfs_set_stack_chunk_length(chunk, chunk_size);
5458 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5459 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5460 btrfs_set_stack_chunk_type(chunk, map->type);
5461 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5462 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5463 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5464 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5465 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5467 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5468 key.type = BTRFS_CHUNK_ITEM_KEY;
5469 key.offset = chunk_offset;
5471 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5472 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5474 * TODO: Cleanup of inserted chunk root in case of
5477 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5482 free_extent_map(em);
5486 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5488 struct btrfs_fs_info *fs_info = trans->fs_info;
5492 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5493 ret = btrfs_alloc_chunk(trans, alloc_profile);
5497 alloc_profile = btrfs_system_alloc_profile(fs_info);
5498 ret = btrfs_alloc_chunk(trans, alloc_profile);
5502 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5504 const int index = btrfs_bg_flags_to_raid_index(map->type);
5506 return btrfs_raid_array[index].tolerated_failures;
5509 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5511 struct extent_map *em;
5512 struct map_lookup *map;
5517 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5521 map = em->map_lookup;
5522 for (i = 0; i < map->num_stripes; i++) {
5523 if (test_bit(BTRFS_DEV_STATE_MISSING,
5524 &map->stripes[i].dev->dev_state)) {
5528 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5529 &map->stripes[i].dev->dev_state)) {
5536 * If the number of missing devices is larger than max errors,
5537 * we can not write the data into that chunk successfully, so
5540 if (miss_ndevs > btrfs_chunk_max_errors(map))
5543 free_extent_map(em);
5547 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5549 struct extent_map *em;
5552 write_lock(&tree->lock);
5553 em = lookup_extent_mapping(tree, 0, (u64)-1);
5555 remove_extent_mapping(tree, em);
5556 write_unlock(&tree->lock);
5560 free_extent_map(em);
5561 /* once for the tree */
5562 free_extent_map(em);
5566 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5568 struct extent_map *em;
5569 struct map_lookup *map;
5572 em = btrfs_get_chunk_map(fs_info, logical, len);
5575 * We could return errors for these cases, but that could get
5576 * ugly and we'd probably do the same thing which is just not do
5577 * anything else and exit, so return 1 so the callers don't try
5578 * to use other copies.
5582 map = em->map_lookup;
5583 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5584 ret = map->num_stripes;
5585 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5586 ret = map->sub_stripes;
5587 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5589 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5591 * There could be two corrupted data stripes, we need
5592 * to loop retry in order to rebuild the correct data.
5594 * Fail a stripe at a time on every retry except the
5595 * stripe under reconstruction.
5597 ret = map->num_stripes;
5600 free_extent_map(em);
5602 down_read(&fs_info->dev_replace.rwsem);
5603 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5604 fs_info->dev_replace.tgtdev)
5606 up_read(&fs_info->dev_replace.rwsem);
5611 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5614 struct extent_map *em;
5615 struct map_lookup *map;
5616 unsigned long len = fs_info->sectorsize;
5618 em = btrfs_get_chunk_map(fs_info, logical, len);
5620 if (!WARN_ON(IS_ERR(em))) {
5621 map = em->map_lookup;
5622 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5623 len = map->stripe_len * nr_data_stripes(map);
5624 free_extent_map(em);
5629 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5631 struct extent_map *em;
5632 struct map_lookup *map;
5635 em = btrfs_get_chunk_map(fs_info, logical, len);
5637 if(!WARN_ON(IS_ERR(em))) {
5638 map = em->map_lookup;
5639 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5641 free_extent_map(em);
5646 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5647 struct map_lookup *map, int first,
5648 int dev_replace_is_ongoing)
5652 int preferred_mirror;
5654 struct btrfs_device *srcdev;
5657 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5659 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5660 num_stripes = map->sub_stripes;
5662 num_stripes = map->num_stripes;
5664 switch (fs_info->fs_devices->read_policy) {
5666 /* Shouldn't happen, just warn and use pid instead of failing */
5667 btrfs_warn_rl(fs_info,
5668 "unknown read_policy type %u, reset to pid",
5669 fs_info->fs_devices->read_policy);
5670 fs_info->fs_devices->read_policy = BTRFS_READ_POLICY_PID;
5672 case BTRFS_READ_POLICY_PID:
5673 preferred_mirror = first + (current->pid % num_stripes);
5677 if (dev_replace_is_ongoing &&
5678 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5679 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5680 srcdev = fs_info->dev_replace.srcdev;
5685 * try to avoid the drive that is the source drive for a
5686 * dev-replace procedure, only choose it if no other non-missing
5687 * mirror is available
5689 for (tolerance = 0; tolerance < 2; tolerance++) {
5690 if (map->stripes[preferred_mirror].dev->bdev &&
5691 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5692 return preferred_mirror;
5693 for (i = first; i < first + num_stripes; i++) {
5694 if (map->stripes[i].dev->bdev &&
5695 (tolerance || map->stripes[i].dev != srcdev))
5700 /* we couldn't find one that doesn't fail. Just return something
5701 * and the io error handling code will clean up eventually
5703 return preferred_mirror;
5706 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5707 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5714 for (i = 0; i < num_stripes - 1; i++) {
5715 /* Swap if parity is on a smaller index */
5716 if (bbio->raid_map[i] > bbio->raid_map[i + 1]) {
5717 swap(bbio->stripes[i], bbio->stripes[i + 1]);
5718 swap(bbio->raid_map[i], bbio->raid_map[i + 1]);
5725 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5727 struct btrfs_bio *bbio = kzalloc(
5728 /* the size of the btrfs_bio */
5729 sizeof(struct btrfs_bio) +
5730 /* plus the variable array for the stripes */
5731 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5732 /* plus the variable array for the tgt dev */
5733 sizeof(int) * (real_stripes) +
5735 * plus the raid_map, which includes both the tgt dev
5738 sizeof(u64) * (total_stripes),
5739 GFP_NOFS|__GFP_NOFAIL);
5741 atomic_set(&bbio->error, 0);
5742 refcount_set(&bbio->refs, 1);
5744 bbio->tgtdev_map = (int *)(bbio->stripes + total_stripes);
5745 bbio->raid_map = (u64 *)(bbio->tgtdev_map + real_stripes);
5750 void btrfs_get_bbio(struct btrfs_bio *bbio)
5752 WARN_ON(!refcount_read(&bbio->refs));
5753 refcount_inc(&bbio->refs);
5756 void btrfs_put_bbio(struct btrfs_bio *bbio)
5760 if (refcount_dec_and_test(&bbio->refs))
5764 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5766 * Please note that, discard won't be sent to target device of device
5769 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5770 u64 logical, u64 *length_ret,
5771 struct btrfs_bio **bbio_ret)
5773 struct extent_map *em;
5774 struct map_lookup *map;
5775 struct btrfs_bio *bbio;
5776 u64 length = *length_ret;
5780 u64 stripe_end_offset;
5787 u32 sub_stripes = 0;
5788 u64 stripes_per_dev = 0;
5789 u32 remaining_stripes = 0;
5790 u32 last_stripe = 0;
5794 /* discard always return a bbio */
5797 em = btrfs_get_chunk_map(fs_info, logical, length);
5801 map = em->map_lookup;
5802 /* we don't discard raid56 yet */
5803 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5808 offset = logical - em->start;
5809 length = min_t(u64, em->start + em->len - logical, length);
5810 *length_ret = length;
5812 stripe_len = map->stripe_len;
5814 * stripe_nr counts the total number of stripes we have to stride
5815 * to get to this block
5817 stripe_nr = div64_u64(offset, stripe_len);
5819 /* stripe_offset is the offset of this block in its stripe */
5820 stripe_offset = offset - stripe_nr * stripe_len;
5822 stripe_nr_end = round_up(offset + length, map->stripe_len);
5823 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5824 stripe_cnt = stripe_nr_end - stripe_nr;
5825 stripe_end_offset = stripe_nr_end * map->stripe_len -
5828 * after this, stripe_nr is the number of stripes on this
5829 * device we have to walk to find the data, and stripe_index is
5830 * the number of our device in the stripe array
5834 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5835 BTRFS_BLOCK_GROUP_RAID10)) {
5836 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5839 sub_stripes = map->sub_stripes;
5841 factor = map->num_stripes / sub_stripes;
5842 num_stripes = min_t(u64, map->num_stripes,
5843 sub_stripes * stripe_cnt);
5844 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5845 stripe_index *= sub_stripes;
5846 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5847 &remaining_stripes);
5848 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5849 last_stripe *= sub_stripes;
5850 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5851 BTRFS_BLOCK_GROUP_DUP)) {
5852 num_stripes = map->num_stripes;
5854 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5858 bbio = alloc_btrfs_bio(num_stripes, 0);
5864 for (i = 0; i < num_stripes; i++) {
5865 bbio->stripes[i].physical =
5866 map->stripes[stripe_index].physical +
5867 stripe_offset + stripe_nr * map->stripe_len;
5868 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5870 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5871 BTRFS_BLOCK_GROUP_RAID10)) {
5872 bbio->stripes[i].length = stripes_per_dev *
5875 if (i / sub_stripes < remaining_stripes)
5876 bbio->stripes[i].length +=
5880 * Special for the first stripe and
5883 * |-------|...|-------|
5887 if (i < sub_stripes)
5888 bbio->stripes[i].length -=
5891 if (stripe_index >= last_stripe &&
5892 stripe_index <= (last_stripe +
5894 bbio->stripes[i].length -=
5897 if (i == sub_stripes - 1)
5900 bbio->stripes[i].length = length;
5904 if (stripe_index == map->num_stripes) {
5911 bbio->map_type = map->type;
5912 bbio->num_stripes = num_stripes;
5914 free_extent_map(em);
5919 * In dev-replace case, for repair case (that's the only case where the mirror
5920 * is selected explicitly when calling btrfs_map_block), blocks left of the
5921 * left cursor can also be read from the target drive.
5923 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5925 * For READ, it also needs to be supported using the same mirror number.
5927 * If the requested block is not left of the left cursor, EIO is returned. This
5928 * can happen because btrfs_num_copies() returns one more in the dev-replace
5931 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5932 u64 logical, u64 length,
5933 u64 srcdev_devid, int *mirror_num,
5936 struct btrfs_bio *bbio = NULL;
5938 int index_srcdev = 0;
5940 u64 physical_of_found = 0;
5944 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5945 logical, &length, &bbio, 0, 0);
5947 ASSERT(bbio == NULL);
5951 num_stripes = bbio->num_stripes;
5952 if (*mirror_num > num_stripes) {
5954 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5955 * that means that the requested area is not left of the left
5958 btrfs_put_bbio(bbio);
5963 * process the rest of the function using the mirror_num of the source
5964 * drive. Therefore look it up first. At the end, patch the device
5965 * pointer to the one of the target drive.
5967 for (i = 0; i < num_stripes; i++) {
5968 if (bbio->stripes[i].dev->devid != srcdev_devid)
5972 * In case of DUP, in order to keep it simple, only add the
5973 * mirror with the lowest physical address
5976 physical_of_found <= bbio->stripes[i].physical)
5981 physical_of_found = bbio->stripes[i].physical;
5984 btrfs_put_bbio(bbio);
5990 *mirror_num = index_srcdev + 1;
5991 *physical = physical_of_found;
5995 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
5997 struct btrfs_block_group *cache;
6000 /* Non zoned filesystem does not use "to_copy" flag */
6001 if (!btrfs_is_zoned(fs_info))
6004 cache = btrfs_lookup_block_group(fs_info, logical);
6006 spin_lock(&cache->lock);
6007 ret = cache->to_copy;
6008 spin_unlock(&cache->lock);
6010 btrfs_put_block_group(cache);
6014 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
6015 struct btrfs_bio **bbio_ret,
6016 struct btrfs_dev_replace *dev_replace,
6018 int *num_stripes_ret, int *max_errors_ret)
6020 struct btrfs_bio *bbio = *bbio_ret;
6021 u64 srcdev_devid = dev_replace->srcdev->devid;
6022 int tgtdev_indexes = 0;
6023 int num_stripes = *num_stripes_ret;
6024 int max_errors = *max_errors_ret;
6027 if (op == BTRFS_MAP_WRITE) {
6028 int index_where_to_add;
6031 * A block group which have "to_copy" set will eventually
6032 * copied by dev-replace process. We can avoid cloning IO here.
6034 if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6038 * duplicate the write operations while the dev replace
6039 * procedure is running. Since the copying of the old disk to
6040 * the new disk takes place at run time while the filesystem is
6041 * mounted writable, the regular write operations to the old
6042 * disk have to be duplicated to go to the new disk as well.
6044 * Note that device->missing is handled by the caller, and that
6045 * the write to the old disk is already set up in the stripes
6048 index_where_to_add = num_stripes;
6049 for (i = 0; i < num_stripes; i++) {
6050 if (bbio->stripes[i].dev->devid == srcdev_devid) {
6051 /* write to new disk, too */
6052 struct btrfs_bio_stripe *new =
6053 bbio->stripes + index_where_to_add;
6054 struct btrfs_bio_stripe *old =
6057 new->physical = old->physical;
6058 new->length = old->length;
6059 new->dev = dev_replace->tgtdev;
6060 bbio->tgtdev_map[i] = index_where_to_add;
6061 index_where_to_add++;
6066 num_stripes = index_where_to_add;
6067 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
6068 int index_srcdev = 0;
6070 u64 physical_of_found = 0;
6073 * During the dev-replace procedure, the target drive can also
6074 * be used to read data in case it is needed to repair a corrupt
6075 * block elsewhere. This is possible if the requested area is
6076 * left of the left cursor. In this area, the target drive is a
6077 * full copy of the source drive.
6079 for (i = 0; i < num_stripes; i++) {
6080 if (bbio->stripes[i].dev->devid == srcdev_devid) {
6082 * In case of DUP, in order to keep it simple,
6083 * only add the mirror with the lowest physical
6087 physical_of_found <=
6088 bbio->stripes[i].physical)
6092 physical_of_found = bbio->stripes[i].physical;
6096 struct btrfs_bio_stripe *tgtdev_stripe =
6097 bbio->stripes + num_stripes;
6099 tgtdev_stripe->physical = physical_of_found;
6100 tgtdev_stripe->length =
6101 bbio->stripes[index_srcdev].length;
6102 tgtdev_stripe->dev = dev_replace->tgtdev;
6103 bbio->tgtdev_map[index_srcdev] = num_stripes;
6110 *num_stripes_ret = num_stripes;
6111 *max_errors_ret = max_errors;
6112 bbio->num_tgtdevs = tgtdev_indexes;
6116 static bool need_full_stripe(enum btrfs_map_op op)
6118 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
6122 * Calculate the geometry of a particular (address, len) tuple. This
6123 * information is used to calculate how big a particular bio can get before it
6124 * straddles a stripe.
6126 * @fs_info: the filesystem
6127 * @em: mapping containing the logical extent
6128 * @op: type of operation - write or read
6129 * @logical: address that we want to figure out the geometry of
6130 * @len: the length of IO we are going to perform, starting at @logical
6131 * @io_geom: pointer used to return values
6133 * Returns < 0 in case a chunk for the given logical address cannot be found,
6134 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
6136 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, struct extent_map *em,
6137 enum btrfs_map_op op, u64 logical, u64 len,
6138 struct btrfs_io_geometry *io_geom)
6140 struct map_lookup *map;
6145 u64 raid56_full_stripe_start = (u64)-1;
6148 ASSERT(op != BTRFS_MAP_DISCARD);
6150 map = em->map_lookup;
6151 /* Offset of this logical address in the chunk */
6152 offset = logical - em->start;
6153 /* Len of a stripe in a chunk */
6154 stripe_len = map->stripe_len;
6155 /* Stripe wher this block falls in */
6156 stripe_nr = div64_u64(offset, stripe_len);
6157 /* Offset of stripe in the chunk */
6158 stripe_offset = stripe_nr * stripe_len;
6159 if (offset < stripe_offset) {
6161 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
6162 stripe_offset, offset, em->start, logical, stripe_len);
6166 /* stripe_offset is the offset of this block in its stripe */
6167 stripe_offset = offset - stripe_offset;
6168 data_stripes = nr_data_stripes(map);
6170 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6171 u64 max_len = stripe_len - stripe_offset;
6174 * In case of raid56, we need to know the stripe aligned start
6176 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6177 unsigned long full_stripe_len = stripe_len * data_stripes;
6178 raid56_full_stripe_start = offset;
6181 * Allow a write of a full stripe, but make sure we
6182 * don't allow straddling of stripes
6184 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6186 raid56_full_stripe_start *= full_stripe_len;
6189 * For writes to RAID[56], allow a full stripeset across
6190 * all disks. For other RAID types and for RAID[56]
6191 * reads, just allow a single stripe (on a single disk).
6193 if (op == BTRFS_MAP_WRITE) {
6194 max_len = stripe_len * data_stripes -
6195 (offset - raid56_full_stripe_start);
6198 len = min_t(u64, em->len - offset, max_len);
6200 len = em->len - offset;
6204 io_geom->offset = offset;
6205 io_geom->stripe_len = stripe_len;
6206 io_geom->stripe_nr = stripe_nr;
6207 io_geom->stripe_offset = stripe_offset;
6208 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6213 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6214 enum btrfs_map_op op,
6215 u64 logical, u64 *length,
6216 struct btrfs_bio **bbio_ret,
6217 int mirror_num, int need_raid_map)
6219 struct extent_map *em;
6220 struct map_lookup *map;
6230 int tgtdev_indexes = 0;
6231 struct btrfs_bio *bbio = NULL;
6232 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6233 int dev_replace_is_ongoing = 0;
6234 int num_alloc_stripes;
6235 int patch_the_first_stripe_for_dev_replace = 0;
6236 u64 physical_to_patch_in_first_stripe = 0;
6237 u64 raid56_full_stripe_start = (u64)-1;
6238 struct btrfs_io_geometry geom;
6241 ASSERT(op != BTRFS_MAP_DISCARD);
6243 em = btrfs_get_chunk_map(fs_info, logical, *length);
6244 ASSERT(!IS_ERR(em));
6246 ret = btrfs_get_io_geometry(fs_info, em, op, logical, *length, &geom);
6250 map = em->map_lookup;
6253 stripe_len = geom.stripe_len;
6254 stripe_nr = geom.stripe_nr;
6255 stripe_offset = geom.stripe_offset;
6256 raid56_full_stripe_start = geom.raid56_stripe_offset;
6257 data_stripes = nr_data_stripes(map);
6259 down_read(&dev_replace->rwsem);
6260 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6262 * Hold the semaphore for read during the whole operation, write is
6263 * requested at commit time but must wait.
6265 if (!dev_replace_is_ongoing)
6266 up_read(&dev_replace->rwsem);
6268 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6269 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6270 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6271 dev_replace->srcdev->devid,
6273 &physical_to_patch_in_first_stripe);
6277 patch_the_first_stripe_for_dev_replace = 1;
6278 } else if (mirror_num > map->num_stripes) {
6284 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6285 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6287 if (!need_full_stripe(op))
6289 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6290 if (need_full_stripe(op))
6291 num_stripes = map->num_stripes;
6292 else if (mirror_num)
6293 stripe_index = mirror_num - 1;
6295 stripe_index = find_live_mirror(fs_info, map, 0,
6296 dev_replace_is_ongoing);
6297 mirror_num = stripe_index + 1;
6300 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6301 if (need_full_stripe(op)) {
6302 num_stripes = map->num_stripes;
6303 } else if (mirror_num) {
6304 stripe_index = mirror_num - 1;
6309 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6310 u32 factor = map->num_stripes / map->sub_stripes;
6312 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6313 stripe_index *= map->sub_stripes;
6315 if (need_full_stripe(op))
6316 num_stripes = map->sub_stripes;
6317 else if (mirror_num)
6318 stripe_index += mirror_num - 1;
6320 int old_stripe_index = stripe_index;
6321 stripe_index = find_live_mirror(fs_info, map,
6323 dev_replace_is_ongoing);
6324 mirror_num = stripe_index - old_stripe_index + 1;
6327 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6328 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6329 /* push stripe_nr back to the start of the full stripe */
6330 stripe_nr = div64_u64(raid56_full_stripe_start,
6331 stripe_len * data_stripes);
6333 /* RAID[56] write or recovery. Return all stripes */
6334 num_stripes = map->num_stripes;
6335 max_errors = nr_parity_stripes(map);
6337 *length = map->stripe_len;
6342 * Mirror #0 or #1 means the original data block.
6343 * Mirror #2 is RAID5 parity block.
6344 * Mirror #3 is RAID6 Q block.
6346 stripe_nr = div_u64_rem(stripe_nr,
6347 data_stripes, &stripe_index);
6349 stripe_index = data_stripes + mirror_num - 2;
6351 /* We distribute the parity blocks across stripes */
6352 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6354 if (!need_full_stripe(op) && mirror_num <= 1)
6359 * after this, stripe_nr is the number of stripes on this
6360 * device we have to walk to find the data, and stripe_index is
6361 * the number of our device in the stripe array
6363 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6365 mirror_num = stripe_index + 1;
6367 if (stripe_index >= map->num_stripes) {
6369 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6370 stripe_index, map->num_stripes);
6375 num_alloc_stripes = num_stripes;
6376 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6377 if (op == BTRFS_MAP_WRITE)
6378 num_alloc_stripes <<= 1;
6379 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6380 num_alloc_stripes++;
6381 tgtdev_indexes = num_stripes;
6384 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6390 for (i = 0; i < num_stripes; i++) {
6391 bbio->stripes[i].physical = map->stripes[stripe_index].physical +
6392 stripe_offset + stripe_nr * map->stripe_len;
6393 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
6397 /* build raid_map */
6398 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6399 (need_full_stripe(op) || mirror_num > 1)) {
6403 /* Work out the disk rotation on this stripe-set */
6404 div_u64_rem(stripe_nr, num_stripes, &rot);
6406 /* Fill in the logical address of each stripe */
6407 tmp = stripe_nr * data_stripes;
6408 for (i = 0; i < data_stripes; i++)
6409 bbio->raid_map[(i+rot) % num_stripes] =
6410 em->start + (tmp + i) * map->stripe_len;
6412 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6413 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6414 bbio->raid_map[(i+rot+1) % num_stripes] =
6417 sort_parity_stripes(bbio, num_stripes);
6420 if (need_full_stripe(op))
6421 max_errors = btrfs_chunk_max_errors(map);
6423 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6424 need_full_stripe(op)) {
6425 handle_ops_on_dev_replace(op, &bbio, dev_replace, logical,
6426 &num_stripes, &max_errors);
6430 bbio->map_type = map->type;
6431 bbio->num_stripes = num_stripes;
6432 bbio->max_errors = max_errors;
6433 bbio->mirror_num = mirror_num;
6436 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6437 * mirror_num == num_stripes + 1 && dev_replace target drive is
6438 * available as a mirror
6440 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6441 WARN_ON(num_stripes > 1);
6442 bbio->stripes[0].dev = dev_replace->tgtdev;
6443 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6444 bbio->mirror_num = map->num_stripes + 1;
6447 if (dev_replace_is_ongoing) {
6448 lockdep_assert_held(&dev_replace->rwsem);
6449 /* Unlock and let waiting writers proceed */
6450 up_read(&dev_replace->rwsem);
6452 free_extent_map(em);
6456 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6457 u64 logical, u64 *length,
6458 struct btrfs_bio **bbio_ret, int mirror_num)
6460 if (op == BTRFS_MAP_DISCARD)
6461 return __btrfs_map_block_for_discard(fs_info, logical,
6464 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6468 /* For Scrub/replace */
6469 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6470 u64 logical, u64 *length,
6471 struct btrfs_bio **bbio_ret)
6473 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6476 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6478 bio->bi_private = bbio->private;
6479 bio->bi_end_io = bbio->end_io;
6482 btrfs_put_bbio(bbio);
6485 static void btrfs_end_bio(struct bio *bio)
6487 struct btrfs_bio *bbio = bio->bi_private;
6488 int is_orig_bio = 0;
6490 if (bio->bi_status) {
6491 atomic_inc(&bbio->error);
6492 if (bio->bi_status == BLK_STS_IOERR ||
6493 bio->bi_status == BLK_STS_TARGET) {
6494 struct btrfs_device *dev = btrfs_io_bio(bio)->device;
6497 if (btrfs_op(bio) == BTRFS_MAP_WRITE)
6498 btrfs_dev_stat_inc_and_print(dev,
6499 BTRFS_DEV_STAT_WRITE_ERRS);
6500 else if (!(bio->bi_opf & REQ_RAHEAD))
6501 btrfs_dev_stat_inc_and_print(dev,
6502 BTRFS_DEV_STAT_READ_ERRS);
6503 if (bio->bi_opf & REQ_PREFLUSH)
6504 btrfs_dev_stat_inc_and_print(dev,
6505 BTRFS_DEV_STAT_FLUSH_ERRS);
6509 if (bio == bbio->orig_bio)
6512 btrfs_bio_counter_dec(bbio->fs_info);
6514 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6517 bio = bbio->orig_bio;
6520 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6521 /* only send an error to the higher layers if it is
6522 * beyond the tolerance of the btrfs bio
6524 if (atomic_read(&bbio->error) > bbio->max_errors) {
6525 bio->bi_status = BLK_STS_IOERR;
6528 * this bio is actually up to date, we didn't
6529 * go over the max number of errors
6531 bio->bi_status = BLK_STS_OK;
6534 btrfs_end_bbio(bbio, bio);
6535 } else if (!is_orig_bio) {
6540 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6541 u64 physical, struct btrfs_device *dev)
6543 struct btrfs_fs_info *fs_info = bbio->fs_info;
6545 bio->bi_private = bbio;
6546 btrfs_io_bio(bio)->device = dev;
6547 bio->bi_end_io = btrfs_end_bio;
6548 bio->bi_iter.bi_sector = physical >> 9;
6550 * For zone append writing, bi_sector must point the beginning of the
6553 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
6554 if (btrfs_dev_is_sequential(dev, physical)) {
6555 u64 zone_start = round_down(physical, fs_info->zone_size);
6557 bio->bi_iter.bi_sector = zone_start >> SECTOR_SHIFT;
6559 bio->bi_opf &= ~REQ_OP_ZONE_APPEND;
6560 bio->bi_opf |= REQ_OP_WRITE;
6563 btrfs_debug_in_rcu(fs_info,
6564 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6565 bio_op(bio), bio->bi_opf, bio->bi_iter.bi_sector,
6566 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6567 dev->devid, bio->bi_iter.bi_size);
6568 bio_set_dev(bio, dev->bdev);
6570 btrfs_bio_counter_inc_noblocked(fs_info);
6572 btrfsic_submit_bio(bio);
6575 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6577 atomic_inc(&bbio->error);
6578 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6579 /* Should be the original bio. */
6580 WARN_ON(bio != bbio->orig_bio);
6582 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6583 bio->bi_iter.bi_sector = logical >> 9;
6584 if (atomic_read(&bbio->error) > bbio->max_errors)
6585 bio->bi_status = BLK_STS_IOERR;
6587 bio->bi_status = BLK_STS_OK;
6588 btrfs_end_bbio(bbio, bio);
6592 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6595 struct btrfs_device *dev;
6596 struct bio *first_bio = bio;
6597 u64 logical = bio->bi_iter.bi_sector << 9;
6603 struct btrfs_bio *bbio = NULL;
6605 length = bio->bi_iter.bi_size;
6606 map_length = length;
6608 btrfs_bio_counter_inc_blocked(fs_info);
6609 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6610 &map_length, &bbio, mirror_num, 1);
6612 btrfs_bio_counter_dec(fs_info);
6613 return errno_to_blk_status(ret);
6616 total_devs = bbio->num_stripes;
6617 bbio->orig_bio = first_bio;
6618 bbio->private = first_bio->bi_private;
6619 bbio->end_io = first_bio->bi_end_io;
6620 bbio->fs_info = fs_info;
6621 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6623 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6624 ((btrfs_op(bio) == BTRFS_MAP_WRITE) || (mirror_num > 1))) {
6625 /* In this case, map_length has been set to the length of
6626 a single stripe; not the whole write */
6627 if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
6628 ret = raid56_parity_write(fs_info, bio, bbio,
6631 ret = raid56_parity_recover(fs_info, bio, bbio,
6632 map_length, mirror_num, 1);
6635 btrfs_bio_counter_dec(fs_info);
6636 return errno_to_blk_status(ret);
6639 if (map_length < length) {
6641 "mapping failed logical %llu bio len %llu len %llu",
6642 logical, length, map_length);
6646 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6647 dev = bbio->stripes[dev_nr].dev;
6648 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6650 (btrfs_op(first_bio) == BTRFS_MAP_WRITE &&
6651 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6652 bbio_error(bbio, first_bio, logical);
6656 if (dev_nr < total_devs - 1)
6657 bio = btrfs_bio_clone(first_bio);
6661 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical, dev);
6663 btrfs_bio_counter_dec(fs_info);
6668 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6671 * If devid and uuid are both specified, the match must be exact, otherwise
6672 * only devid is used.
6674 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6675 u64 devid, u8 *uuid, u8 *fsid)
6677 struct btrfs_device *device;
6678 struct btrfs_fs_devices *seed_devs;
6680 if (!fsid || !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6681 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6682 if (device->devid == devid &&
6683 (!uuid || memcmp(device->uuid, uuid,
6684 BTRFS_UUID_SIZE) == 0))
6689 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6691 !memcmp(seed_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6692 list_for_each_entry(device, &seed_devs->devices,
6694 if (device->devid == devid &&
6695 (!uuid || memcmp(device->uuid, uuid,
6696 BTRFS_UUID_SIZE) == 0))
6705 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6706 u64 devid, u8 *dev_uuid)
6708 struct btrfs_device *device;
6709 unsigned int nofs_flag;
6712 * We call this under the chunk_mutex, so we want to use NOFS for this
6713 * allocation, however we don't want to change btrfs_alloc_device() to
6714 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6717 nofs_flag = memalloc_nofs_save();
6718 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6719 memalloc_nofs_restore(nofs_flag);
6723 list_add(&device->dev_list, &fs_devices->devices);
6724 device->fs_devices = fs_devices;
6725 fs_devices->num_devices++;
6727 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6728 fs_devices->missing_devices++;
6734 * btrfs_alloc_device - allocate struct btrfs_device
6735 * @fs_info: used only for generating a new devid, can be NULL if
6736 * devid is provided (i.e. @devid != NULL).
6737 * @devid: a pointer to devid for this device. If NULL a new devid
6739 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6742 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6743 * on error. Returned struct is not linked onto any lists and must be
6744 * destroyed with btrfs_free_device.
6746 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6750 struct btrfs_device *dev;
6753 if (WARN_ON(!devid && !fs_info))
6754 return ERR_PTR(-EINVAL);
6756 dev = __alloc_device(fs_info);
6765 ret = find_next_devid(fs_info, &tmp);
6767 btrfs_free_device(dev);
6768 return ERR_PTR(ret);
6774 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6776 generate_random_uuid(dev->uuid);
6781 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6782 u64 devid, u8 *uuid, bool error)
6785 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6788 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6792 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6794 int index = btrfs_bg_flags_to_raid_index(type);
6795 int ncopies = btrfs_raid_array[index].ncopies;
6796 const int nparity = btrfs_raid_array[index].nparity;
6800 data_stripes = num_stripes - nparity;
6802 data_stripes = num_stripes / ncopies;
6804 return div_u64(chunk_len, data_stripes);
6807 #if BITS_PER_LONG == 32
6809 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
6810 * can't be accessed on 32bit systems.
6812 * This function do mount time check to reject the fs if it already has
6813 * metadata chunk beyond that limit.
6815 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6816 u64 logical, u64 length, u64 type)
6818 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6821 if (logical + length < MAX_LFS_FILESIZE)
6824 btrfs_err_32bit_limit(fs_info);
6829 * This is to give early warning for any metadata chunk reaching
6830 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
6831 * Although we can still access the metadata, it's not going to be possible
6832 * once the limit is reached.
6834 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6835 u64 logical, u64 length, u64 type)
6837 if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6840 if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6843 btrfs_warn_32bit_limit(fs_info);
6847 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6848 struct btrfs_chunk *chunk)
6850 struct btrfs_fs_info *fs_info = leaf->fs_info;
6851 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6852 struct map_lookup *map;
6853 struct extent_map *em;
6858 u8 uuid[BTRFS_UUID_SIZE];
6863 logical = key->offset;
6864 length = btrfs_chunk_length(leaf, chunk);
6865 type = btrfs_chunk_type(leaf, chunk);
6866 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6868 #if BITS_PER_LONG == 32
6869 ret = check_32bit_meta_chunk(fs_info, logical, length, type);
6872 warn_32bit_meta_chunk(fs_info, logical, length, type);
6876 * Only need to verify chunk item if we're reading from sys chunk array,
6877 * as chunk item in tree block is already verified by tree-checker.
6879 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6880 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6885 read_lock(&map_tree->lock);
6886 em = lookup_extent_mapping(map_tree, logical, 1);
6887 read_unlock(&map_tree->lock);
6889 /* already mapped? */
6890 if (em && em->start <= logical && em->start + em->len > logical) {
6891 free_extent_map(em);
6894 free_extent_map(em);
6897 em = alloc_extent_map();
6900 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6902 free_extent_map(em);
6906 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6907 em->map_lookup = map;
6908 em->start = logical;
6911 em->block_start = 0;
6912 em->block_len = em->len;
6914 map->num_stripes = num_stripes;
6915 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6916 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6917 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6919 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6920 map->verified_stripes = 0;
6921 em->orig_block_len = calc_stripe_length(type, em->len,
6923 for (i = 0; i < num_stripes; i++) {
6924 map->stripes[i].physical =
6925 btrfs_stripe_offset_nr(leaf, chunk, i);
6926 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6927 read_extent_buffer(leaf, uuid, (unsigned long)
6928 btrfs_stripe_dev_uuid_nr(chunk, i),
6930 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6932 if (!map->stripes[i].dev &&
6933 !btrfs_test_opt(fs_info, DEGRADED)) {
6934 free_extent_map(em);
6935 btrfs_report_missing_device(fs_info, devid, uuid, true);
6938 if (!map->stripes[i].dev) {
6939 map->stripes[i].dev =
6940 add_missing_dev(fs_info->fs_devices, devid,
6942 if (IS_ERR(map->stripes[i].dev)) {
6943 free_extent_map(em);
6945 "failed to init missing dev %llu: %ld",
6946 devid, PTR_ERR(map->stripes[i].dev));
6947 return PTR_ERR(map->stripes[i].dev);
6949 btrfs_report_missing_device(fs_info, devid, uuid, false);
6951 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6952 &(map->stripes[i].dev->dev_state));
6956 write_lock(&map_tree->lock);
6957 ret = add_extent_mapping(map_tree, em, 0);
6958 write_unlock(&map_tree->lock);
6961 "failed to add chunk map, start=%llu len=%llu: %d",
6962 em->start, em->len, ret);
6964 free_extent_map(em);
6969 static void fill_device_from_item(struct extent_buffer *leaf,
6970 struct btrfs_dev_item *dev_item,
6971 struct btrfs_device *device)
6975 device->devid = btrfs_device_id(leaf, dev_item);
6976 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6977 device->total_bytes = device->disk_total_bytes;
6978 device->commit_total_bytes = device->disk_total_bytes;
6979 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6980 device->commit_bytes_used = device->bytes_used;
6981 device->type = btrfs_device_type(leaf, dev_item);
6982 device->io_align = btrfs_device_io_align(leaf, dev_item);
6983 device->io_width = btrfs_device_io_width(leaf, dev_item);
6984 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6985 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6986 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6988 ptr = btrfs_device_uuid(dev_item);
6989 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6992 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6995 struct btrfs_fs_devices *fs_devices;
6998 lockdep_assert_held(&uuid_mutex);
7001 /* This will match only for multi-device seed fs */
7002 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
7003 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7007 fs_devices = find_fsid(fsid, NULL);
7009 if (!btrfs_test_opt(fs_info, DEGRADED))
7010 return ERR_PTR(-ENOENT);
7012 fs_devices = alloc_fs_devices(fsid, NULL);
7013 if (IS_ERR(fs_devices))
7016 fs_devices->seeding = true;
7017 fs_devices->opened = 1;
7022 * Upon first call for a seed fs fsid, just create a private copy of the
7023 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7025 fs_devices = clone_fs_devices(fs_devices);
7026 if (IS_ERR(fs_devices))
7029 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
7031 free_fs_devices(fs_devices);
7032 return ERR_PTR(ret);
7035 if (!fs_devices->seeding) {
7036 close_fs_devices(fs_devices);
7037 free_fs_devices(fs_devices);
7038 return ERR_PTR(-EINVAL);
7041 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7046 static int read_one_dev(struct extent_buffer *leaf,
7047 struct btrfs_dev_item *dev_item)
7049 struct btrfs_fs_info *fs_info = leaf->fs_info;
7050 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7051 struct btrfs_device *device;
7054 u8 fs_uuid[BTRFS_FSID_SIZE];
7055 u8 dev_uuid[BTRFS_UUID_SIZE];
7057 devid = btrfs_device_id(leaf, dev_item);
7058 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7060 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7063 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7064 fs_devices = open_seed_devices(fs_info, fs_uuid);
7065 if (IS_ERR(fs_devices))
7066 return PTR_ERR(fs_devices);
7069 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
7072 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7073 btrfs_report_missing_device(fs_info, devid,
7078 device = add_missing_dev(fs_devices, devid, dev_uuid);
7079 if (IS_ERR(device)) {
7081 "failed to add missing dev %llu: %ld",
7082 devid, PTR_ERR(device));
7083 return PTR_ERR(device);
7085 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7087 if (!device->bdev) {
7088 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7089 btrfs_report_missing_device(fs_info,
7090 devid, dev_uuid, true);
7093 btrfs_report_missing_device(fs_info, devid,
7097 if (!device->bdev &&
7098 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7100 * this happens when a device that was properly setup
7101 * in the device info lists suddenly goes bad.
7102 * device->bdev is NULL, and so we have to set
7103 * device->missing to one here
7105 device->fs_devices->missing_devices++;
7106 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7109 /* Move the device to its own fs_devices */
7110 if (device->fs_devices != fs_devices) {
7111 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7112 &device->dev_state));
7114 list_move(&device->dev_list, &fs_devices->devices);
7115 device->fs_devices->num_devices--;
7116 fs_devices->num_devices++;
7118 device->fs_devices->missing_devices--;
7119 fs_devices->missing_devices++;
7121 device->fs_devices = fs_devices;
7125 if (device->fs_devices != fs_info->fs_devices) {
7126 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7127 if (device->generation !=
7128 btrfs_device_generation(leaf, dev_item))
7132 fill_device_from_item(leaf, dev_item, device);
7134 u64 max_total_bytes = i_size_read(device->bdev->bd_inode);
7136 if (device->total_bytes > max_total_bytes) {
7138 "device total_bytes should be at most %llu but found %llu",
7139 max_total_bytes, device->total_bytes);
7143 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7144 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7145 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7146 device->fs_devices->total_rw_bytes += device->total_bytes;
7147 atomic64_add(device->total_bytes - device->bytes_used,
7148 &fs_info->free_chunk_space);
7154 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7156 struct btrfs_root *root = fs_info->tree_root;
7157 struct btrfs_super_block *super_copy = fs_info->super_copy;
7158 struct extent_buffer *sb;
7159 struct btrfs_disk_key *disk_key;
7160 struct btrfs_chunk *chunk;
7162 unsigned long sb_array_offset;
7169 struct btrfs_key key;
7171 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7173 * This will create extent buffer of nodesize, superblock size is
7174 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7175 * overallocate but we can keep it as-is, only the first page is used.
7177 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET,
7178 root->root_key.objectid, 0);
7181 set_extent_buffer_uptodate(sb);
7183 * The sb extent buffer is artificial and just used to read the system array.
7184 * set_extent_buffer_uptodate() call does not properly mark all it's
7185 * pages up-to-date when the page is larger: extent does not cover the
7186 * whole page and consequently check_page_uptodate does not find all
7187 * the page's extents up-to-date (the hole beyond sb),
7188 * write_extent_buffer then triggers a WARN_ON.
7190 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7191 * but sb spans only this function. Add an explicit SetPageUptodate call
7192 * to silence the warning eg. on PowerPC 64.
7194 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
7195 SetPageUptodate(sb->pages[0]);
7197 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7198 array_size = btrfs_super_sys_array_size(super_copy);
7200 array_ptr = super_copy->sys_chunk_array;
7201 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7204 while (cur_offset < array_size) {
7205 disk_key = (struct btrfs_disk_key *)array_ptr;
7206 len = sizeof(*disk_key);
7207 if (cur_offset + len > array_size)
7208 goto out_short_read;
7210 btrfs_disk_key_to_cpu(&key, disk_key);
7213 sb_array_offset += len;
7216 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
7218 "unexpected item type %u in sys_array at offset %u",
7219 (u32)key.type, cur_offset);
7224 chunk = (struct btrfs_chunk *)sb_array_offset;
7226 * At least one btrfs_chunk with one stripe must be present,
7227 * exact stripe count check comes afterwards
7229 len = btrfs_chunk_item_size(1);
7230 if (cur_offset + len > array_size)
7231 goto out_short_read;
7233 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7236 "invalid number of stripes %u in sys_array at offset %u",
7237 num_stripes, cur_offset);
7242 type = btrfs_chunk_type(sb, chunk);
7243 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7245 "invalid chunk type %llu in sys_array at offset %u",
7251 len = btrfs_chunk_item_size(num_stripes);
7252 if (cur_offset + len > array_size)
7253 goto out_short_read;
7255 ret = read_one_chunk(&key, sb, chunk);
7260 sb_array_offset += len;
7263 clear_extent_buffer_uptodate(sb);
7264 free_extent_buffer_stale(sb);
7268 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7270 clear_extent_buffer_uptodate(sb);
7271 free_extent_buffer_stale(sb);
7276 * Check if all chunks in the fs are OK for read-write degraded mount
7278 * If the @failing_dev is specified, it's accounted as missing.
7280 * Return true if all chunks meet the minimal RW mount requirements.
7281 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7283 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7284 struct btrfs_device *failing_dev)
7286 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7287 struct extent_map *em;
7291 read_lock(&map_tree->lock);
7292 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7293 read_unlock(&map_tree->lock);
7294 /* No chunk at all? Return false anyway */
7300 struct map_lookup *map;
7305 map = em->map_lookup;
7307 btrfs_get_num_tolerated_disk_barrier_failures(
7309 for (i = 0; i < map->num_stripes; i++) {
7310 struct btrfs_device *dev = map->stripes[i].dev;
7312 if (!dev || !dev->bdev ||
7313 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7314 dev->last_flush_error)
7316 else if (failing_dev && failing_dev == dev)
7319 if (missing > max_tolerated) {
7322 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7323 em->start, missing, max_tolerated);
7324 free_extent_map(em);
7328 next_start = extent_map_end(em);
7329 free_extent_map(em);
7331 read_lock(&map_tree->lock);
7332 em = lookup_extent_mapping(map_tree, next_start,
7333 (u64)(-1) - next_start);
7334 read_unlock(&map_tree->lock);
7340 static void readahead_tree_node_children(struct extent_buffer *node)
7343 const int nr_items = btrfs_header_nritems(node);
7345 for (i = 0; i < nr_items; i++)
7346 btrfs_readahead_node_child(node, i);
7349 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7351 struct btrfs_root *root = fs_info->chunk_root;
7352 struct btrfs_path *path;
7353 struct extent_buffer *leaf;
7354 struct btrfs_key key;
7355 struct btrfs_key found_key;
7359 u64 last_ra_node = 0;
7361 path = btrfs_alloc_path();
7366 * uuid_mutex is needed only if we are mounting a sprout FS
7367 * otherwise we don't need it.
7369 mutex_lock(&uuid_mutex);
7372 * It is possible for mount and umount to race in such a way that
7373 * we execute this code path, but open_fs_devices failed to clear
7374 * total_rw_bytes. We certainly want it cleared before reading the
7375 * device items, so clear it here.
7377 fs_info->fs_devices->total_rw_bytes = 0;
7380 * Read all device items, and then all the chunk items. All
7381 * device items are found before any chunk item (their object id
7382 * is smaller than the lowest possible object id for a chunk
7383 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7385 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7388 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7392 struct extent_buffer *node;
7394 leaf = path->nodes[0];
7395 slot = path->slots[0];
7396 if (slot >= btrfs_header_nritems(leaf)) {
7397 ret = btrfs_next_leaf(root, path);
7405 * The nodes on level 1 are not locked but we don't need to do
7406 * that during mount time as nothing else can access the tree
7408 node = path->nodes[1];
7410 if (last_ra_node != node->start) {
7411 readahead_tree_node_children(node);
7412 last_ra_node = node->start;
7415 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7416 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7417 struct btrfs_dev_item *dev_item;
7418 dev_item = btrfs_item_ptr(leaf, slot,
7419 struct btrfs_dev_item);
7420 ret = read_one_dev(leaf, dev_item);
7424 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7425 struct btrfs_chunk *chunk;
7426 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7427 mutex_lock(&fs_info->chunk_mutex);
7428 ret = read_one_chunk(&found_key, leaf, chunk);
7429 mutex_unlock(&fs_info->chunk_mutex);
7437 * After loading chunk tree, we've got all device information,
7438 * do another round of validation checks.
7440 if (total_dev != fs_info->fs_devices->total_devices) {
7442 "super_num_devices %llu mismatch with num_devices %llu found here",
7443 btrfs_super_num_devices(fs_info->super_copy),
7448 if (btrfs_super_total_bytes(fs_info->super_copy) <
7449 fs_info->fs_devices->total_rw_bytes) {
7451 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7452 btrfs_super_total_bytes(fs_info->super_copy),
7453 fs_info->fs_devices->total_rw_bytes);
7459 mutex_unlock(&uuid_mutex);
7461 btrfs_free_path(path);
7465 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7467 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7468 struct btrfs_device *device;
7470 fs_devices->fs_info = fs_info;
7472 mutex_lock(&fs_devices->device_list_mutex);
7473 list_for_each_entry(device, &fs_devices->devices, dev_list)
7474 device->fs_info = fs_info;
7476 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7477 list_for_each_entry(device, &seed_devs->devices, dev_list)
7478 device->fs_info = fs_info;
7480 seed_devs->fs_info = fs_info;
7482 mutex_unlock(&fs_devices->device_list_mutex);
7485 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7486 const struct btrfs_dev_stats_item *ptr,
7491 read_extent_buffer(eb, &val,
7492 offsetof(struct btrfs_dev_stats_item, values) +
7493 ((unsigned long)ptr) + (index * sizeof(u64)),
7498 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7499 struct btrfs_dev_stats_item *ptr,
7502 write_extent_buffer(eb, &val,
7503 offsetof(struct btrfs_dev_stats_item, values) +
7504 ((unsigned long)ptr) + (index * sizeof(u64)),
7508 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7509 struct btrfs_path *path)
7511 struct btrfs_dev_stats_item *ptr;
7512 struct extent_buffer *eb;
7513 struct btrfs_key key;
7517 if (!device->fs_info->dev_root)
7520 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7521 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7522 key.offset = device->devid;
7523 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7525 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7526 btrfs_dev_stat_set(device, i, 0);
7527 device->dev_stats_valid = 1;
7528 btrfs_release_path(path);
7529 return ret < 0 ? ret : 0;
7531 slot = path->slots[0];
7532 eb = path->nodes[0];
7533 item_size = btrfs_item_size_nr(eb, slot);
7535 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7537 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7538 if (item_size >= (1 + i) * sizeof(__le64))
7539 btrfs_dev_stat_set(device, i,
7540 btrfs_dev_stats_value(eb, ptr, i));
7542 btrfs_dev_stat_set(device, i, 0);
7545 device->dev_stats_valid = 1;
7546 btrfs_dev_stat_print_on_load(device);
7547 btrfs_release_path(path);
7552 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7554 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7555 struct btrfs_device *device;
7556 struct btrfs_path *path = NULL;
7559 path = btrfs_alloc_path();
7563 mutex_lock(&fs_devices->device_list_mutex);
7564 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7565 ret = btrfs_device_init_dev_stats(device, path);
7569 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7570 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7571 ret = btrfs_device_init_dev_stats(device, path);
7577 mutex_unlock(&fs_devices->device_list_mutex);
7579 btrfs_free_path(path);
7583 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7584 struct btrfs_device *device)
7586 struct btrfs_fs_info *fs_info = trans->fs_info;
7587 struct btrfs_root *dev_root = fs_info->dev_root;
7588 struct btrfs_path *path;
7589 struct btrfs_key key;
7590 struct extent_buffer *eb;
7591 struct btrfs_dev_stats_item *ptr;
7595 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7596 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7597 key.offset = device->devid;
7599 path = btrfs_alloc_path();
7602 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7604 btrfs_warn_in_rcu(fs_info,
7605 "error %d while searching for dev_stats item for device %s",
7606 ret, rcu_str_deref(device->name));
7611 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7612 /* need to delete old one and insert a new one */
7613 ret = btrfs_del_item(trans, dev_root, path);
7615 btrfs_warn_in_rcu(fs_info,
7616 "delete too small dev_stats item for device %s failed %d",
7617 rcu_str_deref(device->name), ret);
7624 /* need to insert a new item */
7625 btrfs_release_path(path);
7626 ret = btrfs_insert_empty_item(trans, dev_root, path,
7627 &key, sizeof(*ptr));
7629 btrfs_warn_in_rcu(fs_info,
7630 "insert dev_stats item for device %s failed %d",
7631 rcu_str_deref(device->name), ret);
7636 eb = path->nodes[0];
7637 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7638 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7639 btrfs_set_dev_stats_value(eb, ptr, i,
7640 btrfs_dev_stat_read(device, i));
7641 btrfs_mark_buffer_dirty(eb);
7644 btrfs_free_path(path);
7649 * called from commit_transaction. Writes all changed device stats to disk.
7651 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7653 struct btrfs_fs_info *fs_info = trans->fs_info;
7654 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7655 struct btrfs_device *device;
7659 mutex_lock(&fs_devices->device_list_mutex);
7660 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7661 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7662 if (!device->dev_stats_valid || stats_cnt == 0)
7667 * There is a LOAD-LOAD control dependency between the value of
7668 * dev_stats_ccnt and updating the on-disk values which requires
7669 * reading the in-memory counters. Such control dependencies
7670 * require explicit read memory barriers.
7672 * This memory barriers pairs with smp_mb__before_atomic in
7673 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7674 * barrier implied by atomic_xchg in
7675 * btrfs_dev_stats_read_and_reset
7679 ret = update_dev_stat_item(trans, device);
7681 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7683 mutex_unlock(&fs_devices->device_list_mutex);
7688 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7690 btrfs_dev_stat_inc(dev, index);
7691 btrfs_dev_stat_print_on_error(dev);
7694 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7696 if (!dev->dev_stats_valid)
7698 btrfs_err_rl_in_rcu(dev->fs_info,
7699 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7700 rcu_str_deref(dev->name),
7701 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7702 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7703 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7704 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7705 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7708 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7712 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7713 if (btrfs_dev_stat_read(dev, i) != 0)
7715 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7716 return; /* all values == 0, suppress message */
7718 btrfs_info_in_rcu(dev->fs_info,
7719 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7720 rcu_str_deref(dev->name),
7721 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7722 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7723 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7724 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7725 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7728 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7729 struct btrfs_ioctl_get_dev_stats *stats)
7731 struct btrfs_device *dev;
7732 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7735 mutex_lock(&fs_devices->device_list_mutex);
7736 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL);
7737 mutex_unlock(&fs_devices->device_list_mutex);
7740 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7742 } else if (!dev->dev_stats_valid) {
7743 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7745 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7746 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7747 if (stats->nr_items > i)
7749 btrfs_dev_stat_read_and_reset(dev, i);
7751 btrfs_dev_stat_set(dev, i, 0);
7753 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7754 current->comm, task_pid_nr(current));
7756 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7757 if (stats->nr_items > i)
7758 stats->values[i] = btrfs_dev_stat_read(dev, i);
7760 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7761 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7766 * Update the size and bytes used for each device where it changed. This is
7767 * delayed since we would otherwise get errors while writing out the
7770 * Must be invoked during transaction commit.
7772 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7774 struct btrfs_device *curr, *next;
7776 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7778 if (list_empty(&trans->dev_update_list))
7782 * We don't need the device_list_mutex here. This list is owned by the
7783 * transaction and the transaction must complete before the device is
7786 mutex_lock(&trans->fs_info->chunk_mutex);
7787 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7789 list_del_init(&curr->post_commit_list);
7790 curr->commit_total_bytes = curr->disk_total_bytes;
7791 curr->commit_bytes_used = curr->bytes_used;
7793 mutex_unlock(&trans->fs_info->chunk_mutex);
7797 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7799 int btrfs_bg_type_to_factor(u64 flags)
7801 const int index = btrfs_bg_flags_to_raid_index(flags);
7803 return btrfs_raid_array[index].ncopies;
7808 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7809 u64 chunk_offset, u64 devid,
7810 u64 physical_offset, u64 physical_len)
7812 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7813 struct extent_map *em;
7814 struct map_lookup *map;
7815 struct btrfs_device *dev;
7821 read_lock(&em_tree->lock);
7822 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7823 read_unlock(&em_tree->lock);
7827 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7828 physical_offset, devid);
7833 map = em->map_lookup;
7834 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7835 if (physical_len != stripe_len) {
7837 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7838 physical_offset, devid, em->start, physical_len,
7844 for (i = 0; i < map->num_stripes; i++) {
7845 if (map->stripes[i].dev->devid == devid &&
7846 map->stripes[i].physical == physical_offset) {
7848 if (map->verified_stripes >= map->num_stripes) {
7850 "too many dev extents for chunk %llu found",
7855 map->verified_stripes++;
7861 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7862 physical_offset, devid);
7866 /* Make sure no dev extent is beyond device bondary */
7867 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL);
7869 btrfs_err(fs_info, "failed to find devid %llu", devid);
7874 if (physical_offset + physical_len > dev->disk_total_bytes) {
7876 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7877 devid, physical_offset, physical_len,
7878 dev->disk_total_bytes);
7883 if (dev->zone_info) {
7884 u64 zone_size = dev->zone_info->zone_size;
7886 if (!IS_ALIGNED(physical_offset, zone_size) ||
7887 !IS_ALIGNED(physical_len, zone_size)) {
7889 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
7890 devid, physical_offset, physical_len);
7897 free_extent_map(em);
7901 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7903 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7904 struct extent_map *em;
7905 struct rb_node *node;
7908 read_lock(&em_tree->lock);
7909 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7910 em = rb_entry(node, struct extent_map, rb_node);
7911 if (em->map_lookup->num_stripes !=
7912 em->map_lookup->verified_stripes) {
7914 "chunk %llu has missing dev extent, have %d expect %d",
7915 em->start, em->map_lookup->verified_stripes,
7916 em->map_lookup->num_stripes);
7922 read_unlock(&em_tree->lock);
7927 * Ensure that all dev extents are mapped to correct chunk, otherwise
7928 * later chunk allocation/free would cause unexpected behavior.
7930 * NOTE: This will iterate through the whole device tree, which should be of
7931 * the same size level as the chunk tree. This slightly increases mount time.
7933 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7935 struct btrfs_path *path;
7936 struct btrfs_root *root = fs_info->dev_root;
7937 struct btrfs_key key;
7939 u64 prev_dev_ext_end = 0;
7943 * We don't have a dev_root because we mounted with ignorebadroots and
7944 * failed to load the root, so we want to skip the verification in this
7947 * However if the dev root is fine, but the tree itself is corrupted
7948 * we'd still fail to mount. This verification is only to make sure
7949 * writes can happen safely, so instead just bypass this check
7950 * completely in the case of IGNOREBADROOTS.
7952 if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
7956 key.type = BTRFS_DEV_EXTENT_KEY;
7959 path = btrfs_alloc_path();
7963 path->reada = READA_FORWARD;
7964 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7968 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7969 ret = btrfs_next_item(root, path);
7972 /* No dev extents at all? Not good */
7979 struct extent_buffer *leaf = path->nodes[0];
7980 struct btrfs_dev_extent *dext;
7981 int slot = path->slots[0];
7983 u64 physical_offset;
7987 btrfs_item_key_to_cpu(leaf, &key, slot);
7988 if (key.type != BTRFS_DEV_EXTENT_KEY)
7990 devid = key.objectid;
7991 physical_offset = key.offset;
7993 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7994 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7995 physical_len = btrfs_dev_extent_length(leaf, dext);
7997 /* Check if this dev extent overlaps with the previous one */
7998 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
8000 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8001 devid, physical_offset, prev_dev_ext_end);
8006 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8007 physical_offset, physical_len);
8011 prev_dev_ext_end = physical_offset + physical_len;
8013 ret = btrfs_next_item(root, path);
8022 /* Ensure all chunks have corresponding dev extents */
8023 ret = verify_chunk_dev_extent_mapping(fs_info);
8025 btrfs_free_path(path);
8030 * Check whether the given block group or device is pinned by any inode being
8031 * used as a swapfile.
8033 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8035 struct btrfs_swapfile_pin *sp;
8036 struct rb_node *node;
8038 spin_lock(&fs_info->swapfile_pins_lock);
8039 node = fs_info->swapfile_pins.rb_node;
8041 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8043 node = node->rb_left;
8044 else if (ptr > sp->ptr)
8045 node = node->rb_right;
8049 spin_unlock(&fs_info->swapfile_pins_lock);
8050 return node != NULL;
8053 static int relocating_repair_kthread(void *data)
8055 struct btrfs_block_group *cache = (struct btrfs_block_group *)data;
8056 struct btrfs_fs_info *fs_info = cache->fs_info;
8060 target = cache->start;
8061 btrfs_put_block_group(cache);
8063 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8065 "zoned: skip relocating block group %llu to repair: EBUSY",
8070 mutex_lock(&fs_info->reclaim_bgs_lock);
8072 /* Ensure block group still exists */
8073 cache = btrfs_lookup_block_group(fs_info, target);
8077 if (!cache->relocating_repair)
8080 ret = btrfs_may_alloc_data_chunk(fs_info, target);
8085 "zoned: relocating block group %llu to repair IO failure",
8087 ret = btrfs_relocate_chunk(fs_info, target);
8091 btrfs_put_block_group(cache);
8092 mutex_unlock(&fs_info->reclaim_bgs_lock);
8093 btrfs_exclop_finish(fs_info);
8098 int btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8100 struct btrfs_block_group *cache;
8102 /* Do not attempt to repair in degraded state */
8103 if (btrfs_test_opt(fs_info, DEGRADED))
8106 cache = btrfs_lookup_block_group(fs_info, logical);
8110 spin_lock(&cache->lock);
8111 if (cache->relocating_repair) {
8112 spin_unlock(&cache->lock);
8113 btrfs_put_block_group(cache);
8116 cache->relocating_repair = 1;
8117 spin_unlock(&cache->lock);
8119 kthread_run(relocating_repair_kthread, cache,
8120 "btrfs-relocating-repair");