1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/mm.h>
8 #include <linux/slab.h>
9 #include <linux/ratelimit.h>
10 #include <linux/kthread.h>
11 #include <linux/semaphore.h>
12 #include <linux/uuid.h>
13 #include <linux/list_sort.h>
14 #include <linux/namei.h>
18 #include "transaction.h"
21 #include "rcu-string.h"
22 #include "dev-replace.h"
24 #include "tree-checker.h"
25 #include "space-info.h"
26 #include "block-group.h"
30 #include "accessors.h"
31 #include "uuid-tree.h"
33 #include "relocation.h"
36 #include "raid-stripe-tree.h"
38 #define BTRFS_BLOCK_GROUP_STRIPE_MASK (BTRFS_BLOCK_GROUP_RAID0 | \
39 BTRFS_BLOCK_GROUP_RAID10 | \
40 BTRFS_BLOCK_GROUP_RAID56_MASK)
42 struct btrfs_io_geometry
{
48 u64 raid56_full_stripe_start
;
53 const struct btrfs_raid_attr btrfs_raid_array
[BTRFS_NR_RAID_TYPES
] = {
54 [BTRFS_RAID_RAID10
] = {
57 .devs_max
= 0, /* 0 == as many as possible */
59 .tolerated_failures
= 1,
63 .raid_name
= "raid10",
64 .bg_flag
= BTRFS_BLOCK_GROUP_RAID10
,
65 .mindev_error
= BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET
,
67 [BTRFS_RAID_RAID1
] = {
72 .tolerated_failures
= 1,
77 .bg_flag
= BTRFS_BLOCK_GROUP_RAID1
,
78 .mindev_error
= BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET
,
80 [BTRFS_RAID_RAID1C3
] = {
85 .tolerated_failures
= 2,
89 .raid_name
= "raid1c3",
90 .bg_flag
= BTRFS_BLOCK_GROUP_RAID1C3
,
91 .mindev_error
= BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET
,
93 [BTRFS_RAID_RAID1C4
] = {
98 .tolerated_failures
= 3,
102 .raid_name
= "raid1c4",
103 .bg_flag
= BTRFS_BLOCK_GROUP_RAID1C4
,
104 .mindev_error
= BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET
,
111 .tolerated_failures
= 0,
116 .bg_flag
= BTRFS_BLOCK_GROUP_DUP
,
119 [BTRFS_RAID_RAID0
] = {
124 .tolerated_failures
= 0,
128 .raid_name
= "raid0",
129 .bg_flag
= BTRFS_BLOCK_GROUP_RAID0
,
132 [BTRFS_RAID_SINGLE
] = {
137 .tolerated_failures
= 0,
141 .raid_name
= "single",
145 [BTRFS_RAID_RAID5
] = {
150 .tolerated_failures
= 1,
154 .raid_name
= "raid5",
155 .bg_flag
= BTRFS_BLOCK_GROUP_RAID5
,
156 .mindev_error
= BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET
,
158 [BTRFS_RAID_RAID6
] = {
163 .tolerated_failures
= 2,
167 .raid_name
= "raid6",
168 .bg_flag
= BTRFS_BLOCK_GROUP_RAID6
,
169 .mindev_error
= BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET
,
174 * Convert block group flags (BTRFS_BLOCK_GROUP_*) to btrfs_raid_types, which
175 * can be used as index to access btrfs_raid_array[].
177 enum btrfs_raid_types __attribute_const__
btrfs_bg_flags_to_raid_index(u64 flags
)
179 const u64 profile
= (flags
& BTRFS_BLOCK_GROUP_PROFILE_MASK
);
182 return BTRFS_RAID_SINGLE
;
184 return BTRFS_BG_FLAG_TO_INDEX(profile
);
187 const char *btrfs_bg_type_to_raid_name(u64 flags
)
189 const int index
= btrfs_bg_flags_to_raid_index(flags
);
191 if (index
>= BTRFS_NR_RAID_TYPES
)
194 return btrfs_raid_array
[index
].raid_name
;
197 int btrfs_nr_parity_stripes(u64 type
)
199 enum btrfs_raid_types index
= btrfs_bg_flags_to_raid_index(type
);
201 return btrfs_raid_array
[index
].nparity
;
205 * Fill @buf with textual description of @bg_flags, no more than @size_buf
206 * bytes including terminating null byte.
208 void btrfs_describe_block_groups(u64 bg_flags
, char *buf
, u32 size_buf
)
213 u64 flags
= bg_flags
;
214 u32 size_bp
= size_buf
;
221 #define DESCRIBE_FLAG(flag, desc) \
223 if (flags & (flag)) { \
224 ret = snprintf(bp, size_bp, "%s|", (desc)); \
225 if (ret < 0 || ret >= size_bp) \
233 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA
, "data");
234 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM
, "system");
235 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA
, "metadata");
237 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE
, "single");
238 for (i
= 0; i
< BTRFS_NR_RAID_TYPES
; i
++)
239 DESCRIBE_FLAG(btrfs_raid_array
[i
].bg_flag
,
240 btrfs_raid_array
[i
].raid_name
);
244 ret
= snprintf(bp
, size_bp
, "0x%llx|", flags
);
248 if (size_bp
< size_buf
)
249 buf
[size_buf
- size_bp
- 1] = '\0'; /* remove last | */
252 * The text is trimmed, it's up to the caller to provide sufficiently
258 static int init_first_rw_device(struct btrfs_trans_handle
*trans
);
259 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info
*fs_info
);
260 static void btrfs_dev_stat_print_on_load(struct btrfs_device
*device
);
266 * There are several mutexes that protect manipulation of devices and low-level
267 * structures like chunks but not block groups, extents or files
269 * uuid_mutex (global lock)
270 * ------------------------
271 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
272 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
273 * device) or requested by the device= mount option
275 * the mutex can be very coarse and can cover long-running operations
277 * protects: updates to fs_devices counters like missing devices, rw devices,
278 * seeding, structure cloning, opening/closing devices at mount/umount time
280 * global::fs_devs - add, remove, updates to the global list
282 * does not protect: manipulation of the fs_devices::devices list in general
283 * but in mount context it could be used to exclude list modifications by eg.
286 * btrfs_device::name - renames (write side), read is RCU
288 * fs_devices::device_list_mutex (per-fs, with RCU)
289 * ------------------------------------------------
290 * protects updates to fs_devices::devices, ie. adding and deleting
292 * simple list traversal with read-only actions can be done with RCU protection
294 * may be used to exclude some operations from running concurrently without any
295 * modifications to the list (see write_all_supers)
297 * Is not required at mount and close times, because our device list is
298 * protected by the uuid_mutex at that point.
302 * protects balance structures (status, state) and context accessed from
303 * several places (internally, ioctl)
307 * protects chunks, adding or removing during allocation, trim or when a new
308 * device is added/removed. Additionally it also protects post_commit_list of
309 * individual devices, since they can be added to the transaction's
310 * post_commit_list only with chunk_mutex held.
314 * a big lock that is held by the cleaner thread and prevents running subvolume
315 * cleaning together with relocation or delayed iputs
327 * Exclusive operations
328 * ====================
330 * Maintains the exclusivity of the following operations that apply to the
331 * whole filesystem and cannot run in parallel.
336 * - Device replace (*)
339 * The device operations (as above) can be in one of the following states:
345 * Only device operations marked with (*) can go into the Paused state for the
348 * - ioctl (only Balance can be Paused through ioctl)
349 * - filesystem remounted as read-only
350 * - filesystem unmounted and mounted as read-only
351 * - system power-cycle and filesystem mounted as read-only
352 * - filesystem or device errors leading to forced read-only
354 * The status of exclusive operation is set and cleared atomically.
355 * During the course of Paused state, fs_info::exclusive_operation remains set.
356 * A device operation in Paused or Running state can be canceled or resumed
357 * either by ioctl (Balance only) or when remounted as read-write.
358 * The exclusive status is cleared when the device operation is canceled or
362 DEFINE_MUTEX(uuid_mutex
);
363 static LIST_HEAD(fs_uuids
);
364 struct list_head
* __attribute_const__
btrfs_get_fs_uuids(void)
370 * Allocate new btrfs_fs_devices structure identified by a fsid.
372 * @fsid: if not NULL, copy the UUID to fs_devices::fsid and to
373 * fs_devices::metadata_fsid
375 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
376 * The returned struct is not linked onto any lists and can be destroyed with
377 * kfree() right away.
379 static struct btrfs_fs_devices
*alloc_fs_devices(const u8
*fsid
)
381 struct btrfs_fs_devices
*fs_devs
;
383 fs_devs
= kzalloc(sizeof(*fs_devs
), GFP_KERNEL
);
385 return ERR_PTR(-ENOMEM
);
387 mutex_init(&fs_devs
->device_list_mutex
);
389 INIT_LIST_HEAD(&fs_devs
->devices
);
390 INIT_LIST_HEAD(&fs_devs
->alloc_list
);
391 INIT_LIST_HEAD(&fs_devs
->fs_list
);
392 INIT_LIST_HEAD(&fs_devs
->seed_list
);
395 memcpy(fs_devs
->fsid
, fsid
, BTRFS_FSID_SIZE
);
396 memcpy(fs_devs
->metadata_uuid
, fsid
, BTRFS_FSID_SIZE
);
402 static void btrfs_free_device(struct btrfs_device
*device
)
404 WARN_ON(!list_empty(&device
->post_commit_list
));
405 rcu_string_free(device
->name
);
406 extent_io_tree_release(&device
->alloc_state
);
407 btrfs_destroy_dev_zone_info(device
);
411 static void free_fs_devices(struct btrfs_fs_devices
*fs_devices
)
413 struct btrfs_device
*device
;
415 WARN_ON(fs_devices
->opened
);
416 while (!list_empty(&fs_devices
->devices
)) {
417 device
= list_entry(fs_devices
->devices
.next
,
418 struct btrfs_device
, dev_list
);
419 list_del(&device
->dev_list
);
420 btrfs_free_device(device
);
425 void __exit
btrfs_cleanup_fs_uuids(void)
427 struct btrfs_fs_devices
*fs_devices
;
429 while (!list_empty(&fs_uuids
)) {
430 fs_devices
= list_entry(fs_uuids
.next
,
431 struct btrfs_fs_devices
, fs_list
);
432 list_del(&fs_devices
->fs_list
);
433 free_fs_devices(fs_devices
);
437 static bool match_fsid_fs_devices(const struct btrfs_fs_devices
*fs_devices
,
438 const u8
*fsid
, const u8
*metadata_fsid
)
440 if (memcmp(fsid
, fs_devices
->fsid
, BTRFS_FSID_SIZE
) != 0)
446 if (memcmp(metadata_fsid
, fs_devices
->metadata_uuid
, BTRFS_FSID_SIZE
) != 0)
452 static noinline
struct btrfs_fs_devices
*find_fsid(
453 const u8
*fsid
, const u8
*metadata_fsid
)
455 struct btrfs_fs_devices
*fs_devices
;
459 /* Handle non-split brain cases */
460 list_for_each_entry(fs_devices
, &fs_uuids
, fs_list
) {
461 if (match_fsid_fs_devices(fs_devices
, fsid
, metadata_fsid
))
468 btrfs_get_bdev_and_sb(const char *device_path
, blk_mode_t flags
, void *holder
,
469 int flush
, struct file
**bdev_file
,
470 struct btrfs_super_block
**disk_super
)
472 struct block_device
*bdev
;
475 *bdev_file
= bdev_file_open_by_path(device_path
, flags
, holder
, NULL
);
477 if (IS_ERR(*bdev_file
)) {
478 ret
= PTR_ERR(*bdev_file
);
481 bdev
= file_bdev(*bdev_file
);
485 ret
= set_blocksize(bdev
, BTRFS_BDEV_BLOCKSIZE
);
490 invalidate_bdev(bdev
);
491 *disk_super
= btrfs_read_dev_super(bdev
);
492 if (IS_ERR(*disk_super
)) {
493 ret
= PTR_ERR(*disk_super
);
506 * Search and remove all stale devices (which are not mounted). When both
507 * inputs are NULL, it will search and release all stale devices.
509 * @devt: Optional. When provided will it release all unmounted devices
510 * matching this devt only.
511 * @skip_device: Optional. Will skip this device when searching for the stale
514 * Return: 0 for success or if @devt is 0.
515 * -EBUSY if @devt is a mounted device.
516 * -ENOENT if @devt does not match any device in the list.
518 static int btrfs_free_stale_devices(dev_t devt
, struct btrfs_device
*skip_device
)
520 struct btrfs_fs_devices
*fs_devices
, *tmp_fs_devices
;
521 struct btrfs_device
*device
, *tmp_device
;
525 lockdep_assert_held(&uuid_mutex
);
527 /* Return good status if there is no instance of devt. */
529 list_for_each_entry_safe(fs_devices
, tmp_fs_devices
, &fs_uuids
, fs_list
) {
531 mutex_lock(&fs_devices
->device_list_mutex
);
532 list_for_each_entry_safe(device
, tmp_device
,
533 &fs_devices
->devices
, dev_list
) {
534 if (skip_device
&& skip_device
== device
)
536 if (devt
&& devt
!= device
->devt
)
538 if (fs_devices
->opened
) {
544 /* delete the stale device */
545 fs_devices
->num_devices
--;
546 list_del(&device
->dev_list
);
547 btrfs_free_device(device
);
551 mutex_unlock(&fs_devices
->device_list_mutex
);
553 if (fs_devices
->num_devices
== 0) {
554 btrfs_sysfs_remove_fsid(fs_devices
);
555 list_del(&fs_devices
->fs_list
);
556 free_fs_devices(fs_devices
);
560 /* If there is at least one freed device return 0. */
567 static struct btrfs_fs_devices
*find_fsid_by_device(
568 struct btrfs_super_block
*disk_super
,
569 dev_t devt
, bool *same_fsid_diff_dev
)
571 struct btrfs_fs_devices
*fsid_fs_devices
;
572 struct btrfs_fs_devices
*devt_fs_devices
;
573 const bool has_metadata_uuid
= (btrfs_super_incompat_flags(disk_super
) &
574 BTRFS_FEATURE_INCOMPAT_METADATA_UUID
);
575 bool found_by_devt
= false;
577 /* Find the fs_device by the usual method, if found use it. */
578 fsid_fs_devices
= find_fsid(disk_super
->fsid
,
579 has_metadata_uuid
? disk_super
->metadata_uuid
: NULL
);
581 /* The temp_fsid feature is supported only with single device filesystem. */
582 if (btrfs_super_num_devices(disk_super
) != 1)
583 return fsid_fs_devices
;
586 * A seed device is an integral component of the sprout device, which
587 * functions as a multi-device filesystem. So, temp-fsid feature is
590 if (btrfs_super_flags(disk_super
) & BTRFS_SUPER_FLAG_SEEDING
)
591 return fsid_fs_devices
;
593 /* Try to find a fs_devices by matching devt. */
594 list_for_each_entry(devt_fs_devices
, &fs_uuids
, fs_list
) {
595 struct btrfs_device
*device
;
597 list_for_each_entry(device
, &devt_fs_devices
->devices
, dev_list
) {
598 if (device
->devt
== devt
) {
599 found_by_devt
= true;
608 /* Existing device. */
609 if (fsid_fs_devices
== NULL
) {
610 if (devt_fs_devices
->opened
== 0) {
614 /* temp_fsid is mounting a subvol. */
615 return devt_fs_devices
;
618 /* Regular or temp_fsid device mounting a subvol. */
619 return devt_fs_devices
;
623 if (fsid_fs_devices
== NULL
) {
626 /* sb::fsid is already used create a new temp_fsid. */
627 *same_fsid_diff_dev
= true;
636 * This is only used on mount, and we are protected from competing things
637 * messing with our fs_devices by the uuid_mutex, thus we do not need the
638 * fs_devices->device_list_mutex here.
640 static int btrfs_open_one_device(struct btrfs_fs_devices
*fs_devices
,
641 struct btrfs_device
*device
, blk_mode_t flags
,
644 struct file
*bdev_file
;
645 struct btrfs_super_block
*disk_super
;
654 ret
= btrfs_get_bdev_and_sb(device
->name
->str
, flags
, holder
, 1,
655 &bdev_file
, &disk_super
);
659 devid
= btrfs_stack_device_id(&disk_super
->dev_item
);
660 if (devid
!= device
->devid
)
661 goto error_free_page
;
663 if (memcmp(device
->uuid
, disk_super
->dev_item
.uuid
, BTRFS_UUID_SIZE
))
664 goto error_free_page
;
666 device
->generation
= btrfs_super_generation(disk_super
);
668 if (btrfs_super_flags(disk_super
) & BTRFS_SUPER_FLAG_SEEDING
) {
669 if (btrfs_super_incompat_flags(disk_super
) &
670 BTRFS_FEATURE_INCOMPAT_METADATA_UUID
) {
672 "BTRFS: Invalid seeding and uuid-changed device detected\n");
673 goto error_free_page
;
676 clear_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
677 fs_devices
->seeding
= true;
679 if (bdev_read_only(file_bdev(bdev_file
)))
680 clear_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
682 set_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
685 if (!bdev_nonrot(file_bdev(bdev_file
)))
686 fs_devices
->rotating
= true;
688 if (bdev_max_discard_sectors(file_bdev(bdev_file
)))
689 fs_devices
->discardable
= true;
691 device
->bdev_file
= bdev_file
;
692 device
->bdev
= file_bdev(bdev_file
);
693 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
);
695 fs_devices
->open_devices
++;
696 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
) &&
697 device
->devid
!= BTRFS_DEV_REPLACE_DEVID
) {
698 fs_devices
->rw_devices
++;
699 list_add_tail(&device
->dev_alloc_list
, &fs_devices
->alloc_list
);
701 btrfs_release_disk_super(disk_super
);
706 btrfs_release_disk_super(disk_super
);
712 u8
*btrfs_sb_fsid_ptr(struct btrfs_super_block
*sb
)
714 bool has_metadata_uuid
= (btrfs_super_incompat_flags(sb
) &
715 BTRFS_FEATURE_INCOMPAT_METADATA_UUID
);
717 return has_metadata_uuid
? sb
->metadata_uuid
: sb
->fsid
;
721 * Add new device to list of registered devices
724 * device pointer which was just added or updated when successful
725 * error pointer when failed
727 static noinline
struct btrfs_device
*device_list_add(const char *path
,
728 struct btrfs_super_block
*disk_super
,
729 bool *new_device_added
)
731 struct btrfs_device
*device
;
732 struct btrfs_fs_devices
*fs_devices
= NULL
;
733 struct rcu_string
*name
;
734 u64 found_transid
= btrfs_super_generation(disk_super
);
735 u64 devid
= btrfs_stack_device_id(&disk_super
->dev_item
);
738 bool same_fsid_diff_dev
= false;
739 bool has_metadata_uuid
= (btrfs_super_incompat_flags(disk_super
) &
740 BTRFS_FEATURE_INCOMPAT_METADATA_UUID
);
742 if (btrfs_super_flags(disk_super
) & BTRFS_SUPER_FLAG_CHANGING_FSID_V2
) {
744 "device %s has incomplete metadata_uuid change, please use btrfstune to complete",
746 return ERR_PTR(-EAGAIN
);
749 error
= lookup_bdev(path
, &path_devt
);
751 btrfs_err(NULL
, "failed to lookup block device for path %s: %d",
753 return ERR_PTR(error
);
756 fs_devices
= find_fsid_by_device(disk_super
, path_devt
, &same_fsid_diff_dev
);
759 fs_devices
= alloc_fs_devices(disk_super
->fsid
);
760 if (IS_ERR(fs_devices
))
761 return ERR_CAST(fs_devices
);
763 if (has_metadata_uuid
)
764 memcpy(fs_devices
->metadata_uuid
,
765 disk_super
->metadata_uuid
, BTRFS_FSID_SIZE
);
767 if (same_fsid_diff_dev
) {
768 generate_random_uuid(fs_devices
->fsid
);
769 fs_devices
->temp_fsid
= true;
770 pr_info("BTRFS: device %s (%d:%d) using temp-fsid %pU\n",
771 path
, MAJOR(path_devt
), MINOR(path_devt
),
775 mutex_lock(&fs_devices
->device_list_mutex
);
776 list_add(&fs_devices
->fs_list
, &fs_uuids
);
780 struct btrfs_dev_lookup_args args
= {
782 .uuid
= disk_super
->dev_item
.uuid
,
785 mutex_lock(&fs_devices
->device_list_mutex
);
786 device
= btrfs_find_device(fs_devices
, &args
);
788 if (found_transid
> fs_devices
->latest_generation
) {
789 memcpy(fs_devices
->fsid
, disk_super
->fsid
,
791 memcpy(fs_devices
->metadata_uuid
,
792 btrfs_sb_fsid_ptr(disk_super
), BTRFS_FSID_SIZE
);
797 unsigned int nofs_flag
;
799 if (fs_devices
->opened
) {
801 "device %s (%d:%d) belongs to fsid %pU, and the fs is already mounted, scanned by %s (%d)",
802 path
, MAJOR(path_devt
), MINOR(path_devt
),
803 fs_devices
->fsid
, current
->comm
,
804 task_pid_nr(current
));
805 mutex_unlock(&fs_devices
->device_list_mutex
);
806 return ERR_PTR(-EBUSY
);
809 nofs_flag
= memalloc_nofs_save();
810 device
= btrfs_alloc_device(NULL
, &devid
,
811 disk_super
->dev_item
.uuid
, path
);
812 memalloc_nofs_restore(nofs_flag
);
813 if (IS_ERR(device
)) {
814 mutex_unlock(&fs_devices
->device_list_mutex
);
815 /* we can safely leave the fs_devices entry around */
819 device
->devt
= path_devt
;
821 list_add_rcu(&device
->dev_list
, &fs_devices
->devices
);
822 fs_devices
->num_devices
++;
824 device
->fs_devices
= fs_devices
;
825 *new_device_added
= true;
827 if (disk_super
->label
[0])
829 "BTRFS: device label %s devid %llu transid %llu %s (%d:%d) scanned by %s (%d)\n",
830 disk_super
->label
, devid
, found_transid
, path
,
831 MAJOR(path_devt
), MINOR(path_devt
),
832 current
->comm
, task_pid_nr(current
));
835 "BTRFS: device fsid %pU devid %llu transid %llu %s (%d:%d) scanned by %s (%d)\n",
836 disk_super
->fsid
, devid
, found_transid
, path
,
837 MAJOR(path_devt
), MINOR(path_devt
),
838 current
->comm
, task_pid_nr(current
));
840 } else if (!device
->name
|| strcmp(device
->name
->str
, path
)) {
842 * When FS is already mounted.
843 * 1. If you are here and if the device->name is NULL that
844 * means this device was missing at time of FS mount.
845 * 2. If you are here and if the device->name is different
846 * from 'path' that means either
847 * a. The same device disappeared and reappeared with
849 * b. The missing-disk-which-was-replaced, has
852 * We must allow 1 and 2a above. But 2b would be a spurious
855 * Further in case of 1 and 2a above, the disk at 'path'
856 * would have missed some transaction when it was away and
857 * in case of 2a the stale bdev has to be updated as well.
858 * 2b must not be allowed at all time.
862 * For now, we do allow update to btrfs_fs_device through the
863 * btrfs dev scan cli after FS has been mounted. We're still
864 * tracking a problem where systems fail mount by subvolume id
865 * when we reject replacement on a mounted FS.
867 if (!fs_devices
->opened
&& found_transid
< device
->generation
) {
869 * That is if the FS is _not_ mounted and if you
870 * are here, that means there is more than one
871 * disk with same uuid and devid.We keep the one
872 * with larger generation number or the last-in if
873 * generation are equal.
875 mutex_unlock(&fs_devices
->device_list_mutex
);
877 "device %s already registered with a higher generation, found %llu expect %llu",
878 path
, found_transid
, device
->generation
);
879 return ERR_PTR(-EEXIST
);
883 * We are going to replace the device path for a given devid,
884 * make sure it's the same device if the device is mounted
886 * NOTE: the device->fs_info may not be reliable here so pass
887 * in a NULL to message helpers instead. This avoids a possible
888 * use-after-free when the fs_info and fs_info->sb are already
892 if (device
->devt
!= path_devt
) {
893 mutex_unlock(&fs_devices
->device_list_mutex
);
894 btrfs_warn_in_rcu(NULL
,
895 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
896 path
, devid
, found_transid
,
898 task_pid_nr(current
));
899 return ERR_PTR(-EEXIST
);
901 btrfs_info_in_rcu(NULL
,
902 "devid %llu device path %s changed to %s scanned by %s (%d)",
903 devid
, btrfs_dev_name(device
),
905 task_pid_nr(current
));
908 name
= rcu_string_strdup(path
, GFP_NOFS
);
910 mutex_unlock(&fs_devices
->device_list_mutex
);
911 return ERR_PTR(-ENOMEM
);
913 rcu_string_free(device
->name
);
914 rcu_assign_pointer(device
->name
, name
);
915 if (test_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
)) {
916 fs_devices
->missing_devices
--;
917 clear_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
);
919 device
->devt
= path_devt
;
923 * Unmount does not free the btrfs_device struct but would zero
924 * generation along with most of the other members. So just update
925 * it back. We need it to pick the disk with largest generation
928 if (!fs_devices
->opened
) {
929 device
->generation
= found_transid
;
930 fs_devices
->latest_generation
= max_t(u64
, found_transid
,
931 fs_devices
->latest_generation
);
934 fs_devices
->total_devices
= btrfs_super_num_devices(disk_super
);
936 mutex_unlock(&fs_devices
->device_list_mutex
);
940 static struct btrfs_fs_devices
*clone_fs_devices(struct btrfs_fs_devices
*orig
)
942 struct btrfs_fs_devices
*fs_devices
;
943 struct btrfs_device
*device
;
944 struct btrfs_device
*orig_dev
;
947 lockdep_assert_held(&uuid_mutex
);
949 fs_devices
= alloc_fs_devices(orig
->fsid
);
950 if (IS_ERR(fs_devices
))
953 fs_devices
->total_devices
= orig
->total_devices
;
955 list_for_each_entry(orig_dev
, &orig
->devices
, dev_list
) {
956 const char *dev_path
= NULL
;
959 * This is ok to do without RCU read locked because we hold the
960 * uuid mutex so nothing we touch in here is going to disappear.
963 dev_path
= orig_dev
->name
->str
;
965 device
= btrfs_alloc_device(NULL
, &orig_dev
->devid
,
966 orig_dev
->uuid
, dev_path
);
967 if (IS_ERR(device
)) {
968 ret
= PTR_ERR(device
);
972 if (orig_dev
->zone_info
) {
973 struct btrfs_zoned_device_info
*zone_info
;
975 zone_info
= btrfs_clone_dev_zone_info(orig_dev
);
977 btrfs_free_device(device
);
981 device
->zone_info
= zone_info
;
984 list_add(&device
->dev_list
, &fs_devices
->devices
);
985 device
->fs_devices
= fs_devices
;
986 fs_devices
->num_devices
++;
990 free_fs_devices(fs_devices
);
994 static void __btrfs_free_extra_devids(struct btrfs_fs_devices
*fs_devices
,
995 struct btrfs_device
**latest_dev
)
997 struct btrfs_device
*device
, *next
;
999 /* This is the initialized path, it is safe to release the devices. */
1000 list_for_each_entry_safe(device
, next
, &fs_devices
->devices
, dev_list
) {
1001 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
)) {
1002 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT
,
1003 &device
->dev_state
) &&
1004 !test_bit(BTRFS_DEV_STATE_MISSING
,
1005 &device
->dev_state
) &&
1007 device
->generation
> (*latest_dev
)->generation
)) {
1008 *latest_dev
= device
;
1014 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1015 * in btrfs_init_dev_replace() so just continue.
1017 if (device
->devid
== BTRFS_DEV_REPLACE_DEVID
)
1020 if (device
->bdev_file
) {
1021 fput(device
->bdev_file
);
1022 device
->bdev
= NULL
;
1023 device
->bdev_file
= NULL
;
1024 fs_devices
->open_devices
--;
1026 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
1027 list_del_init(&device
->dev_alloc_list
);
1028 clear_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
1029 fs_devices
->rw_devices
--;
1031 list_del_init(&device
->dev_list
);
1032 fs_devices
->num_devices
--;
1033 btrfs_free_device(device
);
1039 * After we have read the system tree and know devids belonging to this
1040 * filesystem, remove the device which does not belong there.
1042 void btrfs_free_extra_devids(struct btrfs_fs_devices
*fs_devices
)
1044 struct btrfs_device
*latest_dev
= NULL
;
1045 struct btrfs_fs_devices
*seed_dev
;
1047 mutex_lock(&uuid_mutex
);
1048 __btrfs_free_extra_devids(fs_devices
, &latest_dev
);
1050 list_for_each_entry(seed_dev
, &fs_devices
->seed_list
, seed_list
)
1051 __btrfs_free_extra_devids(seed_dev
, &latest_dev
);
1053 fs_devices
->latest_dev
= latest_dev
;
1055 mutex_unlock(&uuid_mutex
);
1058 static void btrfs_close_bdev(struct btrfs_device
*device
)
1063 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
1064 sync_blockdev(device
->bdev
);
1065 invalidate_bdev(device
->bdev
);
1068 fput(device
->bdev_file
);
1071 static void btrfs_close_one_device(struct btrfs_device
*device
)
1073 struct btrfs_fs_devices
*fs_devices
= device
->fs_devices
;
1075 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
) &&
1076 device
->devid
!= BTRFS_DEV_REPLACE_DEVID
) {
1077 list_del_init(&device
->dev_alloc_list
);
1078 fs_devices
->rw_devices
--;
1081 if (device
->devid
== BTRFS_DEV_REPLACE_DEVID
)
1082 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
);
1084 if (test_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
)) {
1085 clear_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
);
1086 fs_devices
->missing_devices
--;
1089 btrfs_close_bdev(device
);
1091 fs_devices
->open_devices
--;
1092 device
->bdev
= NULL
;
1094 clear_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
1095 btrfs_destroy_dev_zone_info(device
);
1097 device
->fs_info
= NULL
;
1098 atomic_set(&device
->dev_stats_ccnt
, 0);
1099 extent_io_tree_release(&device
->alloc_state
);
1102 * Reset the flush error record. We might have a transient flush error
1103 * in this mount, and if so we aborted the current transaction and set
1104 * the fs to an error state, guaranteeing no super blocks can be further
1105 * committed. However that error might be transient and if we unmount the
1106 * filesystem and mount it again, we should allow the mount to succeed
1107 * (btrfs_check_rw_degradable() should not fail) - if after mounting the
1108 * filesystem again we still get flush errors, then we will again abort
1109 * any transaction and set the error state, guaranteeing no commits of
1110 * unsafe super blocks.
1112 device
->last_flush_error
= 0;
1114 /* Verify the device is back in a pristine state */
1115 WARN_ON(test_bit(BTRFS_DEV_STATE_FLUSH_SENT
, &device
->dev_state
));
1116 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
));
1117 WARN_ON(!list_empty(&device
->dev_alloc_list
));
1118 WARN_ON(!list_empty(&device
->post_commit_list
));
1121 static void close_fs_devices(struct btrfs_fs_devices
*fs_devices
)
1123 struct btrfs_device
*device
, *tmp
;
1125 lockdep_assert_held(&uuid_mutex
);
1127 if (--fs_devices
->opened
> 0)
1130 list_for_each_entry_safe(device
, tmp
, &fs_devices
->devices
, dev_list
)
1131 btrfs_close_one_device(device
);
1133 WARN_ON(fs_devices
->open_devices
);
1134 WARN_ON(fs_devices
->rw_devices
);
1135 fs_devices
->opened
= 0;
1136 fs_devices
->seeding
= false;
1137 fs_devices
->fs_info
= NULL
;
1140 void btrfs_close_devices(struct btrfs_fs_devices
*fs_devices
)
1143 struct btrfs_fs_devices
*tmp
;
1145 mutex_lock(&uuid_mutex
);
1146 close_fs_devices(fs_devices
);
1147 if (!fs_devices
->opened
) {
1148 list_splice_init(&fs_devices
->seed_list
, &list
);
1151 * If the struct btrfs_fs_devices is not assembled with any
1152 * other device, it can be re-initialized during the next mount
1153 * without the needing device-scan step. Therefore, it can be
1156 if (fs_devices
->num_devices
== 1) {
1157 list_del(&fs_devices
->fs_list
);
1158 free_fs_devices(fs_devices
);
1163 list_for_each_entry_safe(fs_devices
, tmp
, &list
, seed_list
) {
1164 close_fs_devices(fs_devices
);
1165 list_del(&fs_devices
->seed_list
);
1166 free_fs_devices(fs_devices
);
1168 mutex_unlock(&uuid_mutex
);
1171 static int open_fs_devices(struct btrfs_fs_devices
*fs_devices
,
1172 blk_mode_t flags
, void *holder
)
1174 struct btrfs_device
*device
;
1175 struct btrfs_device
*latest_dev
= NULL
;
1176 struct btrfs_device
*tmp_device
;
1178 list_for_each_entry_safe(device
, tmp_device
, &fs_devices
->devices
,
1182 ret
= btrfs_open_one_device(fs_devices
, device
, flags
, holder
);
1184 (!latest_dev
|| device
->generation
> latest_dev
->generation
)) {
1185 latest_dev
= device
;
1186 } else if (ret
== -ENODATA
) {
1187 fs_devices
->num_devices
--;
1188 list_del(&device
->dev_list
);
1189 btrfs_free_device(device
);
1192 if (fs_devices
->open_devices
== 0)
1195 fs_devices
->opened
= 1;
1196 fs_devices
->latest_dev
= latest_dev
;
1197 fs_devices
->total_rw_bytes
= 0;
1198 fs_devices
->chunk_alloc_policy
= BTRFS_CHUNK_ALLOC_REGULAR
;
1199 fs_devices
->read_policy
= BTRFS_READ_POLICY_PID
;
1204 static int devid_cmp(void *priv
, const struct list_head
*a
,
1205 const struct list_head
*b
)
1207 const struct btrfs_device
*dev1
, *dev2
;
1209 dev1
= list_entry(a
, struct btrfs_device
, dev_list
);
1210 dev2
= list_entry(b
, struct btrfs_device
, dev_list
);
1212 if (dev1
->devid
< dev2
->devid
)
1214 else if (dev1
->devid
> dev2
->devid
)
1219 int btrfs_open_devices(struct btrfs_fs_devices
*fs_devices
,
1220 blk_mode_t flags
, void *holder
)
1224 lockdep_assert_held(&uuid_mutex
);
1226 * The device_list_mutex cannot be taken here in case opening the
1227 * underlying device takes further locks like open_mutex.
1229 * We also don't need the lock here as this is called during mount and
1230 * exclusion is provided by uuid_mutex
1233 if (fs_devices
->opened
) {
1234 fs_devices
->opened
++;
1237 list_sort(NULL
, &fs_devices
->devices
, devid_cmp
);
1238 ret
= open_fs_devices(fs_devices
, flags
, holder
);
1244 void btrfs_release_disk_super(struct btrfs_super_block
*super
)
1246 struct page
*page
= virt_to_page(super
);
1251 static struct btrfs_super_block
*btrfs_read_disk_super(struct block_device
*bdev
,
1252 u64 bytenr
, u64 bytenr_orig
)
1254 struct btrfs_super_block
*disk_super
;
1259 /* make sure our super fits in the device */
1260 if (bytenr
+ PAGE_SIZE
>= bdev_nr_bytes(bdev
))
1261 return ERR_PTR(-EINVAL
);
1263 /* make sure our super fits in the page */
1264 if (sizeof(*disk_super
) > PAGE_SIZE
)
1265 return ERR_PTR(-EINVAL
);
1267 /* make sure our super doesn't straddle pages on disk */
1268 index
= bytenr
>> PAGE_SHIFT
;
1269 if ((bytenr
+ sizeof(*disk_super
) - 1) >> PAGE_SHIFT
!= index
)
1270 return ERR_PTR(-EINVAL
);
1272 /* pull in the page with our super */
1273 page
= read_cache_page_gfp(bdev
->bd_inode
->i_mapping
, index
, GFP_KERNEL
);
1276 return ERR_CAST(page
);
1278 p
= page_address(page
);
1280 /* align our pointer to the offset of the super block */
1281 disk_super
= p
+ offset_in_page(bytenr
);
1283 if (btrfs_super_bytenr(disk_super
) != bytenr_orig
||
1284 btrfs_super_magic(disk_super
) != BTRFS_MAGIC
) {
1285 btrfs_release_disk_super(p
);
1286 return ERR_PTR(-EINVAL
);
1289 if (disk_super
->label
[0] && disk_super
->label
[BTRFS_LABEL_SIZE
- 1])
1290 disk_super
->label
[BTRFS_LABEL_SIZE
- 1] = 0;
1295 int btrfs_forget_devices(dev_t devt
)
1299 mutex_lock(&uuid_mutex
);
1300 ret
= btrfs_free_stale_devices(devt
, NULL
);
1301 mutex_unlock(&uuid_mutex
);
1306 static bool btrfs_skip_registration(struct btrfs_super_block
*disk_super
,
1307 const char *path
, dev_t devt
,
1310 struct btrfs_fs_devices
*fs_devices
;
1313 * Do not skip device registration for mounted devices with matching
1314 * maj:min but different paths. Booting without initrd relies on
1315 * /dev/root initially, later replaced with the actual root device.
1316 * A successful scan ensures grub2-probe selects the correct device.
1318 list_for_each_entry(fs_devices
, &fs_uuids
, fs_list
) {
1319 struct btrfs_device
*device
;
1321 mutex_lock(&fs_devices
->device_list_mutex
);
1323 if (!fs_devices
->opened
) {
1324 mutex_unlock(&fs_devices
->device_list_mutex
);
1328 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
) {
1329 if (device
->bdev
&& (device
->bdev
->bd_dev
== devt
) &&
1330 strcmp(device
->name
->str
, path
) != 0) {
1331 mutex_unlock(&fs_devices
->device_list_mutex
);
1333 /* Do not skip registration. */
1337 mutex_unlock(&fs_devices
->device_list_mutex
);
1340 if (!mount_arg_dev
&& btrfs_super_num_devices(disk_super
) == 1 &&
1341 !(btrfs_super_flags(disk_super
) & BTRFS_SUPER_FLAG_SEEDING
))
1348 * Look for a btrfs signature on a device. This may be called out of the mount path
1349 * and we are not allowed to call set_blocksize during the scan. The superblock
1350 * is read via pagecache.
1352 * With @mount_arg_dev it's a scan during mount time that will always register
1353 * the device or return an error. Multi-device and seeding devices are registered
1356 struct btrfs_device
*btrfs_scan_one_device(const char *path
, blk_mode_t flags
,
1359 struct btrfs_super_block
*disk_super
;
1360 bool new_device_added
= false;
1361 struct btrfs_device
*device
= NULL
;
1362 struct file
*bdev_file
;
1363 u64 bytenr
, bytenr_orig
;
1367 lockdep_assert_held(&uuid_mutex
);
1370 * we would like to check all the supers, but that would make
1371 * a btrfs mount succeed after a mkfs from a different FS.
1372 * So, we need to add a special mount option to scan for
1373 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1377 * Avoid an exclusive open here, as the systemd-udev may initiate the
1378 * device scan which may race with the user's mount or mkfs command,
1379 * resulting in failure.
1380 * Since the device scan is solely for reading purposes, there is no
1381 * need for an exclusive open. Additionally, the devices are read again
1382 * during the mount process. It is ok to get some inconsistent
1383 * values temporarily, as the device paths of the fsid are the only
1384 * required information for assembling the volume.
1386 bdev_file
= bdev_file_open_by_path(path
, flags
, NULL
, NULL
);
1387 if (IS_ERR(bdev_file
))
1388 return ERR_CAST(bdev_file
);
1390 bytenr_orig
= btrfs_sb_offset(0);
1391 ret
= btrfs_sb_log_location_bdev(file_bdev(bdev_file
), 0, READ
, &bytenr
);
1393 device
= ERR_PTR(ret
);
1394 goto error_bdev_put
;
1397 disk_super
= btrfs_read_disk_super(file_bdev(bdev_file
), bytenr
,
1399 if (IS_ERR(disk_super
)) {
1400 device
= ERR_CAST(disk_super
);
1401 goto error_bdev_put
;
1404 devt
= file_bdev(bdev_file
)->bd_dev
;
1405 if (btrfs_skip_registration(disk_super
, path
, devt
, mount_arg_dev
)) {
1406 pr_debug("BTRFS: skip registering single non-seed device %s (%d:%d)\n",
1407 path
, MAJOR(devt
), MINOR(devt
));
1409 btrfs_free_stale_devices(devt
, NULL
);
1412 goto free_disk_super
;
1415 device
= device_list_add(path
, disk_super
, &new_device_added
);
1416 if (!IS_ERR(device
) && new_device_added
)
1417 btrfs_free_stale_devices(device
->devt
, device
);
1420 btrfs_release_disk_super(disk_super
);
1429 * Try to find a chunk that intersects [start, start + len] range and when one
1430 * such is found, record the end of it in *start
1432 static bool contains_pending_extent(struct btrfs_device
*device
, u64
*start
,
1435 u64 physical_start
, physical_end
;
1437 lockdep_assert_held(&device
->fs_info
->chunk_mutex
);
1439 if (find_first_extent_bit(&device
->alloc_state
, *start
,
1440 &physical_start
, &physical_end
,
1441 CHUNK_ALLOCATED
, NULL
)) {
1443 if (in_range(physical_start
, *start
, len
) ||
1444 in_range(*start
, physical_start
,
1445 physical_end
+ 1 - physical_start
)) {
1446 *start
= physical_end
+ 1;
1453 static u64
dev_extent_search_start(struct btrfs_device
*device
)
1455 switch (device
->fs_devices
->chunk_alloc_policy
) {
1456 case BTRFS_CHUNK_ALLOC_REGULAR
:
1457 return BTRFS_DEVICE_RANGE_RESERVED
;
1458 case BTRFS_CHUNK_ALLOC_ZONED
:
1460 * We don't care about the starting region like regular
1461 * allocator, because we anyway use/reserve the first two zones
1462 * for superblock logging.
1470 static bool dev_extent_hole_check_zoned(struct btrfs_device
*device
,
1471 u64
*hole_start
, u64
*hole_size
,
1474 u64 zone_size
= device
->zone_info
->zone_size
;
1477 bool changed
= false;
1479 ASSERT(IS_ALIGNED(*hole_start
, zone_size
));
1481 while (*hole_size
> 0) {
1482 pos
= btrfs_find_allocatable_zones(device
, *hole_start
,
1483 *hole_start
+ *hole_size
,
1485 if (pos
!= *hole_start
) {
1486 *hole_size
= *hole_start
+ *hole_size
- pos
;
1489 if (*hole_size
< num_bytes
)
1493 ret
= btrfs_ensure_empty_zones(device
, pos
, num_bytes
);
1495 /* Range is ensured to be empty */
1499 /* Given hole range was invalid (outside of device) */
1500 if (ret
== -ERANGE
) {
1501 *hole_start
+= *hole_size
;
1506 *hole_start
+= zone_size
;
1507 *hole_size
-= zone_size
;
1515 * Check if specified hole is suitable for allocation.
1517 * @device: the device which we have the hole
1518 * @hole_start: starting position of the hole
1519 * @hole_size: the size of the hole
1520 * @num_bytes: the size of the free space that we need
1522 * This function may modify @hole_start and @hole_size to reflect the suitable
1523 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1525 static bool dev_extent_hole_check(struct btrfs_device
*device
, u64
*hole_start
,
1526 u64
*hole_size
, u64 num_bytes
)
1528 bool changed
= false;
1529 u64 hole_end
= *hole_start
+ *hole_size
;
1533 * Check before we set max_hole_start, otherwise we could end up
1534 * sending back this offset anyway.
1536 if (contains_pending_extent(device
, hole_start
, *hole_size
)) {
1537 if (hole_end
>= *hole_start
)
1538 *hole_size
= hole_end
- *hole_start
;
1544 switch (device
->fs_devices
->chunk_alloc_policy
) {
1545 case BTRFS_CHUNK_ALLOC_REGULAR
:
1546 /* No extra check */
1548 case BTRFS_CHUNK_ALLOC_ZONED
:
1549 if (dev_extent_hole_check_zoned(device
, hole_start
,
1550 hole_size
, num_bytes
)) {
1553 * The changed hole can contain pending extent.
1554 * Loop again to check that.
1570 * Find free space in the specified device.
1572 * @device: the device which we search the free space in
1573 * @num_bytes: the size of the free space that we need
1574 * @search_start: the position from which to begin the search
1575 * @start: store the start of the free space.
1576 * @len: the size of the free space. that we find, or the size
1577 * of the max free space if we don't find suitable free space
1579 * This does a pretty simple search, the expectation is that it is called very
1580 * infrequently and that a given device has a small number of extents.
1582 * @start is used to store the start of the free space if we find. But if we
1583 * don't find suitable free space, it will be used to store the start position
1584 * of the max free space.
1586 * @len is used to store the size of the free space that we find.
1587 * But if we don't find suitable free space, it is used to store the size of
1588 * the max free space.
1590 * NOTE: This function will search *commit* root of device tree, and does extra
1591 * check to ensure dev extents are not double allocated.
1592 * This makes the function safe to allocate dev extents but may not report
1593 * correct usable device space, as device extent freed in current transaction
1594 * is not reported as available.
1596 static int find_free_dev_extent(struct btrfs_device
*device
, u64 num_bytes
,
1597 u64
*start
, u64
*len
)
1599 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
1600 struct btrfs_root
*root
= fs_info
->dev_root
;
1601 struct btrfs_key key
;
1602 struct btrfs_dev_extent
*dev_extent
;
1603 struct btrfs_path
*path
;
1607 u64 max_hole_size
= 0;
1609 u64 search_end
= device
->total_bytes
;
1612 struct extent_buffer
*l
;
1614 search_start
= dev_extent_search_start(device
);
1615 max_hole_start
= search_start
;
1617 WARN_ON(device
->zone_info
&&
1618 !IS_ALIGNED(num_bytes
, device
->zone_info
->zone_size
));
1620 path
= btrfs_alloc_path();
1626 if (search_start
>= search_end
||
1627 test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
)) {
1632 path
->reada
= READA_FORWARD
;
1633 path
->search_commit_root
= 1;
1634 path
->skip_locking
= 1;
1636 key
.objectid
= device
->devid
;
1637 key
.offset
= search_start
;
1638 key
.type
= BTRFS_DEV_EXTENT_KEY
;
1640 ret
= btrfs_search_backwards(root
, &key
, path
);
1644 while (search_start
< search_end
) {
1646 slot
= path
->slots
[0];
1647 if (slot
>= btrfs_header_nritems(l
)) {
1648 ret
= btrfs_next_leaf(root
, path
);
1656 btrfs_item_key_to_cpu(l
, &key
, slot
);
1658 if (key
.objectid
< device
->devid
)
1661 if (key
.objectid
> device
->devid
)
1664 if (key
.type
!= BTRFS_DEV_EXTENT_KEY
)
1667 if (key
.offset
> search_end
)
1670 if (key
.offset
> search_start
) {
1671 hole_size
= key
.offset
- search_start
;
1672 dev_extent_hole_check(device
, &search_start
, &hole_size
,
1675 if (hole_size
> max_hole_size
) {
1676 max_hole_start
= search_start
;
1677 max_hole_size
= hole_size
;
1681 * If this free space is greater than which we need,
1682 * it must be the max free space that we have found
1683 * until now, so max_hole_start must point to the start
1684 * of this free space and the length of this free space
1685 * is stored in max_hole_size. Thus, we return
1686 * max_hole_start and max_hole_size and go back to the
1689 if (hole_size
>= num_bytes
) {
1695 dev_extent
= btrfs_item_ptr(l
, slot
, struct btrfs_dev_extent
);
1696 extent_end
= key
.offset
+ btrfs_dev_extent_length(l
,
1698 if (extent_end
> search_start
)
1699 search_start
= extent_end
;
1706 * At this point, search_start should be the end of
1707 * allocated dev extents, and when shrinking the device,
1708 * search_end may be smaller than search_start.
1710 if (search_end
> search_start
) {
1711 hole_size
= search_end
- search_start
;
1712 if (dev_extent_hole_check(device
, &search_start
, &hole_size
,
1714 btrfs_release_path(path
);
1718 if (hole_size
> max_hole_size
) {
1719 max_hole_start
= search_start
;
1720 max_hole_size
= hole_size
;
1725 if (max_hole_size
< num_bytes
)
1730 ASSERT(max_hole_start
+ max_hole_size
<= search_end
);
1732 btrfs_free_path(path
);
1733 *start
= max_hole_start
;
1735 *len
= max_hole_size
;
1739 static int btrfs_free_dev_extent(struct btrfs_trans_handle
*trans
,
1740 struct btrfs_device
*device
,
1741 u64 start
, u64
*dev_extent_len
)
1743 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
1744 struct btrfs_root
*root
= fs_info
->dev_root
;
1746 struct btrfs_path
*path
;
1747 struct btrfs_key key
;
1748 struct btrfs_key found_key
;
1749 struct extent_buffer
*leaf
= NULL
;
1750 struct btrfs_dev_extent
*extent
= NULL
;
1752 path
= btrfs_alloc_path();
1756 key
.objectid
= device
->devid
;
1758 key
.type
= BTRFS_DEV_EXTENT_KEY
;
1760 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
1762 ret
= btrfs_previous_item(root
, path
, key
.objectid
,
1763 BTRFS_DEV_EXTENT_KEY
);
1766 leaf
= path
->nodes
[0];
1767 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
1768 extent
= btrfs_item_ptr(leaf
, path
->slots
[0],
1769 struct btrfs_dev_extent
);
1770 BUG_ON(found_key
.offset
> start
|| found_key
.offset
+
1771 btrfs_dev_extent_length(leaf
, extent
) < start
);
1773 btrfs_release_path(path
);
1775 } else if (ret
== 0) {
1776 leaf
= path
->nodes
[0];
1777 extent
= btrfs_item_ptr(leaf
, path
->slots
[0],
1778 struct btrfs_dev_extent
);
1783 *dev_extent_len
= btrfs_dev_extent_length(leaf
, extent
);
1785 ret
= btrfs_del_item(trans
, root
, path
);
1787 set_bit(BTRFS_TRANS_HAVE_FREE_BGS
, &trans
->transaction
->flags
);
1789 btrfs_free_path(path
);
1793 static u64
find_next_chunk(struct btrfs_fs_info
*fs_info
)
1798 read_lock(&fs_info
->mapping_tree_lock
);
1799 n
= rb_last(&fs_info
->mapping_tree
.rb_root
);
1801 struct btrfs_chunk_map
*map
;
1803 map
= rb_entry(n
, struct btrfs_chunk_map
, rb_node
);
1804 ret
= map
->start
+ map
->chunk_len
;
1806 read_unlock(&fs_info
->mapping_tree_lock
);
1811 static noinline
int find_next_devid(struct btrfs_fs_info
*fs_info
,
1815 struct btrfs_key key
;
1816 struct btrfs_key found_key
;
1817 struct btrfs_path
*path
;
1819 path
= btrfs_alloc_path();
1823 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
1824 key
.type
= BTRFS_DEV_ITEM_KEY
;
1825 key
.offset
= (u64
)-1;
1827 ret
= btrfs_search_slot(NULL
, fs_info
->chunk_root
, &key
, path
, 0, 0);
1833 btrfs_err(fs_info
, "corrupted chunk tree devid -1 matched");
1838 ret
= btrfs_previous_item(fs_info
->chunk_root
, path
,
1839 BTRFS_DEV_ITEMS_OBJECTID
,
1840 BTRFS_DEV_ITEM_KEY
);
1844 btrfs_item_key_to_cpu(path
->nodes
[0], &found_key
,
1846 *devid_ret
= found_key
.offset
+ 1;
1850 btrfs_free_path(path
);
1855 * the device information is stored in the chunk root
1856 * the btrfs_device struct should be fully filled in
1858 static int btrfs_add_dev_item(struct btrfs_trans_handle
*trans
,
1859 struct btrfs_device
*device
)
1862 struct btrfs_path
*path
;
1863 struct btrfs_dev_item
*dev_item
;
1864 struct extent_buffer
*leaf
;
1865 struct btrfs_key key
;
1868 path
= btrfs_alloc_path();
1872 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
1873 key
.type
= BTRFS_DEV_ITEM_KEY
;
1874 key
.offset
= device
->devid
;
1876 btrfs_reserve_chunk_metadata(trans
, true);
1877 ret
= btrfs_insert_empty_item(trans
, trans
->fs_info
->chunk_root
, path
,
1878 &key
, sizeof(*dev_item
));
1879 btrfs_trans_release_chunk_metadata(trans
);
1883 leaf
= path
->nodes
[0];
1884 dev_item
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_dev_item
);
1886 btrfs_set_device_id(leaf
, dev_item
, device
->devid
);
1887 btrfs_set_device_generation(leaf
, dev_item
, 0);
1888 btrfs_set_device_type(leaf
, dev_item
, device
->type
);
1889 btrfs_set_device_io_align(leaf
, dev_item
, device
->io_align
);
1890 btrfs_set_device_io_width(leaf
, dev_item
, device
->io_width
);
1891 btrfs_set_device_sector_size(leaf
, dev_item
, device
->sector_size
);
1892 btrfs_set_device_total_bytes(leaf
, dev_item
,
1893 btrfs_device_get_disk_total_bytes(device
));
1894 btrfs_set_device_bytes_used(leaf
, dev_item
,
1895 btrfs_device_get_bytes_used(device
));
1896 btrfs_set_device_group(leaf
, dev_item
, 0);
1897 btrfs_set_device_seek_speed(leaf
, dev_item
, 0);
1898 btrfs_set_device_bandwidth(leaf
, dev_item
, 0);
1899 btrfs_set_device_start_offset(leaf
, dev_item
, 0);
1901 ptr
= btrfs_device_uuid(dev_item
);
1902 write_extent_buffer(leaf
, device
->uuid
, ptr
, BTRFS_UUID_SIZE
);
1903 ptr
= btrfs_device_fsid(dev_item
);
1904 write_extent_buffer(leaf
, trans
->fs_info
->fs_devices
->metadata_uuid
,
1905 ptr
, BTRFS_FSID_SIZE
);
1906 btrfs_mark_buffer_dirty(trans
, leaf
);
1910 btrfs_free_path(path
);
1915 * Function to update ctime/mtime for a given device path.
1916 * Mainly used for ctime/mtime based probe like libblkid.
1918 * We don't care about errors here, this is just to be kind to userspace.
1920 static void update_dev_time(const char *device_path
)
1925 ret
= kern_path(device_path
, LOOKUP_FOLLOW
, &path
);
1929 inode_update_time(d_inode(path
.dentry
), S_MTIME
| S_CTIME
| S_VERSION
);
1933 static int btrfs_rm_dev_item(struct btrfs_trans_handle
*trans
,
1934 struct btrfs_device
*device
)
1936 struct btrfs_root
*root
= device
->fs_info
->chunk_root
;
1938 struct btrfs_path
*path
;
1939 struct btrfs_key key
;
1941 path
= btrfs_alloc_path();
1945 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
1946 key
.type
= BTRFS_DEV_ITEM_KEY
;
1947 key
.offset
= device
->devid
;
1949 btrfs_reserve_chunk_metadata(trans
, false);
1950 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
1951 btrfs_trans_release_chunk_metadata(trans
);
1958 ret
= btrfs_del_item(trans
, root
, path
);
1960 btrfs_free_path(path
);
1965 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1966 * filesystem. It's up to the caller to adjust that number regarding eg. device
1969 static int btrfs_check_raid_min_devices(struct btrfs_fs_info
*fs_info
,
1977 seq
= read_seqbegin(&fs_info
->profiles_lock
);
1979 all_avail
= fs_info
->avail_data_alloc_bits
|
1980 fs_info
->avail_system_alloc_bits
|
1981 fs_info
->avail_metadata_alloc_bits
;
1982 } while (read_seqretry(&fs_info
->profiles_lock
, seq
));
1984 for (i
= 0; i
< BTRFS_NR_RAID_TYPES
; i
++) {
1985 if (!(all_avail
& btrfs_raid_array
[i
].bg_flag
))
1988 if (num_devices
< btrfs_raid_array
[i
].devs_min
)
1989 return btrfs_raid_array
[i
].mindev_error
;
1995 static struct btrfs_device
* btrfs_find_next_active_device(
1996 struct btrfs_fs_devices
*fs_devs
, struct btrfs_device
*device
)
1998 struct btrfs_device
*next_device
;
2000 list_for_each_entry(next_device
, &fs_devs
->devices
, dev_list
) {
2001 if (next_device
!= device
&&
2002 !test_bit(BTRFS_DEV_STATE_MISSING
, &next_device
->dev_state
)
2003 && next_device
->bdev
)
2011 * Helper function to check if the given device is part of s_bdev / latest_dev
2012 * and replace it with the provided or the next active device, in the context
2013 * where this function called, there should be always be another device (or
2014 * this_dev) which is active.
2016 void __cold
btrfs_assign_next_active_device(struct btrfs_device
*device
,
2017 struct btrfs_device
*next_device
)
2019 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
2022 next_device
= btrfs_find_next_active_device(fs_info
->fs_devices
,
2024 ASSERT(next_device
);
2026 if (fs_info
->sb
->s_bdev
&&
2027 (fs_info
->sb
->s_bdev
== device
->bdev
))
2028 fs_info
->sb
->s_bdev
= next_device
->bdev
;
2030 if (fs_info
->fs_devices
->latest_dev
->bdev
== device
->bdev
)
2031 fs_info
->fs_devices
->latest_dev
= next_device
;
2035 * Return btrfs_fs_devices::num_devices excluding the device that's being
2036 * currently replaced.
2038 static u64
btrfs_num_devices(struct btrfs_fs_info
*fs_info
)
2040 u64 num_devices
= fs_info
->fs_devices
->num_devices
;
2042 down_read(&fs_info
->dev_replace
.rwsem
);
2043 if (btrfs_dev_replace_is_ongoing(&fs_info
->dev_replace
)) {
2044 ASSERT(num_devices
> 1);
2047 up_read(&fs_info
->dev_replace
.rwsem
);
2052 static void btrfs_scratch_superblock(struct btrfs_fs_info
*fs_info
,
2053 struct block_device
*bdev
, int copy_num
)
2055 struct btrfs_super_block
*disk_super
;
2056 const size_t len
= sizeof(disk_super
->magic
);
2057 const u64 bytenr
= btrfs_sb_offset(copy_num
);
2060 disk_super
= btrfs_read_disk_super(bdev
, bytenr
, bytenr
);
2061 if (IS_ERR(disk_super
))
2064 memset(&disk_super
->magic
, 0, len
);
2065 folio_mark_dirty(virt_to_folio(disk_super
));
2066 btrfs_release_disk_super(disk_super
);
2068 ret
= sync_blockdev_range(bdev
, bytenr
, bytenr
+ len
- 1);
2070 btrfs_warn(fs_info
, "error clearing superblock number %d (%d)",
2074 void btrfs_scratch_superblocks(struct btrfs_fs_info
*fs_info
, struct btrfs_device
*device
)
2077 struct block_device
*bdev
= device
->bdev
;
2082 for (copy_num
= 0; copy_num
< BTRFS_SUPER_MIRROR_MAX
; copy_num
++) {
2083 if (bdev_is_zoned(bdev
))
2084 btrfs_reset_sb_log_zones(bdev
, copy_num
);
2086 btrfs_scratch_superblock(fs_info
, bdev
, copy_num
);
2089 /* Notify udev that device has changed */
2090 btrfs_kobject_uevent(bdev
, KOBJ_CHANGE
);
2092 /* Update ctime/mtime for device path for libblkid */
2093 update_dev_time(device
->name
->str
);
2096 int btrfs_rm_device(struct btrfs_fs_info
*fs_info
,
2097 struct btrfs_dev_lookup_args
*args
,
2098 struct file
**bdev_file
)
2100 struct btrfs_trans_handle
*trans
;
2101 struct btrfs_device
*device
;
2102 struct btrfs_fs_devices
*cur_devices
;
2103 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
2107 if (btrfs_fs_incompat(fs_info
, EXTENT_TREE_V2
)) {
2108 btrfs_err(fs_info
, "device remove not supported on extent tree v2 yet");
2113 * The device list in fs_devices is accessed without locks (neither
2114 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2115 * filesystem and another device rm cannot run.
2117 num_devices
= btrfs_num_devices(fs_info
);
2119 ret
= btrfs_check_raid_min_devices(fs_info
, num_devices
- 1);
2123 device
= btrfs_find_device(fs_info
->fs_devices
, args
);
2126 ret
= BTRFS_ERROR_DEV_MISSING_NOT_FOUND
;
2132 if (btrfs_pinned_by_swapfile(fs_info
, device
)) {
2133 btrfs_warn_in_rcu(fs_info
,
2134 "cannot remove device %s (devid %llu) due to active swapfile",
2135 btrfs_dev_name(device
), device
->devid
);
2139 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
))
2140 return BTRFS_ERROR_DEV_TGT_REPLACE
;
2142 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
) &&
2143 fs_info
->fs_devices
->rw_devices
== 1)
2144 return BTRFS_ERROR_DEV_ONLY_WRITABLE
;
2146 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
2147 mutex_lock(&fs_info
->chunk_mutex
);
2148 list_del_init(&device
->dev_alloc_list
);
2149 device
->fs_devices
->rw_devices
--;
2150 mutex_unlock(&fs_info
->chunk_mutex
);
2153 ret
= btrfs_shrink_device(device
, 0);
2157 trans
= btrfs_start_transaction(fs_info
->chunk_root
, 0);
2158 if (IS_ERR(trans
)) {
2159 ret
= PTR_ERR(trans
);
2163 ret
= btrfs_rm_dev_item(trans
, device
);
2165 /* Any error in dev item removal is critical */
2167 "failed to remove device item for devid %llu: %d",
2168 device
->devid
, ret
);
2169 btrfs_abort_transaction(trans
, ret
);
2170 btrfs_end_transaction(trans
);
2174 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
);
2175 btrfs_scrub_cancel_dev(device
);
2178 * the device list mutex makes sure that we don't change
2179 * the device list while someone else is writing out all
2180 * the device supers. Whoever is writing all supers, should
2181 * lock the device list mutex before getting the number of
2182 * devices in the super block (super_copy). Conversely,
2183 * whoever updates the number of devices in the super block
2184 * (super_copy) should hold the device list mutex.
2188 * In normal cases the cur_devices == fs_devices. But in case
2189 * of deleting a seed device, the cur_devices should point to
2190 * its own fs_devices listed under the fs_devices->seed_list.
2192 cur_devices
= device
->fs_devices
;
2193 mutex_lock(&fs_devices
->device_list_mutex
);
2194 list_del_rcu(&device
->dev_list
);
2196 cur_devices
->num_devices
--;
2197 cur_devices
->total_devices
--;
2198 /* Update total_devices of the parent fs_devices if it's seed */
2199 if (cur_devices
!= fs_devices
)
2200 fs_devices
->total_devices
--;
2202 if (test_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
))
2203 cur_devices
->missing_devices
--;
2205 btrfs_assign_next_active_device(device
, NULL
);
2207 if (device
->bdev_file
) {
2208 cur_devices
->open_devices
--;
2209 /* remove sysfs entry */
2210 btrfs_sysfs_remove_device(device
);
2213 num_devices
= btrfs_super_num_devices(fs_info
->super_copy
) - 1;
2214 btrfs_set_super_num_devices(fs_info
->super_copy
, num_devices
);
2215 mutex_unlock(&fs_devices
->device_list_mutex
);
2218 * At this point, the device is zero sized and detached from the
2219 * devices list. All that's left is to zero out the old supers and
2222 * We cannot call btrfs_close_bdev() here because we're holding the sb
2223 * write lock, and fput() on the block device will pull in the
2224 * ->open_mutex on the block device and it's dependencies. Instead
2225 * just flush the device and let the caller do the final bdev_release.
2227 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
2228 btrfs_scratch_superblocks(fs_info
, device
);
2230 sync_blockdev(device
->bdev
);
2231 invalidate_bdev(device
->bdev
);
2235 *bdev_file
= device
->bdev_file
;
2237 btrfs_free_device(device
);
2240 * This can happen if cur_devices is the private seed devices list. We
2241 * cannot call close_fs_devices() here because it expects the uuid_mutex
2242 * to be held, but in fact we don't need that for the private
2243 * seed_devices, we can simply decrement cur_devices->opened and then
2244 * remove it from our list and free the fs_devices.
2246 if (cur_devices
->num_devices
== 0) {
2247 list_del_init(&cur_devices
->seed_list
);
2248 ASSERT(cur_devices
->opened
== 1);
2249 cur_devices
->opened
--;
2250 free_fs_devices(cur_devices
);
2253 ret
= btrfs_commit_transaction(trans
);
2258 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
2259 mutex_lock(&fs_info
->chunk_mutex
);
2260 list_add(&device
->dev_alloc_list
,
2261 &fs_devices
->alloc_list
);
2262 device
->fs_devices
->rw_devices
++;
2263 mutex_unlock(&fs_info
->chunk_mutex
);
2268 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device
*srcdev
)
2270 struct btrfs_fs_devices
*fs_devices
;
2272 lockdep_assert_held(&srcdev
->fs_info
->fs_devices
->device_list_mutex
);
2275 * in case of fs with no seed, srcdev->fs_devices will point
2276 * to fs_devices of fs_info. However when the dev being replaced is
2277 * a seed dev it will point to the seed's local fs_devices. In short
2278 * srcdev will have its correct fs_devices in both the cases.
2280 fs_devices
= srcdev
->fs_devices
;
2282 list_del_rcu(&srcdev
->dev_list
);
2283 list_del(&srcdev
->dev_alloc_list
);
2284 fs_devices
->num_devices
--;
2285 if (test_bit(BTRFS_DEV_STATE_MISSING
, &srcdev
->dev_state
))
2286 fs_devices
->missing_devices
--;
2288 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &srcdev
->dev_state
))
2289 fs_devices
->rw_devices
--;
2292 fs_devices
->open_devices
--;
2295 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device
*srcdev
)
2297 struct btrfs_fs_devices
*fs_devices
= srcdev
->fs_devices
;
2299 mutex_lock(&uuid_mutex
);
2301 btrfs_close_bdev(srcdev
);
2303 btrfs_free_device(srcdev
);
2305 /* if this is no devs we rather delete the fs_devices */
2306 if (!fs_devices
->num_devices
) {
2308 * On a mounted FS, num_devices can't be zero unless it's a
2309 * seed. In case of a seed device being replaced, the replace
2310 * target added to the sprout FS, so there will be no more
2311 * device left under the seed FS.
2313 ASSERT(fs_devices
->seeding
);
2315 list_del_init(&fs_devices
->seed_list
);
2316 close_fs_devices(fs_devices
);
2317 free_fs_devices(fs_devices
);
2319 mutex_unlock(&uuid_mutex
);
2322 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device
*tgtdev
)
2324 struct btrfs_fs_devices
*fs_devices
= tgtdev
->fs_info
->fs_devices
;
2326 mutex_lock(&fs_devices
->device_list_mutex
);
2328 btrfs_sysfs_remove_device(tgtdev
);
2331 fs_devices
->open_devices
--;
2333 fs_devices
->num_devices
--;
2335 btrfs_assign_next_active_device(tgtdev
, NULL
);
2337 list_del_rcu(&tgtdev
->dev_list
);
2339 mutex_unlock(&fs_devices
->device_list_mutex
);
2341 btrfs_scratch_superblocks(tgtdev
->fs_info
, tgtdev
);
2343 btrfs_close_bdev(tgtdev
);
2345 btrfs_free_device(tgtdev
);
2349 * Populate args from device at path.
2351 * @fs_info: the filesystem
2352 * @args: the args to populate
2353 * @path: the path to the device
2355 * This will read the super block of the device at @path and populate @args with
2356 * the devid, fsid, and uuid. This is meant to be used for ioctls that need to
2357 * lookup a device to operate on, but need to do it before we take any locks.
2358 * This properly handles the special case of "missing" that a user may pass in,
2359 * and does some basic sanity checks. The caller must make sure that @path is
2360 * properly NUL terminated before calling in, and must call
2361 * btrfs_put_dev_args_from_path() in order to free up the temporary fsid and
2364 * Return: 0 for success, -errno for failure
2366 int btrfs_get_dev_args_from_path(struct btrfs_fs_info
*fs_info
,
2367 struct btrfs_dev_lookup_args
*args
,
2370 struct btrfs_super_block
*disk_super
;
2371 struct file
*bdev_file
;
2374 if (!path
|| !path
[0])
2376 if (!strcmp(path
, "missing")) {
2377 args
->missing
= true;
2381 args
->uuid
= kzalloc(BTRFS_UUID_SIZE
, GFP_KERNEL
);
2382 args
->fsid
= kzalloc(BTRFS_FSID_SIZE
, GFP_KERNEL
);
2383 if (!args
->uuid
|| !args
->fsid
) {
2384 btrfs_put_dev_args_from_path(args
);
2388 ret
= btrfs_get_bdev_and_sb(path
, BLK_OPEN_READ
, NULL
, 0,
2389 &bdev_file
, &disk_super
);
2391 btrfs_put_dev_args_from_path(args
);
2395 args
->devid
= btrfs_stack_device_id(&disk_super
->dev_item
);
2396 memcpy(args
->uuid
, disk_super
->dev_item
.uuid
, BTRFS_UUID_SIZE
);
2397 if (btrfs_fs_incompat(fs_info
, METADATA_UUID
))
2398 memcpy(args
->fsid
, disk_super
->metadata_uuid
, BTRFS_FSID_SIZE
);
2400 memcpy(args
->fsid
, disk_super
->fsid
, BTRFS_FSID_SIZE
);
2401 btrfs_release_disk_super(disk_super
);
2407 * Only use this jointly with btrfs_get_dev_args_from_path() because we will
2408 * allocate our ->uuid and ->fsid pointers, everybody else uses local variables
2409 * that don't need to be freed.
2411 void btrfs_put_dev_args_from_path(struct btrfs_dev_lookup_args
*args
)
2419 struct btrfs_device
*btrfs_find_device_by_devspec(
2420 struct btrfs_fs_info
*fs_info
, u64 devid
,
2421 const char *device_path
)
2423 BTRFS_DEV_LOOKUP_ARGS(args
);
2424 struct btrfs_device
*device
;
2429 device
= btrfs_find_device(fs_info
->fs_devices
, &args
);
2431 return ERR_PTR(-ENOENT
);
2435 ret
= btrfs_get_dev_args_from_path(fs_info
, &args
, device_path
);
2437 return ERR_PTR(ret
);
2438 device
= btrfs_find_device(fs_info
->fs_devices
, &args
);
2439 btrfs_put_dev_args_from_path(&args
);
2441 return ERR_PTR(-ENOENT
);
2445 static struct btrfs_fs_devices
*btrfs_init_sprout(struct btrfs_fs_info
*fs_info
)
2447 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
2448 struct btrfs_fs_devices
*old_devices
;
2449 struct btrfs_fs_devices
*seed_devices
;
2451 lockdep_assert_held(&uuid_mutex
);
2452 if (!fs_devices
->seeding
)
2453 return ERR_PTR(-EINVAL
);
2456 * Private copy of the seed devices, anchored at
2457 * fs_info->fs_devices->seed_list
2459 seed_devices
= alloc_fs_devices(NULL
);
2460 if (IS_ERR(seed_devices
))
2461 return seed_devices
;
2464 * It's necessary to retain a copy of the original seed fs_devices in
2465 * fs_uuids so that filesystems which have been seeded can successfully
2466 * reference the seed device from open_seed_devices. This also supports
2469 old_devices
= clone_fs_devices(fs_devices
);
2470 if (IS_ERR(old_devices
)) {
2471 kfree(seed_devices
);
2475 list_add(&old_devices
->fs_list
, &fs_uuids
);
2477 memcpy(seed_devices
, fs_devices
, sizeof(*seed_devices
));
2478 seed_devices
->opened
= 1;
2479 INIT_LIST_HEAD(&seed_devices
->devices
);
2480 INIT_LIST_HEAD(&seed_devices
->alloc_list
);
2481 mutex_init(&seed_devices
->device_list_mutex
);
2483 return seed_devices
;
2487 * Splice seed devices into the sprout fs_devices.
2488 * Generate a new fsid for the sprouted read-write filesystem.
2490 static void btrfs_setup_sprout(struct btrfs_fs_info
*fs_info
,
2491 struct btrfs_fs_devices
*seed_devices
)
2493 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
2494 struct btrfs_super_block
*disk_super
= fs_info
->super_copy
;
2495 struct btrfs_device
*device
;
2499 * We are updating the fsid, the thread leading to device_list_add()
2500 * could race, so uuid_mutex is needed.
2502 lockdep_assert_held(&uuid_mutex
);
2505 * The threads listed below may traverse dev_list but can do that without
2506 * device_list_mutex:
2507 * - All device ops and balance - as we are in btrfs_exclop_start.
2508 * - Various dev_list readers - are using RCU.
2509 * - btrfs_ioctl_fitrim() - is using RCU.
2511 * For-read threads as below are using device_list_mutex:
2512 * - Readonly scrub btrfs_scrub_dev()
2513 * - Readonly scrub btrfs_scrub_progress()
2514 * - btrfs_get_dev_stats()
2516 lockdep_assert_held(&fs_devices
->device_list_mutex
);
2518 list_splice_init_rcu(&fs_devices
->devices
, &seed_devices
->devices
,
2520 list_for_each_entry(device
, &seed_devices
->devices
, dev_list
)
2521 device
->fs_devices
= seed_devices
;
2523 fs_devices
->seeding
= false;
2524 fs_devices
->num_devices
= 0;
2525 fs_devices
->open_devices
= 0;
2526 fs_devices
->missing_devices
= 0;
2527 fs_devices
->rotating
= false;
2528 list_add(&seed_devices
->seed_list
, &fs_devices
->seed_list
);
2530 generate_random_uuid(fs_devices
->fsid
);
2531 memcpy(fs_devices
->metadata_uuid
, fs_devices
->fsid
, BTRFS_FSID_SIZE
);
2532 memcpy(disk_super
->fsid
, fs_devices
->fsid
, BTRFS_FSID_SIZE
);
2534 super_flags
= btrfs_super_flags(disk_super
) &
2535 ~BTRFS_SUPER_FLAG_SEEDING
;
2536 btrfs_set_super_flags(disk_super
, super_flags
);
2540 * Store the expected generation for seed devices in device items.
2542 static int btrfs_finish_sprout(struct btrfs_trans_handle
*trans
)
2544 BTRFS_DEV_LOOKUP_ARGS(args
);
2545 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2546 struct btrfs_root
*root
= fs_info
->chunk_root
;
2547 struct btrfs_path
*path
;
2548 struct extent_buffer
*leaf
;
2549 struct btrfs_dev_item
*dev_item
;
2550 struct btrfs_device
*device
;
2551 struct btrfs_key key
;
2552 u8 fs_uuid
[BTRFS_FSID_SIZE
];
2553 u8 dev_uuid
[BTRFS_UUID_SIZE
];
2556 path
= btrfs_alloc_path();
2560 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
2562 key
.type
= BTRFS_DEV_ITEM_KEY
;
2565 btrfs_reserve_chunk_metadata(trans
, false);
2566 ret
= btrfs_search_slot(trans
, root
, &key
, path
, 0, 1);
2567 btrfs_trans_release_chunk_metadata(trans
);
2571 leaf
= path
->nodes
[0];
2573 if (path
->slots
[0] >= btrfs_header_nritems(leaf
)) {
2574 ret
= btrfs_next_leaf(root
, path
);
2579 leaf
= path
->nodes
[0];
2580 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
2581 btrfs_release_path(path
);
2585 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
2586 if (key
.objectid
!= BTRFS_DEV_ITEMS_OBJECTID
||
2587 key
.type
!= BTRFS_DEV_ITEM_KEY
)
2590 dev_item
= btrfs_item_ptr(leaf
, path
->slots
[0],
2591 struct btrfs_dev_item
);
2592 args
.devid
= btrfs_device_id(leaf
, dev_item
);
2593 read_extent_buffer(leaf
, dev_uuid
, btrfs_device_uuid(dev_item
),
2595 read_extent_buffer(leaf
, fs_uuid
, btrfs_device_fsid(dev_item
),
2597 args
.uuid
= dev_uuid
;
2598 args
.fsid
= fs_uuid
;
2599 device
= btrfs_find_device(fs_info
->fs_devices
, &args
);
2600 BUG_ON(!device
); /* Logic error */
2602 if (device
->fs_devices
->seeding
) {
2603 btrfs_set_device_generation(leaf
, dev_item
,
2604 device
->generation
);
2605 btrfs_mark_buffer_dirty(trans
, leaf
);
2613 btrfs_free_path(path
);
2617 int btrfs_init_new_device(struct btrfs_fs_info
*fs_info
, const char *device_path
)
2619 struct btrfs_root
*root
= fs_info
->dev_root
;
2620 struct btrfs_trans_handle
*trans
;
2621 struct btrfs_device
*device
;
2622 struct file
*bdev_file
;
2623 struct super_block
*sb
= fs_info
->sb
;
2624 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
2625 struct btrfs_fs_devices
*seed_devices
= NULL
;
2626 u64 orig_super_total_bytes
;
2627 u64 orig_super_num_devices
;
2629 bool seeding_dev
= false;
2630 bool locked
= false;
2632 if (sb_rdonly(sb
) && !fs_devices
->seeding
)
2635 bdev_file
= bdev_file_open_by_path(device_path
, BLK_OPEN_WRITE
,
2636 fs_info
->bdev_holder
, NULL
);
2637 if (IS_ERR(bdev_file
))
2638 return PTR_ERR(bdev_file
);
2640 if (!btrfs_check_device_zone_type(fs_info
, file_bdev(bdev_file
))) {
2645 if (fs_devices
->seeding
) {
2647 down_write(&sb
->s_umount
);
2648 mutex_lock(&uuid_mutex
);
2652 sync_blockdev(file_bdev(bdev_file
));
2655 list_for_each_entry_rcu(device
, &fs_devices
->devices
, dev_list
) {
2656 if (device
->bdev
== file_bdev(bdev_file
)) {
2664 device
= btrfs_alloc_device(fs_info
, NULL
, NULL
, device_path
);
2665 if (IS_ERR(device
)) {
2666 /* we can safely leave the fs_devices entry around */
2667 ret
= PTR_ERR(device
);
2671 device
->fs_info
= fs_info
;
2672 device
->bdev_file
= bdev_file
;
2673 device
->bdev
= file_bdev(bdev_file
);
2674 ret
= lookup_bdev(device_path
, &device
->devt
);
2676 goto error_free_device
;
2678 ret
= btrfs_get_dev_zone_info(device
, false);
2680 goto error_free_device
;
2682 trans
= btrfs_start_transaction(root
, 0);
2683 if (IS_ERR(trans
)) {
2684 ret
= PTR_ERR(trans
);
2685 goto error_free_zone
;
2688 set_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
2689 device
->generation
= trans
->transid
;
2690 device
->io_width
= fs_info
->sectorsize
;
2691 device
->io_align
= fs_info
->sectorsize
;
2692 device
->sector_size
= fs_info
->sectorsize
;
2693 device
->total_bytes
=
2694 round_down(bdev_nr_bytes(device
->bdev
), fs_info
->sectorsize
);
2695 device
->disk_total_bytes
= device
->total_bytes
;
2696 device
->commit_total_bytes
= device
->total_bytes
;
2697 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
);
2698 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
);
2699 device
->dev_stats_valid
= 1;
2700 set_blocksize(device
->bdev
, BTRFS_BDEV_BLOCKSIZE
);
2703 btrfs_clear_sb_rdonly(sb
);
2705 /* GFP_KERNEL allocation must not be under device_list_mutex */
2706 seed_devices
= btrfs_init_sprout(fs_info
);
2707 if (IS_ERR(seed_devices
)) {
2708 ret
= PTR_ERR(seed_devices
);
2709 btrfs_abort_transaction(trans
, ret
);
2714 mutex_lock(&fs_devices
->device_list_mutex
);
2716 btrfs_setup_sprout(fs_info
, seed_devices
);
2717 btrfs_assign_next_active_device(fs_info
->fs_devices
->latest_dev
,
2721 device
->fs_devices
= fs_devices
;
2723 mutex_lock(&fs_info
->chunk_mutex
);
2724 list_add_rcu(&device
->dev_list
, &fs_devices
->devices
);
2725 list_add(&device
->dev_alloc_list
, &fs_devices
->alloc_list
);
2726 fs_devices
->num_devices
++;
2727 fs_devices
->open_devices
++;
2728 fs_devices
->rw_devices
++;
2729 fs_devices
->total_devices
++;
2730 fs_devices
->total_rw_bytes
+= device
->total_bytes
;
2732 atomic64_add(device
->total_bytes
, &fs_info
->free_chunk_space
);
2734 if (!bdev_nonrot(device
->bdev
))
2735 fs_devices
->rotating
= true;
2737 orig_super_total_bytes
= btrfs_super_total_bytes(fs_info
->super_copy
);
2738 btrfs_set_super_total_bytes(fs_info
->super_copy
,
2739 round_down(orig_super_total_bytes
+ device
->total_bytes
,
2740 fs_info
->sectorsize
));
2742 orig_super_num_devices
= btrfs_super_num_devices(fs_info
->super_copy
);
2743 btrfs_set_super_num_devices(fs_info
->super_copy
,
2744 orig_super_num_devices
+ 1);
2747 * we've got more storage, clear any full flags on the space
2750 btrfs_clear_space_info_full(fs_info
);
2752 mutex_unlock(&fs_info
->chunk_mutex
);
2754 /* Add sysfs device entry */
2755 btrfs_sysfs_add_device(device
);
2757 mutex_unlock(&fs_devices
->device_list_mutex
);
2760 mutex_lock(&fs_info
->chunk_mutex
);
2761 ret
= init_first_rw_device(trans
);
2762 mutex_unlock(&fs_info
->chunk_mutex
);
2764 btrfs_abort_transaction(trans
, ret
);
2769 ret
= btrfs_add_dev_item(trans
, device
);
2771 btrfs_abort_transaction(trans
, ret
);
2776 ret
= btrfs_finish_sprout(trans
);
2778 btrfs_abort_transaction(trans
, ret
);
2783 * fs_devices now represents the newly sprouted filesystem and
2784 * its fsid has been changed by btrfs_sprout_splice().
2786 btrfs_sysfs_update_sprout_fsid(fs_devices
);
2789 ret
= btrfs_commit_transaction(trans
);
2792 mutex_unlock(&uuid_mutex
);
2793 up_write(&sb
->s_umount
);
2796 if (ret
) /* transaction commit */
2799 ret
= btrfs_relocate_sys_chunks(fs_info
);
2801 btrfs_handle_fs_error(fs_info
, ret
,
2802 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2803 trans
= btrfs_attach_transaction(root
);
2804 if (IS_ERR(trans
)) {
2805 if (PTR_ERR(trans
) == -ENOENT
)
2807 ret
= PTR_ERR(trans
);
2811 ret
= btrfs_commit_transaction(trans
);
2815 * Now that we have written a new super block to this device, check all
2816 * other fs_devices list if device_path alienates any other scanned
2818 * We can ignore the return value as it typically returns -EINVAL and
2819 * only succeeds if the device was an alien.
2821 btrfs_forget_devices(device
->devt
);
2823 /* Update ctime/mtime for blkid or udev */
2824 update_dev_time(device_path
);
2829 btrfs_sysfs_remove_device(device
);
2830 mutex_lock(&fs_info
->fs_devices
->device_list_mutex
);
2831 mutex_lock(&fs_info
->chunk_mutex
);
2832 list_del_rcu(&device
->dev_list
);
2833 list_del(&device
->dev_alloc_list
);
2834 fs_info
->fs_devices
->num_devices
--;
2835 fs_info
->fs_devices
->open_devices
--;
2836 fs_info
->fs_devices
->rw_devices
--;
2837 fs_info
->fs_devices
->total_devices
--;
2838 fs_info
->fs_devices
->total_rw_bytes
-= device
->total_bytes
;
2839 atomic64_sub(device
->total_bytes
, &fs_info
->free_chunk_space
);
2840 btrfs_set_super_total_bytes(fs_info
->super_copy
,
2841 orig_super_total_bytes
);
2842 btrfs_set_super_num_devices(fs_info
->super_copy
,
2843 orig_super_num_devices
);
2844 mutex_unlock(&fs_info
->chunk_mutex
);
2845 mutex_unlock(&fs_info
->fs_devices
->device_list_mutex
);
2848 btrfs_set_sb_rdonly(sb
);
2850 btrfs_end_transaction(trans
);
2852 btrfs_destroy_dev_zone_info(device
);
2854 btrfs_free_device(device
);
2858 mutex_unlock(&uuid_mutex
);
2859 up_write(&sb
->s_umount
);
2864 static noinline
int btrfs_update_device(struct btrfs_trans_handle
*trans
,
2865 struct btrfs_device
*device
)
2868 struct btrfs_path
*path
;
2869 struct btrfs_root
*root
= device
->fs_info
->chunk_root
;
2870 struct btrfs_dev_item
*dev_item
;
2871 struct extent_buffer
*leaf
;
2872 struct btrfs_key key
;
2874 path
= btrfs_alloc_path();
2878 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
2879 key
.type
= BTRFS_DEV_ITEM_KEY
;
2880 key
.offset
= device
->devid
;
2882 ret
= btrfs_search_slot(trans
, root
, &key
, path
, 0, 1);
2891 leaf
= path
->nodes
[0];
2892 dev_item
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_dev_item
);
2894 btrfs_set_device_id(leaf
, dev_item
, device
->devid
);
2895 btrfs_set_device_type(leaf
, dev_item
, device
->type
);
2896 btrfs_set_device_io_align(leaf
, dev_item
, device
->io_align
);
2897 btrfs_set_device_io_width(leaf
, dev_item
, device
->io_width
);
2898 btrfs_set_device_sector_size(leaf
, dev_item
, device
->sector_size
);
2899 btrfs_set_device_total_bytes(leaf
, dev_item
,
2900 btrfs_device_get_disk_total_bytes(device
));
2901 btrfs_set_device_bytes_used(leaf
, dev_item
,
2902 btrfs_device_get_bytes_used(device
));
2903 btrfs_mark_buffer_dirty(trans
, leaf
);
2906 btrfs_free_path(path
);
2910 int btrfs_grow_device(struct btrfs_trans_handle
*trans
,
2911 struct btrfs_device
*device
, u64 new_size
)
2913 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
2914 struct btrfs_super_block
*super_copy
= fs_info
->super_copy
;
2919 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
))
2922 new_size
= round_down(new_size
, fs_info
->sectorsize
);
2924 mutex_lock(&fs_info
->chunk_mutex
);
2925 old_total
= btrfs_super_total_bytes(super_copy
);
2926 diff
= round_down(new_size
- device
->total_bytes
, fs_info
->sectorsize
);
2928 if (new_size
<= device
->total_bytes
||
2929 test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
)) {
2930 mutex_unlock(&fs_info
->chunk_mutex
);
2934 btrfs_set_super_total_bytes(super_copy
,
2935 round_down(old_total
+ diff
, fs_info
->sectorsize
));
2936 device
->fs_devices
->total_rw_bytes
+= diff
;
2937 atomic64_add(diff
, &fs_info
->free_chunk_space
);
2939 btrfs_device_set_total_bytes(device
, new_size
);
2940 btrfs_device_set_disk_total_bytes(device
, new_size
);
2941 btrfs_clear_space_info_full(device
->fs_info
);
2942 if (list_empty(&device
->post_commit_list
))
2943 list_add_tail(&device
->post_commit_list
,
2944 &trans
->transaction
->dev_update_list
);
2945 mutex_unlock(&fs_info
->chunk_mutex
);
2947 btrfs_reserve_chunk_metadata(trans
, false);
2948 ret
= btrfs_update_device(trans
, device
);
2949 btrfs_trans_release_chunk_metadata(trans
);
2954 static int btrfs_free_chunk(struct btrfs_trans_handle
*trans
, u64 chunk_offset
)
2956 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2957 struct btrfs_root
*root
= fs_info
->chunk_root
;
2959 struct btrfs_path
*path
;
2960 struct btrfs_key key
;
2962 path
= btrfs_alloc_path();
2966 key
.objectid
= BTRFS_FIRST_CHUNK_TREE_OBJECTID
;
2967 key
.offset
= chunk_offset
;
2968 key
.type
= BTRFS_CHUNK_ITEM_KEY
;
2970 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
2973 else if (ret
> 0) { /* Logic error or corruption */
2974 btrfs_handle_fs_error(fs_info
, -ENOENT
,
2975 "Failed lookup while freeing chunk.");
2980 ret
= btrfs_del_item(trans
, root
, path
);
2982 btrfs_handle_fs_error(fs_info
, ret
,
2983 "Failed to delete chunk item.");
2985 btrfs_free_path(path
);
2989 static int btrfs_del_sys_chunk(struct btrfs_fs_info
*fs_info
, u64 chunk_offset
)
2991 struct btrfs_super_block
*super_copy
= fs_info
->super_copy
;
2992 struct btrfs_disk_key
*disk_key
;
2993 struct btrfs_chunk
*chunk
;
3000 struct btrfs_key key
;
3002 lockdep_assert_held(&fs_info
->chunk_mutex
);
3003 array_size
= btrfs_super_sys_array_size(super_copy
);
3005 ptr
= super_copy
->sys_chunk_array
;
3008 while (cur
< array_size
) {
3009 disk_key
= (struct btrfs_disk_key
*)ptr
;
3010 btrfs_disk_key_to_cpu(&key
, disk_key
);
3012 len
= sizeof(*disk_key
);
3014 if (key
.type
== BTRFS_CHUNK_ITEM_KEY
) {
3015 chunk
= (struct btrfs_chunk
*)(ptr
+ len
);
3016 num_stripes
= btrfs_stack_chunk_num_stripes(chunk
);
3017 len
+= btrfs_chunk_item_size(num_stripes
);
3022 if (key
.objectid
== BTRFS_FIRST_CHUNK_TREE_OBJECTID
&&
3023 key
.offset
== chunk_offset
) {
3024 memmove(ptr
, ptr
+ len
, array_size
- (cur
+ len
));
3026 btrfs_set_super_sys_array_size(super_copy
, array_size
);
3035 struct btrfs_chunk_map
*btrfs_find_chunk_map_nolock(struct btrfs_fs_info
*fs_info
,
3036 u64 logical
, u64 length
)
3038 struct rb_node
*node
= fs_info
->mapping_tree
.rb_root
.rb_node
;
3039 struct rb_node
*prev
= NULL
;
3040 struct rb_node
*orig_prev
;
3041 struct btrfs_chunk_map
*map
;
3042 struct btrfs_chunk_map
*prev_map
= NULL
;
3045 map
= rb_entry(node
, struct btrfs_chunk_map
, rb_node
);
3049 if (logical
< map
->start
) {
3050 node
= node
->rb_left
;
3051 } else if (logical
>= map
->start
+ map
->chunk_len
) {
3052 node
= node
->rb_right
;
3054 refcount_inc(&map
->refs
);
3063 while (prev
&& logical
>= prev_map
->start
+ prev_map
->chunk_len
) {
3064 prev
= rb_next(prev
);
3065 prev_map
= rb_entry(prev
, struct btrfs_chunk_map
, rb_node
);
3070 prev_map
= rb_entry(prev
, struct btrfs_chunk_map
, rb_node
);
3071 while (prev
&& logical
< prev_map
->start
) {
3072 prev
= rb_prev(prev
);
3073 prev_map
= rb_entry(prev
, struct btrfs_chunk_map
, rb_node
);
3078 u64 end
= logical
+ length
;
3081 * Caller can pass a U64_MAX length when it wants to get any
3082 * chunk starting at an offset of 'logical' or higher, so deal
3083 * with underflow by resetting the end offset to U64_MAX.
3088 if (end
> prev_map
->start
&&
3089 logical
< prev_map
->start
+ prev_map
->chunk_len
) {
3090 refcount_inc(&prev_map
->refs
);
3098 struct btrfs_chunk_map
*btrfs_find_chunk_map(struct btrfs_fs_info
*fs_info
,
3099 u64 logical
, u64 length
)
3101 struct btrfs_chunk_map
*map
;
3103 read_lock(&fs_info
->mapping_tree_lock
);
3104 map
= btrfs_find_chunk_map_nolock(fs_info
, logical
, length
);
3105 read_unlock(&fs_info
->mapping_tree_lock
);
3111 * Find the mapping containing the given logical extent.
3113 * @logical: Logical block offset in bytes.
3114 * @length: Length of extent in bytes.
3116 * Return: Chunk mapping or ERR_PTR.
3118 struct btrfs_chunk_map
*btrfs_get_chunk_map(struct btrfs_fs_info
*fs_info
,
3119 u64 logical
, u64 length
)
3121 struct btrfs_chunk_map
*map
;
3123 map
= btrfs_find_chunk_map(fs_info
, logical
, length
);
3125 if (unlikely(!map
)) {
3127 "unable to find chunk map for logical %llu length %llu",
3129 return ERR_PTR(-EINVAL
);
3132 if (unlikely(map
->start
> logical
|| map
->start
+ map
->chunk_len
<= logical
)) {
3134 "found a bad chunk map, wanted %llu-%llu, found %llu-%llu",
3135 logical
, logical
+ length
, map
->start
,
3136 map
->start
+ map
->chunk_len
);
3137 btrfs_free_chunk_map(map
);
3138 return ERR_PTR(-EINVAL
);
3141 /* Callers are responsible for dropping the reference. */
3145 static int remove_chunk_item(struct btrfs_trans_handle
*trans
,
3146 struct btrfs_chunk_map
*map
, u64 chunk_offset
)
3151 * Removing chunk items and updating the device items in the chunks btree
3152 * requires holding the chunk_mutex.
3153 * See the comment at btrfs_chunk_alloc() for the details.
3155 lockdep_assert_held(&trans
->fs_info
->chunk_mutex
);
3157 for (i
= 0; i
< map
->num_stripes
; i
++) {
3160 ret
= btrfs_update_device(trans
, map
->stripes
[i
].dev
);
3165 return btrfs_free_chunk(trans
, chunk_offset
);
3168 int btrfs_remove_chunk(struct btrfs_trans_handle
*trans
, u64 chunk_offset
)
3170 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
3171 struct btrfs_chunk_map
*map
;
3172 u64 dev_extent_len
= 0;
3174 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
3176 map
= btrfs_get_chunk_map(fs_info
, chunk_offset
, 1);
3179 * This is a logic error, but we don't want to just rely on the
3180 * user having built with ASSERT enabled, so if ASSERT doesn't
3181 * do anything we still error out.
3184 return PTR_ERR(map
);
3188 * First delete the device extent items from the devices btree.
3189 * We take the device_list_mutex to avoid racing with the finishing phase
3190 * of a device replace operation. See the comment below before acquiring
3191 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3192 * because that can result in a deadlock when deleting the device extent
3193 * items from the devices btree - COWing an extent buffer from the btree
3194 * may result in allocating a new metadata chunk, which would attempt to
3195 * lock again fs_info->chunk_mutex.
3197 mutex_lock(&fs_devices
->device_list_mutex
);
3198 for (i
= 0; i
< map
->num_stripes
; i
++) {
3199 struct btrfs_device
*device
= map
->stripes
[i
].dev
;
3200 ret
= btrfs_free_dev_extent(trans
, device
,
3201 map
->stripes
[i
].physical
,
3204 mutex_unlock(&fs_devices
->device_list_mutex
);
3205 btrfs_abort_transaction(trans
, ret
);
3209 if (device
->bytes_used
> 0) {
3210 mutex_lock(&fs_info
->chunk_mutex
);
3211 btrfs_device_set_bytes_used(device
,
3212 device
->bytes_used
- dev_extent_len
);
3213 atomic64_add(dev_extent_len
, &fs_info
->free_chunk_space
);
3214 btrfs_clear_space_info_full(fs_info
);
3215 mutex_unlock(&fs_info
->chunk_mutex
);
3218 mutex_unlock(&fs_devices
->device_list_mutex
);
3221 * We acquire fs_info->chunk_mutex for 2 reasons:
3223 * 1) Just like with the first phase of the chunk allocation, we must
3224 * reserve system space, do all chunk btree updates and deletions, and
3225 * update the system chunk array in the superblock while holding this
3226 * mutex. This is for similar reasons as explained on the comment at
3227 * the top of btrfs_chunk_alloc();
3229 * 2) Prevent races with the final phase of a device replace operation
3230 * that replaces the device object associated with the map's stripes,
3231 * because the device object's id can change at any time during that
3232 * final phase of the device replace operation
3233 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3234 * replaced device and then see it with an ID of
3235 * BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3236 * the device item, which does not exists on the chunk btree.
3237 * The finishing phase of device replace acquires both the
3238 * device_list_mutex and the chunk_mutex, in that order, so we are
3239 * safe by just acquiring the chunk_mutex.
3241 trans
->removing_chunk
= true;
3242 mutex_lock(&fs_info
->chunk_mutex
);
3244 check_system_chunk(trans
, map
->type
);
3246 ret
= remove_chunk_item(trans
, map
, chunk_offset
);
3248 * Normally we should not get -ENOSPC since we reserved space before
3249 * through the call to check_system_chunk().
3251 * Despite our system space_info having enough free space, we may not
3252 * be able to allocate extents from its block groups, because all have
3253 * an incompatible profile, which will force us to allocate a new system
3254 * block group with the right profile, or right after we called
3255 * check_system_space() above, a scrub turned the only system block group
3256 * with enough free space into RO mode.
3257 * This is explained with more detail at do_chunk_alloc().
3259 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3261 if (ret
== -ENOSPC
) {
3262 const u64 sys_flags
= btrfs_system_alloc_profile(fs_info
);
3263 struct btrfs_block_group
*sys_bg
;
3265 sys_bg
= btrfs_create_chunk(trans
, sys_flags
);
3266 if (IS_ERR(sys_bg
)) {
3267 ret
= PTR_ERR(sys_bg
);
3268 btrfs_abort_transaction(trans
, ret
);
3272 ret
= btrfs_chunk_alloc_add_chunk_item(trans
, sys_bg
);
3274 btrfs_abort_transaction(trans
, ret
);
3278 ret
= remove_chunk_item(trans
, map
, chunk_offset
);
3280 btrfs_abort_transaction(trans
, ret
);
3284 btrfs_abort_transaction(trans
, ret
);
3288 trace_btrfs_chunk_free(fs_info
, map
, chunk_offset
, map
->chunk_len
);
3290 if (map
->type
& BTRFS_BLOCK_GROUP_SYSTEM
) {
3291 ret
= btrfs_del_sys_chunk(fs_info
, chunk_offset
);
3293 btrfs_abort_transaction(trans
, ret
);
3298 mutex_unlock(&fs_info
->chunk_mutex
);
3299 trans
->removing_chunk
= false;
3302 * We are done with chunk btree updates and deletions, so release the
3303 * system space we previously reserved (with check_system_chunk()).
3305 btrfs_trans_release_chunk_metadata(trans
);
3307 ret
= btrfs_remove_block_group(trans
, map
);
3309 btrfs_abort_transaction(trans
, ret
);
3314 if (trans
->removing_chunk
) {
3315 mutex_unlock(&fs_info
->chunk_mutex
);
3316 trans
->removing_chunk
= false;
3319 btrfs_free_chunk_map(map
);
3323 int btrfs_relocate_chunk(struct btrfs_fs_info
*fs_info
, u64 chunk_offset
)
3325 struct btrfs_root
*root
= fs_info
->chunk_root
;
3326 struct btrfs_trans_handle
*trans
;
3327 struct btrfs_block_group
*block_group
;
3331 if (btrfs_fs_incompat(fs_info
, EXTENT_TREE_V2
)) {
3333 "relocate: not supported on extent tree v2 yet");
3338 * Prevent races with automatic removal of unused block groups.
3339 * After we relocate and before we remove the chunk with offset
3340 * chunk_offset, automatic removal of the block group can kick in,
3341 * resulting in a failure when calling btrfs_remove_chunk() below.
3343 * Make sure to acquire this mutex before doing a tree search (dev
3344 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3345 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3346 * we release the path used to search the chunk/dev tree and before
3347 * the current task acquires this mutex and calls us.
3349 lockdep_assert_held(&fs_info
->reclaim_bgs_lock
);
3351 /* step one, relocate all the extents inside this chunk */
3352 btrfs_scrub_pause(fs_info
);
3353 ret
= btrfs_relocate_block_group(fs_info
, chunk_offset
);
3354 btrfs_scrub_continue(fs_info
);
3357 * If we had a transaction abort, stop all running scrubs.
3358 * See transaction.c:cleanup_transaction() why we do it here.
3360 if (BTRFS_FS_ERROR(fs_info
))
3361 btrfs_scrub_cancel(fs_info
);
3365 block_group
= btrfs_lookup_block_group(fs_info
, chunk_offset
);
3368 btrfs_discard_cancel_work(&fs_info
->discard_ctl
, block_group
);
3369 length
= block_group
->length
;
3370 btrfs_put_block_group(block_group
);
3373 * On a zoned file system, discard the whole block group, this will
3374 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3375 * resetting the zone fails, don't treat it as a fatal problem from the
3376 * filesystem's point of view.
3378 if (btrfs_is_zoned(fs_info
)) {
3379 ret
= btrfs_discard_extent(fs_info
, chunk_offset
, length
, NULL
);
3382 "failed to reset zone %llu after relocation",
3386 trans
= btrfs_start_trans_remove_block_group(root
->fs_info
,
3388 if (IS_ERR(trans
)) {
3389 ret
= PTR_ERR(trans
);
3390 btrfs_handle_fs_error(root
->fs_info
, ret
, NULL
);
3395 * step two, delete the device extents and the
3396 * chunk tree entries
3398 ret
= btrfs_remove_chunk(trans
, chunk_offset
);
3399 btrfs_end_transaction(trans
);
3403 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info
*fs_info
)
3405 struct btrfs_root
*chunk_root
= fs_info
->chunk_root
;
3406 struct btrfs_path
*path
;
3407 struct extent_buffer
*leaf
;
3408 struct btrfs_chunk
*chunk
;
3409 struct btrfs_key key
;
3410 struct btrfs_key found_key
;
3412 bool retried
= false;
3416 path
= btrfs_alloc_path();
3421 key
.objectid
= BTRFS_FIRST_CHUNK_TREE_OBJECTID
;
3422 key
.offset
= (u64
)-1;
3423 key
.type
= BTRFS_CHUNK_ITEM_KEY
;
3426 mutex_lock(&fs_info
->reclaim_bgs_lock
);
3427 ret
= btrfs_search_slot(NULL
, chunk_root
, &key
, path
, 0, 0);
3429 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3434 * On the first search we would find chunk tree with
3435 * offset -1, which is not possible. On subsequent
3436 * loops this would find an existing item on an invalid
3437 * offset (one less than the previous one, wrong
3438 * alignment and size).
3444 ret
= btrfs_previous_item(chunk_root
, path
, key
.objectid
,
3447 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3453 leaf
= path
->nodes
[0];
3454 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
3456 chunk
= btrfs_item_ptr(leaf
, path
->slots
[0],
3457 struct btrfs_chunk
);
3458 chunk_type
= btrfs_chunk_type(leaf
, chunk
);
3459 btrfs_release_path(path
);
3461 if (chunk_type
& BTRFS_BLOCK_GROUP_SYSTEM
) {
3462 ret
= btrfs_relocate_chunk(fs_info
, found_key
.offset
);
3468 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3470 if (found_key
.offset
== 0)
3472 key
.offset
= found_key
.offset
- 1;
3475 if (failed
&& !retried
) {
3479 } else if (WARN_ON(failed
&& retried
)) {
3483 btrfs_free_path(path
);
3488 * return 1 : allocate a data chunk successfully,
3489 * return <0: errors during allocating a data chunk,
3490 * return 0 : no need to allocate a data chunk.
3492 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info
*fs_info
,
3495 struct btrfs_block_group
*cache
;
3499 cache
= btrfs_lookup_block_group(fs_info
, chunk_offset
);
3501 chunk_type
= cache
->flags
;
3502 btrfs_put_block_group(cache
);
3504 if (!(chunk_type
& BTRFS_BLOCK_GROUP_DATA
))
3507 spin_lock(&fs_info
->data_sinfo
->lock
);
3508 bytes_used
= fs_info
->data_sinfo
->bytes_used
;
3509 spin_unlock(&fs_info
->data_sinfo
->lock
);
3512 struct btrfs_trans_handle
*trans
;
3515 trans
= btrfs_join_transaction(fs_info
->tree_root
);
3517 return PTR_ERR(trans
);
3519 ret
= btrfs_force_chunk_alloc(trans
, BTRFS_BLOCK_GROUP_DATA
);
3520 btrfs_end_transaction(trans
);
3529 static void btrfs_disk_balance_args_to_cpu(struct btrfs_balance_args
*cpu
,
3530 const struct btrfs_disk_balance_args
*disk
)
3532 memset(cpu
, 0, sizeof(*cpu
));
3534 cpu
->profiles
= le64_to_cpu(disk
->profiles
);
3535 cpu
->usage
= le64_to_cpu(disk
->usage
);
3536 cpu
->devid
= le64_to_cpu(disk
->devid
);
3537 cpu
->pstart
= le64_to_cpu(disk
->pstart
);
3538 cpu
->pend
= le64_to_cpu(disk
->pend
);
3539 cpu
->vstart
= le64_to_cpu(disk
->vstart
);
3540 cpu
->vend
= le64_to_cpu(disk
->vend
);
3541 cpu
->target
= le64_to_cpu(disk
->target
);
3542 cpu
->flags
= le64_to_cpu(disk
->flags
);
3543 cpu
->limit
= le64_to_cpu(disk
->limit
);
3544 cpu
->stripes_min
= le32_to_cpu(disk
->stripes_min
);
3545 cpu
->stripes_max
= le32_to_cpu(disk
->stripes_max
);
3548 static void btrfs_cpu_balance_args_to_disk(struct btrfs_disk_balance_args
*disk
,
3549 const struct btrfs_balance_args
*cpu
)
3551 memset(disk
, 0, sizeof(*disk
));
3553 disk
->profiles
= cpu_to_le64(cpu
->profiles
);
3554 disk
->usage
= cpu_to_le64(cpu
->usage
);
3555 disk
->devid
= cpu_to_le64(cpu
->devid
);
3556 disk
->pstart
= cpu_to_le64(cpu
->pstart
);
3557 disk
->pend
= cpu_to_le64(cpu
->pend
);
3558 disk
->vstart
= cpu_to_le64(cpu
->vstart
);
3559 disk
->vend
= cpu_to_le64(cpu
->vend
);
3560 disk
->target
= cpu_to_le64(cpu
->target
);
3561 disk
->flags
= cpu_to_le64(cpu
->flags
);
3562 disk
->limit
= cpu_to_le64(cpu
->limit
);
3563 disk
->stripes_min
= cpu_to_le32(cpu
->stripes_min
);
3564 disk
->stripes_max
= cpu_to_le32(cpu
->stripes_max
);
3567 static int insert_balance_item(struct btrfs_fs_info
*fs_info
,
3568 struct btrfs_balance_control
*bctl
)
3570 struct btrfs_root
*root
= fs_info
->tree_root
;
3571 struct btrfs_trans_handle
*trans
;
3572 struct btrfs_balance_item
*item
;
3573 struct btrfs_disk_balance_args disk_bargs
;
3574 struct btrfs_path
*path
;
3575 struct extent_buffer
*leaf
;
3576 struct btrfs_key key
;
3579 path
= btrfs_alloc_path();
3583 trans
= btrfs_start_transaction(root
, 0);
3584 if (IS_ERR(trans
)) {
3585 btrfs_free_path(path
);
3586 return PTR_ERR(trans
);
3589 key
.objectid
= BTRFS_BALANCE_OBJECTID
;
3590 key
.type
= BTRFS_TEMPORARY_ITEM_KEY
;
3593 ret
= btrfs_insert_empty_item(trans
, root
, path
, &key
,
3598 leaf
= path
->nodes
[0];
3599 item
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_balance_item
);
3601 memzero_extent_buffer(leaf
, (unsigned long)item
, sizeof(*item
));
3603 btrfs_cpu_balance_args_to_disk(&disk_bargs
, &bctl
->data
);
3604 btrfs_set_balance_data(leaf
, item
, &disk_bargs
);
3605 btrfs_cpu_balance_args_to_disk(&disk_bargs
, &bctl
->meta
);
3606 btrfs_set_balance_meta(leaf
, item
, &disk_bargs
);
3607 btrfs_cpu_balance_args_to_disk(&disk_bargs
, &bctl
->sys
);
3608 btrfs_set_balance_sys(leaf
, item
, &disk_bargs
);
3610 btrfs_set_balance_flags(leaf
, item
, bctl
->flags
);
3612 btrfs_mark_buffer_dirty(trans
, leaf
);
3614 btrfs_free_path(path
);
3615 err
= btrfs_commit_transaction(trans
);
3621 static int del_balance_item(struct btrfs_fs_info
*fs_info
)
3623 struct btrfs_root
*root
= fs_info
->tree_root
;
3624 struct btrfs_trans_handle
*trans
;
3625 struct btrfs_path
*path
;
3626 struct btrfs_key key
;
3629 path
= btrfs_alloc_path();
3633 trans
= btrfs_start_transaction_fallback_global_rsv(root
, 0);
3634 if (IS_ERR(trans
)) {
3635 btrfs_free_path(path
);
3636 return PTR_ERR(trans
);
3639 key
.objectid
= BTRFS_BALANCE_OBJECTID
;
3640 key
.type
= BTRFS_TEMPORARY_ITEM_KEY
;
3643 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
3651 ret
= btrfs_del_item(trans
, root
, path
);
3653 btrfs_free_path(path
);
3654 err
= btrfs_commit_transaction(trans
);
3661 * This is a heuristic used to reduce the number of chunks balanced on
3662 * resume after balance was interrupted.
3664 static void update_balance_args(struct btrfs_balance_control
*bctl
)
3667 * Turn on soft mode for chunk types that were being converted.
3669 if (bctl
->data
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)
3670 bctl
->data
.flags
|= BTRFS_BALANCE_ARGS_SOFT
;
3671 if (bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)
3672 bctl
->sys
.flags
|= BTRFS_BALANCE_ARGS_SOFT
;
3673 if (bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)
3674 bctl
->meta
.flags
|= BTRFS_BALANCE_ARGS_SOFT
;
3677 * Turn on usage filter if is not already used. The idea is
3678 * that chunks that we have already balanced should be
3679 * reasonably full. Don't do it for chunks that are being
3680 * converted - that will keep us from relocating unconverted
3681 * (albeit full) chunks.
3683 if (!(bctl
->data
.flags
& BTRFS_BALANCE_ARGS_USAGE
) &&
3684 !(bctl
->data
.flags
& BTRFS_BALANCE_ARGS_USAGE_RANGE
) &&
3685 !(bctl
->data
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)) {
3686 bctl
->data
.flags
|= BTRFS_BALANCE_ARGS_USAGE
;
3687 bctl
->data
.usage
= 90;
3689 if (!(bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_USAGE
) &&
3690 !(bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_USAGE_RANGE
) &&
3691 !(bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)) {
3692 bctl
->sys
.flags
|= BTRFS_BALANCE_ARGS_USAGE
;
3693 bctl
->sys
.usage
= 90;
3695 if (!(bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_USAGE
) &&
3696 !(bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_USAGE_RANGE
) &&
3697 !(bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)) {
3698 bctl
->meta
.flags
|= BTRFS_BALANCE_ARGS_USAGE
;
3699 bctl
->meta
.usage
= 90;
3704 * Clear the balance status in fs_info and delete the balance item from disk.
3706 static void reset_balance_state(struct btrfs_fs_info
*fs_info
)
3708 struct btrfs_balance_control
*bctl
= fs_info
->balance_ctl
;
3711 ASSERT(fs_info
->balance_ctl
);
3713 spin_lock(&fs_info
->balance_lock
);
3714 fs_info
->balance_ctl
= NULL
;
3715 spin_unlock(&fs_info
->balance_lock
);
3718 ret
= del_balance_item(fs_info
);
3720 btrfs_handle_fs_error(fs_info
, ret
, NULL
);
3724 * Balance filters. Return 1 if chunk should be filtered out
3725 * (should not be balanced).
3727 static int chunk_profiles_filter(u64 chunk_type
,
3728 struct btrfs_balance_args
*bargs
)
3730 chunk_type
= chunk_to_extended(chunk_type
) &
3731 BTRFS_EXTENDED_PROFILE_MASK
;
3733 if (bargs
->profiles
& chunk_type
)
3739 static int chunk_usage_range_filter(struct btrfs_fs_info
*fs_info
, u64 chunk_offset
,
3740 struct btrfs_balance_args
*bargs
)
3742 struct btrfs_block_group
*cache
;
3744 u64 user_thresh_min
;
3745 u64 user_thresh_max
;
3748 cache
= btrfs_lookup_block_group(fs_info
, chunk_offset
);
3749 chunk_used
= cache
->used
;
3751 if (bargs
->usage_min
== 0)
3752 user_thresh_min
= 0;
3754 user_thresh_min
= mult_perc(cache
->length
, bargs
->usage_min
);
3756 if (bargs
->usage_max
== 0)
3757 user_thresh_max
= 1;
3758 else if (bargs
->usage_max
> 100)
3759 user_thresh_max
= cache
->length
;
3761 user_thresh_max
= mult_perc(cache
->length
, bargs
->usage_max
);
3763 if (user_thresh_min
<= chunk_used
&& chunk_used
< user_thresh_max
)
3766 btrfs_put_block_group(cache
);
3770 static int chunk_usage_filter(struct btrfs_fs_info
*fs_info
,
3771 u64 chunk_offset
, struct btrfs_balance_args
*bargs
)
3773 struct btrfs_block_group
*cache
;
3774 u64 chunk_used
, user_thresh
;
3777 cache
= btrfs_lookup_block_group(fs_info
, chunk_offset
);
3778 chunk_used
= cache
->used
;
3780 if (bargs
->usage_min
== 0)
3782 else if (bargs
->usage
> 100)
3783 user_thresh
= cache
->length
;
3785 user_thresh
= mult_perc(cache
->length
, bargs
->usage
);
3787 if (chunk_used
< user_thresh
)
3790 btrfs_put_block_group(cache
);
3794 static int chunk_devid_filter(struct extent_buffer
*leaf
,
3795 struct btrfs_chunk
*chunk
,
3796 struct btrfs_balance_args
*bargs
)
3798 struct btrfs_stripe
*stripe
;
3799 int num_stripes
= btrfs_chunk_num_stripes(leaf
, chunk
);
3802 for (i
= 0; i
< num_stripes
; i
++) {
3803 stripe
= btrfs_stripe_nr(chunk
, i
);
3804 if (btrfs_stripe_devid(leaf
, stripe
) == bargs
->devid
)
3811 static u64
calc_data_stripes(u64 type
, int num_stripes
)
3813 const int index
= btrfs_bg_flags_to_raid_index(type
);
3814 const int ncopies
= btrfs_raid_array
[index
].ncopies
;
3815 const int nparity
= btrfs_raid_array
[index
].nparity
;
3817 return (num_stripes
- nparity
) / ncopies
;
3820 /* [pstart, pend) */
3821 static int chunk_drange_filter(struct extent_buffer
*leaf
,
3822 struct btrfs_chunk
*chunk
,
3823 struct btrfs_balance_args
*bargs
)
3825 struct btrfs_stripe
*stripe
;
3826 int num_stripes
= btrfs_chunk_num_stripes(leaf
, chunk
);
3833 if (!(bargs
->flags
& BTRFS_BALANCE_ARGS_DEVID
))
3836 type
= btrfs_chunk_type(leaf
, chunk
);
3837 factor
= calc_data_stripes(type
, num_stripes
);
3839 for (i
= 0; i
< num_stripes
; i
++) {
3840 stripe
= btrfs_stripe_nr(chunk
, i
);
3841 if (btrfs_stripe_devid(leaf
, stripe
) != bargs
->devid
)
3844 stripe_offset
= btrfs_stripe_offset(leaf
, stripe
);
3845 stripe_length
= btrfs_chunk_length(leaf
, chunk
);
3846 stripe_length
= div_u64(stripe_length
, factor
);
3848 if (stripe_offset
< bargs
->pend
&&
3849 stripe_offset
+ stripe_length
> bargs
->pstart
)
3856 /* [vstart, vend) */
3857 static int chunk_vrange_filter(struct extent_buffer
*leaf
,
3858 struct btrfs_chunk
*chunk
,
3860 struct btrfs_balance_args
*bargs
)
3862 if (chunk_offset
< bargs
->vend
&&
3863 chunk_offset
+ btrfs_chunk_length(leaf
, chunk
) > bargs
->vstart
)
3864 /* at least part of the chunk is inside this vrange */
3870 static int chunk_stripes_range_filter(struct extent_buffer
*leaf
,
3871 struct btrfs_chunk
*chunk
,
3872 struct btrfs_balance_args
*bargs
)
3874 int num_stripes
= btrfs_chunk_num_stripes(leaf
, chunk
);
3876 if (bargs
->stripes_min
<= num_stripes
3877 && num_stripes
<= bargs
->stripes_max
)
3883 static int chunk_soft_convert_filter(u64 chunk_type
,
3884 struct btrfs_balance_args
*bargs
)
3886 if (!(bargs
->flags
& BTRFS_BALANCE_ARGS_CONVERT
))
3889 chunk_type
= chunk_to_extended(chunk_type
) &
3890 BTRFS_EXTENDED_PROFILE_MASK
;
3892 if (bargs
->target
== chunk_type
)
3898 static int should_balance_chunk(struct extent_buffer
*leaf
,
3899 struct btrfs_chunk
*chunk
, u64 chunk_offset
)
3901 struct btrfs_fs_info
*fs_info
= leaf
->fs_info
;
3902 struct btrfs_balance_control
*bctl
= fs_info
->balance_ctl
;
3903 struct btrfs_balance_args
*bargs
= NULL
;
3904 u64 chunk_type
= btrfs_chunk_type(leaf
, chunk
);
3907 if (!((chunk_type
& BTRFS_BLOCK_GROUP_TYPE_MASK
) &
3908 (bctl
->flags
& BTRFS_BALANCE_TYPE_MASK
))) {
3912 if (chunk_type
& BTRFS_BLOCK_GROUP_DATA
)
3913 bargs
= &bctl
->data
;
3914 else if (chunk_type
& BTRFS_BLOCK_GROUP_SYSTEM
)
3916 else if (chunk_type
& BTRFS_BLOCK_GROUP_METADATA
)
3917 bargs
= &bctl
->meta
;
3919 /* profiles filter */
3920 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_PROFILES
) &&
3921 chunk_profiles_filter(chunk_type
, bargs
)) {
3926 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_USAGE
) &&
3927 chunk_usage_filter(fs_info
, chunk_offset
, bargs
)) {
3929 } else if ((bargs
->flags
& BTRFS_BALANCE_ARGS_USAGE_RANGE
) &&
3930 chunk_usage_range_filter(fs_info
, chunk_offset
, bargs
)) {
3935 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_DEVID
) &&
3936 chunk_devid_filter(leaf
, chunk
, bargs
)) {
3940 /* drange filter, makes sense only with devid filter */
3941 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_DRANGE
) &&
3942 chunk_drange_filter(leaf
, chunk
, bargs
)) {
3947 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_VRANGE
) &&
3948 chunk_vrange_filter(leaf
, chunk
, chunk_offset
, bargs
)) {
3952 /* stripes filter */
3953 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_STRIPES_RANGE
) &&
3954 chunk_stripes_range_filter(leaf
, chunk
, bargs
)) {
3958 /* soft profile changing mode */
3959 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_SOFT
) &&
3960 chunk_soft_convert_filter(chunk_type
, bargs
)) {
3965 * limited by count, must be the last filter
3967 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_LIMIT
)) {
3968 if (bargs
->limit
== 0)
3972 } else if ((bargs
->flags
& BTRFS_BALANCE_ARGS_LIMIT_RANGE
)) {
3974 * Same logic as the 'limit' filter; the minimum cannot be
3975 * determined here because we do not have the global information
3976 * about the count of all chunks that satisfy the filters.
3978 if (bargs
->limit_max
== 0)
3987 static int __btrfs_balance(struct btrfs_fs_info
*fs_info
)
3989 struct btrfs_balance_control
*bctl
= fs_info
->balance_ctl
;
3990 struct btrfs_root
*chunk_root
= fs_info
->chunk_root
;
3992 struct btrfs_chunk
*chunk
;
3993 struct btrfs_path
*path
= NULL
;
3994 struct btrfs_key key
;
3995 struct btrfs_key found_key
;
3996 struct extent_buffer
*leaf
;
3999 int enospc_errors
= 0;
4000 bool counting
= true;
4001 /* The single value limit and min/max limits use the same bytes in the */
4002 u64 limit_data
= bctl
->data
.limit
;
4003 u64 limit_meta
= bctl
->meta
.limit
;
4004 u64 limit_sys
= bctl
->sys
.limit
;
4008 int chunk_reserved
= 0;
4010 path
= btrfs_alloc_path();
4016 /* zero out stat counters */
4017 spin_lock(&fs_info
->balance_lock
);
4018 memset(&bctl
->stat
, 0, sizeof(bctl
->stat
));
4019 spin_unlock(&fs_info
->balance_lock
);
4023 * The single value limit and min/max limits use the same bytes
4026 bctl
->data
.limit
= limit_data
;
4027 bctl
->meta
.limit
= limit_meta
;
4028 bctl
->sys
.limit
= limit_sys
;
4030 key
.objectid
= BTRFS_FIRST_CHUNK_TREE_OBJECTID
;
4031 key
.offset
= (u64
)-1;
4032 key
.type
= BTRFS_CHUNK_ITEM_KEY
;
4035 if ((!counting
&& atomic_read(&fs_info
->balance_pause_req
)) ||
4036 atomic_read(&fs_info
->balance_cancel_req
)) {
4041 mutex_lock(&fs_info
->reclaim_bgs_lock
);
4042 ret
= btrfs_search_slot(NULL
, chunk_root
, &key
, path
, 0, 0);
4044 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4049 * this shouldn't happen, it means the last relocate
4053 BUG(); /* FIXME break ? */
4055 ret
= btrfs_previous_item(chunk_root
, path
, 0,
4056 BTRFS_CHUNK_ITEM_KEY
);
4058 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4063 leaf
= path
->nodes
[0];
4064 slot
= path
->slots
[0];
4065 btrfs_item_key_to_cpu(leaf
, &found_key
, slot
);
4067 if (found_key
.objectid
!= key
.objectid
) {
4068 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4072 chunk
= btrfs_item_ptr(leaf
, slot
, struct btrfs_chunk
);
4073 chunk_type
= btrfs_chunk_type(leaf
, chunk
);
4076 spin_lock(&fs_info
->balance_lock
);
4077 bctl
->stat
.considered
++;
4078 spin_unlock(&fs_info
->balance_lock
);
4081 ret
= should_balance_chunk(leaf
, chunk
, found_key
.offset
);
4083 btrfs_release_path(path
);
4085 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4090 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4091 spin_lock(&fs_info
->balance_lock
);
4092 bctl
->stat
.expected
++;
4093 spin_unlock(&fs_info
->balance_lock
);
4095 if (chunk_type
& BTRFS_BLOCK_GROUP_DATA
)
4097 else if (chunk_type
& BTRFS_BLOCK_GROUP_SYSTEM
)
4099 else if (chunk_type
& BTRFS_BLOCK_GROUP_METADATA
)
4106 * Apply limit_min filter, no need to check if the LIMITS
4107 * filter is used, limit_min is 0 by default
4109 if (((chunk_type
& BTRFS_BLOCK_GROUP_DATA
) &&
4110 count_data
< bctl
->data
.limit_min
)
4111 || ((chunk_type
& BTRFS_BLOCK_GROUP_METADATA
) &&
4112 count_meta
< bctl
->meta
.limit_min
)
4113 || ((chunk_type
& BTRFS_BLOCK_GROUP_SYSTEM
) &&
4114 count_sys
< bctl
->sys
.limit_min
)) {
4115 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4119 if (!chunk_reserved
) {
4121 * We may be relocating the only data chunk we have,
4122 * which could potentially end up with losing data's
4123 * raid profile, so lets allocate an empty one in
4126 ret
= btrfs_may_alloc_data_chunk(fs_info
,
4129 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4131 } else if (ret
== 1) {
4136 ret
= btrfs_relocate_chunk(fs_info
, found_key
.offset
);
4137 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4138 if (ret
== -ENOSPC
) {
4140 } else if (ret
== -ETXTBSY
) {
4142 "skipping relocation of block group %llu due to active swapfile",
4148 spin_lock(&fs_info
->balance_lock
);
4149 bctl
->stat
.completed
++;
4150 spin_unlock(&fs_info
->balance_lock
);
4153 if (found_key
.offset
== 0)
4155 key
.offset
= found_key
.offset
- 1;
4159 btrfs_release_path(path
);
4164 btrfs_free_path(path
);
4165 if (enospc_errors
) {
4166 btrfs_info(fs_info
, "%d enospc errors during balance",
4176 * See if a given profile is valid and reduced.
4178 * @flags: profile to validate
4179 * @extended: if true @flags is treated as an extended profile
4181 static int alloc_profile_is_valid(u64 flags
, int extended
)
4183 u64 mask
= (extended
? BTRFS_EXTENDED_PROFILE_MASK
:
4184 BTRFS_BLOCK_GROUP_PROFILE_MASK
);
4186 flags
&= ~BTRFS_BLOCK_GROUP_TYPE_MASK
;
4188 /* 1) check that all other bits are zeroed */
4192 /* 2) see if profile is reduced */
4194 return !extended
; /* "0" is valid for usual profiles */
4196 return has_single_bit_set(flags
);
4200 * Validate target profile against allowed profiles and return true if it's OK.
4201 * Otherwise print the error message and return false.
4203 static inline int validate_convert_profile(struct btrfs_fs_info
*fs_info
,
4204 const struct btrfs_balance_args
*bargs
,
4205 u64 allowed
, const char *type
)
4207 if (!(bargs
->flags
& BTRFS_BALANCE_ARGS_CONVERT
))
4210 /* Profile is valid and does not have bits outside of the allowed set */
4211 if (alloc_profile_is_valid(bargs
->target
, 1) &&
4212 (bargs
->target
& ~allowed
) == 0)
4215 btrfs_err(fs_info
, "balance: invalid convert %s profile %s",
4216 type
, btrfs_bg_type_to_raid_name(bargs
->target
));
4221 * Fill @buf with textual description of balance filter flags @bargs, up to
4222 * @size_buf including the terminating null. The output may be trimmed if it
4223 * does not fit into the provided buffer.
4225 static void describe_balance_args(struct btrfs_balance_args
*bargs
, char *buf
,
4229 u32 size_bp
= size_buf
;
4231 u64 flags
= bargs
->flags
;
4232 char tmp_buf
[128] = {'\0'};
4237 #define CHECK_APPEND_NOARG(a) \
4239 ret = snprintf(bp, size_bp, (a)); \
4240 if (ret < 0 || ret >= size_bp) \
4241 goto out_overflow; \
4246 #define CHECK_APPEND_1ARG(a, v1) \
4248 ret = snprintf(bp, size_bp, (a), (v1)); \
4249 if (ret < 0 || ret >= size_bp) \
4250 goto out_overflow; \
4255 #define CHECK_APPEND_2ARG(a, v1, v2) \
4257 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
4258 if (ret < 0 || ret >= size_bp) \
4259 goto out_overflow; \
4264 if (flags
& BTRFS_BALANCE_ARGS_CONVERT
)
4265 CHECK_APPEND_1ARG("convert=%s,",
4266 btrfs_bg_type_to_raid_name(bargs
->target
));
4268 if (flags
& BTRFS_BALANCE_ARGS_SOFT
)
4269 CHECK_APPEND_NOARG("soft,");
4271 if (flags
& BTRFS_BALANCE_ARGS_PROFILES
) {
4272 btrfs_describe_block_groups(bargs
->profiles
, tmp_buf
,
4274 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf
);
4277 if (flags
& BTRFS_BALANCE_ARGS_USAGE
)
4278 CHECK_APPEND_1ARG("usage=%llu,", bargs
->usage
);
4280 if (flags
& BTRFS_BALANCE_ARGS_USAGE_RANGE
)
4281 CHECK_APPEND_2ARG("usage=%u..%u,",
4282 bargs
->usage_min
, bargs
->usage_max
);
4284 if (flags
& BTRFS_BALANCE_ARGS_DEVID
)
4285 CHECK_APPEND_1ARG("devid=%llu,", bargs
->devid
);
4287 if (flags
& BTRFS_BALANCE_ARGS_DRANGE
)
4288 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4289 bargs
->pstart
, bargs
->pend
);
4291 if (flags
& BTRFS_BALANCE_ARGS_VRANGE
)
4292 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4293 bargs
->vstart
, bargs
->vend
);
4295 if (flags
& BTRFS_BALANCE_ARGS_LIMIT
)
4296 CHECK_APPEND_1ARG("limit=%llu,", bargs
->limit
);
4298 if (flags
& BTRFS_BALANCE_ARGS_LIMIT_RANGE
)
4299 CHECK_APPEND_2ARG("limit=%u..%u,",
4300 bargs
->limit_min
, bargs
->limit_max
);
4302 if (flags
& BTRFS_BALANCE_ARGS_STRIPES_RANGE
)
4303 CHECK_APPEND_2ARG("stripes=%u..%u,",
4304 bargs
->stripes_min
, bargs
->stripes_max
);
4306 #undef CHECK_APPEND_2ARG
4307 #undef CHECK_APPEND_1ARG
4308 #undef CHECK_APPEND_NOARG
4312 if (size_bp
< size_buf
)
4313 buf
[size_buf
- size_bp
- 1] = '\0'; /* remove last , */
4318 static void describe_balance_start_or_resume(struct btrfs_fs_info
*fs_info
)
4320 u32 size_buf
= 1024;
4321 char tmp_buf
[192] = {'\0'};
4324 u32 size_bp
= size_buf
;
4326 struct btrfs_balance_control
*bctl
= fs_info
->balance_ctl
;
4328 buf
= kzalloc(size_buf
, GFP_KERNEL
);
4334 #define CHECK_APPEND_1ARG(a, v1) \
4336 ret = snprintf(bp, size_bp, (a), (v1)); \
4337 if (ret < 0 || ret >= size_bp) \
4338 goto out_overflow; \
4343 if (bctl
->flags
& BTRFS_BALANCE_FORCE
)
4344 CHECK_APPEND_1ARG("%s", "-f ");
4346 if (bctl
->flags
& BTRFS_BALANCE_DATA
) {
4347 describe_balance_args(&bctl
->data
, tmp_buf
, sizeof(tmp_buf
));
4348 CHECK_APPEND_1ARG("-d%s ", tmp_buf
);
4351 if (bctl
->flags
& BTRFS_BALANCE_METADATA
) {
4352 describe_balance_args(&bctl
->meta
, tmp_buf
, sizeof(tmp_buf
));
4353 CHECK_APPEND_1ARG("-m%s ", tmp_buf
);
4356 if (bctl
->flags
& BTRFS_BALANCE_SYSTEM
) {
4357 describe_balance_args(&bctl
->sys
, tmp_buf
, sizeof(tmp_buf
));
4358 CHECK_APPEND_1ARG("-s%s ", tmp_buf
);
4361 #undef CHECK_APPEND_1ARG
4365 if (size_bp
< size_buf
)
4366 buf
[size_buf
- size_bp
- 1] = '\0'; /* remove last " " */
4367 btrfs_info(fs_info
, "balance: %s %s",
4368 (bctl
->flags
& BTRFS_BALANCE_RESUME
) ?
4369 "resume" : "start", buf
);
4375 * Should be called with balance mutexe held
4377 int btrfs_balance(struct btrfs_fs_info
*fs_info
,
4378 struct btrfs_balance_control
*bctl
,
4379 struct btrfs_ioctl_balance_args
*bargs
)
4381 u64 meta_target
, data_target
;
4387 bool reducing_redundancy
;
4388 bool paused
= false;
4391 if (btrfs_fs_closing(fs_info
) ||
4392 atomic_read(&fs_info
->balance_pause_req
) ||
4393 btrfs_should_cancel_balance(fs_info
)) {
4398 allowed
= btrfs_super_incompat_flags(fs_info
->super_copy
);
4399 if (allowed
& BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS
)
4403 * In case of mixed groups both data and meta should be picked,
4404 * and identical options should be given for both of them.
4406 allowed
= BTRFS_BALANCE_DATA
| BTRFS_BALANCE_METADATA
;
4407 if (mixed
&& (bctl
->flags
& allowed
)) {
4408 if (!(bctl
->flags
& BTRFS_BALANCE_DATA
) ||
4409 !(bctl
->flags
& BTRFS_BALANCE_METADATA
) ||
4410 memcmp(&bctl
->data
, &bctl
->meta
, sizeof(bctl
->data
))) {
4412 "balance: mixed groups data and metadata options must be the same");
4419 * rw_devices will not change at the moment, device add/delete/replace
4422 num_devices
= fs_info
->fs_devices
->rw_devices
;
4425 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4426 * special bit for it, to make it easier to distinguish. Thus we need
4427 * to set it manually, or balance would refuse the profile.
4429 allowed
= BTRFS_AVAIL_ALLOC_BIT_SINGLE
;
4430 for (i
= 0; i
< ARRAY_SIZE(btrfs_raid_array
); i
++)
4431 if (num_devices
>= btrfs_raid_array
[i
].devs_min
)
4432 allowed
|= btrfs_raid_array
[i
].bg_flag
;
4434 if (!validate_convert_profile(fs_info
, &bctl
->data
, allowed
, "data") ||
4435 !validate_convert_profile(fs_info
, &bctl
->meta
, allowed
, "metadata") ||
4436 !validate_convert_profile(fs_info
, &bctl
->sys
, allowed
, "system")) {
4442 * Allow to reduce metadata or system integrity only if force set for
4443 * profiles with redundancy (copies, parity)
4446 for (i
= 0; i
< ARRAY_SIZE(btrfs_raid_array
); i
++) {
4447 if (btrfs_raid_array
[i
].ncopies
>= 2 ||
4448 btrfs_raid_array
[i
].tolerated_failures
>= 1)
4449 allowed
|= btrfs_raid_array
[i
].bg_flag
;
4452 seq
= read_seqbegin(&fs_info
->profiles_lock
);
4454 if (((bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) &&
4455 (fs_info
->avail_system_alloc_bits
& allowed
) &&
4456 !(bctl
->sys
.target
& allowed
)) ||
4457 ((bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) &&
4458 (fs_info
->avail_metadata_alloc_bits
& allowed
) &&
4459 !(bctl
->meta
.target
& allowed
)))
4460 reducing_redundancy
= true;
4462 reducing_redundancy
= false;
4464 /* if we're not converting, the target field is uninitialized */
4465 meta_target
= (bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) ?
4466 bctl
->meta
.target
: fs_info
->avail_metadata_alloc_bits
;
4467 data_target
= (bctl
->data
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) ?
4468 bctl
->data
.target
: fs_info
->avail_data_alloc_bits
;
4469 } while (read_seqretry(&fs_info
->profiles_lock
, seq
));
4471 if (reducing_redundancy
) {
4472 if (bctl
->flags
& BTRFS_BALANCE_FORCE
) {
4474 "balance: force reducing metadata redundancy");
4477 "balance: reduces metadata redundancy, use --force if you want this");
4483 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target
) <
4484 btrfs_get_num_tolerated_disk_barrier_failures(data_target
)) {
4486 "balance: metadata profile %s has lower redundancy than data profile %s",
4487 btrfs_bg_type_to_raid_name(meta_target
),
4488 btrfs_bg_type_to_raid_name(data_target
));
4491 ret
= insert_balance_item(fs_info
, bctl
);
4492 if (ret
&& ret
!= -EEXIST
)
4495 if (!(bctl
->flags
& BTRFS_BALANCE_RESUME
)) {
4496 BUG_ON(ret
== -EEXIST
);
4497 BUG_ON(fs_info
->balance_ctl
);
4498 spin_lock(&fs_info
->balance_lock
);
4499 fs_info
->balance_ctl
= bctl
;
4500 spin_unlock(&fs_info
->balance_lock
);
4502 BUG_ON(ret
!= -EEXIST
);
4503 spin_lock(&fs_info
->balance_lock
);
4504 update_balance_args(bctl
);
4505 spin_unlock(&fs_info
->balance_lock
);
4508 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
));
4509 set_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
);
4510 describe_balance_start_or_resume(fs_info
);
4511 mutex_unlock(&fs_info
->balance_mutex
);
4513 ret
= __btrfs_balance(fs_info
);
4515 mutex_lock(&fs_info
->balance_mutex
);
4516 if (ret
== -ECANCELED
&& atomic_read(&fs_info
->balance_pause_req
)) {
4517 btrfs_info(fs_info
, "balance: paused");
4518 btrfs_exclop_balance(fs_info
, BTRFS_EXCLOP_BALANCE_PAUSED
);
4522 * Balance can be canceled by:
4524 * - Regular cancel request
4525 * Then ret == -ECANCELED and balance_cancel_req > 0
4527 * - Fatal signal to "btrfs" process
4528 * Either the signal caught by wait_reserve_ticket() and callers
4529 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4531 * Either way, in this case balance_cancel_req = 0, and
4532 * ret == -EINTR or ret == -ECANCELED.
4534 * So here we only check the return value to catch canceled balance.
4536 else if (ret
== -ECANCELED
|| ret
== -EINTR
)
4537 btrfs_info(fs_info
, "balance: canceled");
4539 btrfs_info(fs_info
, "balance: ended with status: %d", ret
);
4541 clear_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
);
4544 memset(bargs
, 0, sizeof(*bargs
));
4545 btrfs_update_ioctl_balance_args(fs_info
, bargs
);
4548 /* We didn't pause, we can clean everything up. */
4550 reset_balance_state(fs_info
);
4551 btrfs_exclop_finish(fs_info
);
4554 wake_up(&fs_info
->balance_wait_q
);
4558 if (bctl
->flags
& BTRFS_BALANCE_RESUME
)
4559 reset_balance_state(fs_info
);
4562 btrfs_exclop_finish(fs_info
);
4567 static int balance_kthread(void *data
)
4569 struct btrfs_fs_info
*fs_info
= data
;
4572 sb_start_write(fs_info
->sb
);
4573 mutex_lock(&fs_info
->balance_mutex
);
4574 if (fs_info
->balance_ctl
)
4575 ret
= btrfs_balance(fs_info
, fs_info
->balance_ctl
, NULL
);
4576 mutex_unlock(&fs_info
->balance_mutex
);
4577 sb_end_write(fs_info
->sb
);
4582 int btrfs_resume_balance_async(struct btrfs_fs_info
*fs_info
)
4584 struct task_struct
*tsk
;
4586 mutex_lock(&fs_info
->balance_mutex
);
4587 if (!fs_info
->balance_ctl
) {
4588 mutex_unlock(&fs_info
->balance_mutex
);
4591 mutex_unlock(&fs_info
->balance_mutex
);
4593 if (btrfs_test_opt(fs_info
, SKIP_BALANCE
)) {
4594 btrfs_info(fs_info
, "balance: resume skipped");
4598 spin_lock(&fs_info
->super_lock
);
4599 ASSERT(fs_info
->exclusive_operation
== BTRFS_EXCLOP_BALANCE_PAUSED
);
4600 fs_info
->exclusive_operation
= BTRFS_EXCLOP_BALANCE
;
4601 spin_unlock(&fs_info
->super_lock
);
4603 * A ro->rw remount sequence should continue with the paused balance
4604 * regardless of who pauses it, system or the user as of now, so set
4607 spin_lock(&fs_info
->balance_lock
);
4608 fs_info
->balance_ctl
->flags
|= BTRFS_BALANCE_RESUME
;
4609 spin_unlock(&fs_info
->balance_lock
);
4611 tsk
= kthread_run(balance_kthread
, fs_info
, "btrfs-balance");
4612 return PTR_ERR_OR_ZERO(tsk
);
4615 int btrfs_recover_balance(struct btrfs_fs_info
*fs_info
)
4617 struct btrfs_balance_control
*bctl
;
4618 struct btrfs_balance_item
*item
;
4619 struct btrfs_disk_balance_args disk_bargs
;
4620 struct btrfs_path
*path
;
4621 struct extent_buffer
*leaf
;
4622 struct btrfs_key key
;
4625 path
= btrfs_alloc_path();
4629 key
.objectid
= BTRFS_BALANCE_OBJECTID
;
4630 key
.type
= BTRFS_TEMPORARY_ITEM_KEY
;
4633 ret
= btrfs_search_slot(NULL
, fs_info
->tree_root
, &key
, path
, 0, 0);
4636 if (ret
> 0) { /* ret = -ENOENT; */
4641 bctl
= kzalloc(sizeof(*bctl
), GFP_NOFS
);
4647 leaf
= path
->nodes
[0];
4648 item
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_balance_item
);
4650 bctl
->flags
= btrfs_balance_flags(leaf
, item
);
4651 bctl
->flags
|= BTRFS_BALANCE_RESUME
;
4653 btrfs_balance_data(leaf
, item
, &disk_bargs
);
4654 btrfs_disk_balance_args_to_cpu(&bctl
->data
, &disk_bargs
);
4655 btrfs_balance_meta(leaf
, item
, &disk_bargs
);
4656 btrfs_disk_balance_args_to_cpu(&bctl
->meta
, &disk_bargs
);
4657 btrfs_balance_sys(leaf
, item
, &disk_bargs
);
4658 btrfs_disk_balance_args_to_cpu(&bctl
->sys
, &disk_bargs
);
4661 * This should never happen, as the paused balance state is recovered
4662 * during mount without any chance of other exclusive ops to collide.
4664 * This gives the exclusive op status to balance and keeps in paused
4665 * state until user intervention (cancel or umount). If the ownership
4666 * cannot be assigned, show a message but do not fail. The balance
4667 * is in a paused state and must have fs_info::balance_ctl properly
4670 if (!btrfs_exclop_start(fs_info
, BTRFS_EXCLOP_BALANCE_PAUSED
))
4672 "balance: cannot set exclusive op status, resume manually");
4674 btrfs_release_path(path
);
4676 mutex_lock(&fs_info
->balance_mutex
);
4677 BUG_ON(fs_info
->balance_ctl
);
4678 spin_lock(&fs_info
->balance_lock
);
4679 fs_info
->balance_ctl
= bctl
;
4680 spin_unlock(&fs_info
->balance_lock
);
4681 mutex_unlock(&fs_info
->balance_mutex
);
4683 btrfs_free_path(path
);
4687 int btrfs_pause_balance(struct btrfs_fs_info
*fs_info
)
4691 mutex_lock(&fs_info
->balance_mutex
);
4692 if (!fs_info
->balance_ctl
) {
4693 mutex_unlock(&fs_info
->balance_mutex
);
4697 if (test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
)) {
4698 atomic_inc(&fs_info
->balance_pause_req
);
4699 mutex_unlock(&fs_info
->balance_mutex
);
4701 wait_event(fs_info
->balance_wait_q
,
4702 !test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
));
4704 mutex_lock(&fs_info
->balance_mutex
);
4705 /* we are good with balance_ctl ripped off from under us */
4706 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
));
4707 atomic_dec(&fs_info
->balance_pause_req
);
4712 mutex_unlock(&fs_info
->balance_mutex
);
4716 int btrfs_cancel_balance(struct btrfs_fs_info
*fs_info
)
4718 mutex_lock(&fs_info
->balance_mutex
);
4719 if (!fs_info
->balance_ctl
) {
4720 mutex_unlock(&fs_info
->balance_mutex
);
4725 * A paused balance with the item stored on disk can be resumed at
4726 * mount time if the mount is read-write. Otherwise it's still paused
4727 * and we must not allow cancelling as it deletes the item.
4729 if (sb_rdonly(fs_info
->sb
)) {
4730 mutex_unlock(&fs_info
->balance_mutex
);
4734 atomic_inc(&fs_info
->balance_cancel_req
);
4736 * if we are running just wait and return, balance item is
4737 * deleted in btrfs_balance in this case
4739 if (test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
)) {
4740 mutex_unlock(&fs_info
->balance_mutex
);
4741 wait_event(fs_info
->balance_wait_q
,
4742 !test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
));
4743 mutex_lock(&fs_info
->balance_mutex
);
4745 mutex_unlock(&fs_info
->balance_mutex
);
4747 * Lock released to allow other waiters to continue, we'll
4748 * reexamine the status again.
4750 mutex_lock(&fs_info
->balance_mutex
);
4752 if (fs_info
->balance_ctl
) {
4753 reset_balance_state(fs_info
);
4754 btrfs_exclop_finish(fs_info
);
4755 btrfs_info(fs_info
, "balance: canceled");
4759 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
));
4760 atomic_dec(&fs_info
->balance_cancel_req
);
4761 mutex_unlock(&fs_info
->balance_mutex
);
4765 int btrfs_uuid_scan_kthread(void *data
)
4767 struct btrfs_fs_info
*fs_info
= data
;
4768 struct btrfs_root
*root
= fs_info
->tree_root
;
4769 struct btrfs_key key
;
4770 struct btrfs_path
*path
= NULL
;
4772 struct extent_buffer
*eb
;
4774 struct btrfs_root_item root_item
;
4776 struct btrfs_trans_handle
*trans
= NULL
;
4777 bool closing
= false;
4779 path
= btrfs_alloc_path();
4786 key
.type
= BTRFS_ROOT_ITEM_KEY
;
4790 if (btrfs_fs_closing(fs_info
)) {
4794 ret
= btrfs_search_forward(root
, &key
, path
,
4795 BTRFS_OLDEST_GENERATION
);
4802 if (key
.type
!= BTRFS_ROOT_ITEM_KEY
||
4803 (key
.objectid
< BTRFS_FIRST_FREE_OBJECTID
&&
4804 key
.objectid
!= BTRFS_FS_TREE_OBJECTID
) ||
4805 key
.objectid
> BTRFS_LAST_FREE_OBJECTID
)
4808 eb
= path
->nodes
[0];
4809 slot
= path
->slots
[0];
4810 item_size
= btrfs_item_size(eb
, slot
);
4811 if (item_size
< sizeof(root_item
))
4814 read_extent_buffer(eb
, &root_item
,
4815 btrfs_item_ptr_offset(eb
, slot
),
4816 (int)sizeof(root_item
));
4817 if (btrfs_root_refs(&root_item
) == 0)
4820 if (!btrfs_is_empty_uuid(root_item
.uuid
) ||
4821 !btrfs_is_empty_uuid(root_item
.received_uuid
)) {
4825 btrfs_release_path(path
);
4827 * 1 - subvol uuid item
4828 * 1 - received_subvol uuid item
4830 trans
= btrfs_start_transaction(fs_info
->uuid_root
, 2);
4831 if (IS_ERR(trans
)) {
4832 ret
= PTR_ERR(trans
);
4840 btrfs_release_path(path
);
4841 if (!btrfs_is_empty_uuid(root_item
.uuid
)) {
4842 ret
= btrfs_uuid_tree_add(trans
, root_item
.uuid
,
4843 BTRFS_UUID_KEY_SUBVOL
,
4846 btrfs_warn(fs_info
, "uuid_tree_add failed %d",
4852 if (!btrfs_is_empty_uuid(root_item
.received_uuid
)) {
4853 ret
= btrfs_uuid_tree_add(trans
,
4854 root_item
.received_uuid
,
4855 BTRFS_UUID_KEY_RECEIVED_SUBVOL
,
4858 btrfs_warn(fs_info
, "uuid_tree_add failed %d",
4865 btrfs_release_path(path
);
4867 ret
= btrfs_end_transaction(trans
);
4873 if (key
.offset
< (u64
)-1) {
4875 } else if (key
.type
< BTRFS_ROOT_ITEM_KEY
) {
4877 key
.type
= BTRFS_ROOT_ITEM_KEY
;
4878 } else if (key
.objectid
< (u64
)-1) {
4880 key
.type
= BTRFS_ROOT_ITEM_KEY
;
4889 btrfs_free_path(path
);
4890 if (trans
&& !IS_ERR(trans
))
4891 btrfs_end_transaction(trans
);
4893 btrfs_warn(fs_info
, "btrfs_uuid_scan_kthread failed %d", ret
);
4895 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN
, &fs_info
->flags
);
4896 up(&fs_info
->uuid_tree_rescan_sem
);
4900 int btrfs_create_uuid_tree(struct btrfs_fs_info
*fs_info
)
4902 struct btrfs_trans_handle
*trans
;
4903 struct btrfs_root
*tree_root
= fs_info
->tree_root
;
4904 struct btrfs_root
*uuid_root
;
4905 struct task_struct
*task
;
4912 trans
= btrfs_start_transaction(tree_root
, 2);
4914 return PTR_ERR(trans
);
4916 uuid_root
= btrfs_create_tree(trans
, BTRFS_UUID_TREE_OBJECTID
);
4917 if (IS_ERR(uuid_root
)) {
4918 ret
= PTR_ERR(uuid_root
);
4919 btrfs_abort_transaction(trans
, ret
);
4920 btrfs_end_transaction(trans
);
4924 fs_info
->uuid_root
= uuid_root
;
4926 ret
= btrfs_commit_transaction(trans
);
4930 down(&fs_info
->uuid_tree_rescan_sem
);
4931 task
= kthread_run(btrfs_uuid_scan_kthread
, fs_info
, "btrfs-uuid");
4933 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4934 btrfs_warn(fs_info
, "failed to start uuid_scan task");
4935 up(&fs_info
->uuid_tree_rescan_sem
);
4936 return PTR_ERR(task
);
4943 * shrinking a device means finding all of the device extents past
4944 * the new size, and then following the back refs to the chunks.
4945 * The chunk relocation code actually frees the device extent
4947 int btrfs_shrink_device(struct btrfs_device
*device
, u64 new_size
)
4949 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
4950 struct btrfs_root
*root
= fs_info
->dev_root
;
4951 struct btrfs_trans_handle
*trans
;
4952 struct btrfs_dev_extent
*dev_extent
= NULL
;
4953 struct btrfs_path
*path
;
4959 bool retried
= false;
4960 struct extent_buffer
*l
;
4961 struct btrfs_key key
;
4962 struct btrfs_super_block
*super_copy
= fs_info
->super_copy
;
4963 u64 old_total
= btrfs_super_total_bytes(super_copy
);
4964 u64 old_size
= btrfs_device_get_total_bytes(device
);
4969 new_size
= round_down(new_size
, fs_info
->sectorsize
);
4971 diff
= round_down(old_size
- new_size
, fs_info
->sectorsize
);
4973 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
))
4976 path
= btrfs_alloc_path();
4980 path
->reada
= READA_BACK
;
4982 trans
= btrfs_start_transaction(root
, 0);
4983 if (IS_ERR(trans
)) {
4984 btrfs_free_path(path
);
4985 return PTR_ERR(trans
);
4988 mutex_lock(&fs_info
->chunk_mutex
);
4990 btrfs_device_set_total_bytes(device
, new_size
);
4991 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
4992 device
->fs_devices
->total_rw_bytes
-= diff
;
4995 * The new free_chunk_space is new_size - used, so we have to
4996 * subtract the delta of the old free_chunk_space which included
4997 * old_size - used. If used > new_size then just subtract this
4998 * entire device's free space.
5000 if (device
->bytes_used
< new_size
)
5001 free_diff
= (old_size
- device
->bytes_used
) -
5002 (new_size
- device
->bytes_used
);
5004 free_diff
= old_size
- device
->bytes_used
;
5005 atomic64_sub(free_diff
, &fs_info
->free_chunk_space
);
5009 * Once the device's size has been set to the new size, ensure all
5010 * in-memory chunks are synced to disk so that the loop below sees them
5011 * and relocates them accordingly.
5013 if (contains_pending_extent(device
, &start
, diff
)) {
5014 mutex_unlock(&fs_info
->chunk_mutex
);
5015 ret
= btrfs_commit_transaction(trans
);
5019 mutex_unlock(&fs_info
->chunk_mutex
);
5020 btrfs_end_transaction(trans
);
5024 key
.objectid
= device
->devid
;
5025 key
.offset
= (u64
)-1;
5026 key
.type
= BTRFS_DEV_EXTENT_KEY
;
5029 mutex_lock(&fs_info
->reclaim_bgs_lock
);
5030 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
5032 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
5036 ret
= btrfs_previous_item(root
, path
, 0, key
.type
);
5038 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
5042 btrfs_release_path(path
);
5047 slot
= path
->slots
[0];
5048 btrfs_item_key_to_cpu(l
, &key
, path
->slots
[0]);
5050 if (key
.objectid
!= device
->devid
) {
5051 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
5052 btrfs_release_path(path
);
5056 dev_extent
= btrfs_item_ptr(l
, slot
, struct btrfs_dev_extent
);
5057 length
= btrfs_dev_extent_length(l
, dev_extent
);
5059 if (key
.offset
+ length
<= new_size
) {
5060 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
5061 btrfs_release_path(path
);
5065 chunk_offset
= btrfs_dev_extent_chunk_offset(l
, dev_extent
);
5066 btrfs_release_path(path
);
5069 * We may be relocating the only data chunk we have,
5070 * which could potentially end up with losing data's
5071 * raid profile, so lets allocate an empty one in
5074 ret
= btrfs_may_alloc_data_chunk(fs_info
, chunk_offset
);
5076 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
5080 ret
= btrfs_relocate_chunk(fs_info
, chunk_offset
);
5081 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
5082 if (ret
== -ENOSPC
) {
5085 if (ret
== -ETXTBSY
) {
5087 "could not shrink block group %llu due to active swapfile",
5092 } while (key
.offset
-- > 0);
5094 if (failed
&& !retried
) {
5098 } else if (failed
&& retried
) {
5103 /* Shrinking succeeded, else we would be at "done". */
5104 trans
= btrfs_start_transaction(root
, 0);
5105 if (IS_ERR(trans
)) {
5106 ret
= PTR_ERR(trans
);
5110 mutex_lock(&fs_info
->chunk_mutex
);
5111 /* Clear all state bits beyond the shrunk device size */
5112 clear_extent_bits(&device
->alloc_state
, new_size
, (u64
)-1,
5115 btrfs_device_set_disk_total_bytes(device
, new_size
);
5116 if (list_empty(&device
->post_commit_list
))
5117 list_add_tail(&device
->post_commit_list
,
5118 &trans
->transaction
->dev_update_list
);
5120 WARN_ON(diff
> old_total
);
5121 btrfs_set_super_total_bytes(super_copy
,
5122 round_down(old_total
- diff
, fs_info
->sectorsize
));
5123 mutex_unlock(&fs_info
->chunk_mutex
);
5125 btrfs_reserve_chunk_metadata(trans
, false);
5126 /* Now btrfs_update_device() will change the on-disk size. */
5127 ret
= btrfs_update_device(trans
, device
);
5128 btrfs_trans_release_chunk_metadata(trans
);
5130 btrfs_abort_transaction(trans
, ret
);
5131 btrfs_end_transaction(trans
);
5133 ret
= btrfs_commit_transaction(trans
);
5136 btrfs_free_path(path
);
5138 mutex_lock(&fs_info
->chunk_mutex
);
5139 btrfs_device_set_total_bytes(device
, old_size
);
5140 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
5141 device
->fs_devices
->total_rw_bytes
+= diff
;
5142 atomic64_add(free_diff
, &fs_info
->free_chunk_space
);
5144 mutex_unlock(&fs_info
->chunk_mutex
);
5149 static int btrfs_add_system_chunk(struct btrfs_fs_info
*fs_info
,
5150 struct btrfs_key
*key
,
5151 struct btrfs_chunk
*chunk
, int item_size
)
5153 struct btrfs_super_block
*super_copy
= fs_info
->super_copy
;
5154 struct btrfs_disk_key disk_key
;
5158 lockdep_assert_held(&fs_info
->chunk_mutex
);
5160 array_size
= btrfs_super_sys_array_size(super_copy
);
5161 if (array_size
+ item_size
+ sizeof(disk_key
)
5162 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE
)
5165 ptr
= super_copy
->sys_chunk_array
+ array_size
;
5166 btrfs_cpu_key_to_disk(&disk_key
, key
);
5167 memcpy(ptr
, &disk_key
, sizeof(disk_key
));
5168 ptr
+= sizeof(disk_key
);
5169 memcpy(ptr
, chunk
, item_size
);
5170 item_size
+= sizeof(disk_key
);
5171 btrfs_set_super_sys_array_size(super_copy
, array_size
+ item_size
);
5177 * sort the devices in descending order by max_avail, total_avail
5179 static int btrfs_cmp_device_info(const void *a
, const void *b
)
5181 const struct btrfs_device_info
*di_a
= a
;
5182 const struct btrfs_device_info
*di_b
= b
;
5184 if (di_a
->max_avail
> di_b
->max_avail
)
5186 if (di_a
->max_avail
< di_b
->max_avail
)
5188 if (di_a
->total_avail
> di_b
->total_avail
)
5190 if (di_a
->total_avail
< di_b
->total_avail
)
5195 static void check_raid56_incompat_flag(struct btrfs_fs_info
*info
, u64 type
)
5197 if (!(type
& BTRFS_BLOCK_GROUP_RAID56_MASK
))
5200 btrfs_set_fs_incompat(info
, RAID56
);
5203 static void check_raid1c34_incompat_flag(struct btrfs_fs_info
*info
, u64 type
)
5205 if (!(type
& (BTRFS_BLOCK_GROUP_RAID1C3
| BTRFS_BLOCK_GROUP_RAID1C4
)))
5208 btrfs_set_fs_incompat(info
, RAID1C34
);
5212 * Structure used internally for btrfs_create_chunk() function.
5213 * Wraps needed parameters.
5215 struct alloc_chunk_ctl
{
5218 /* Total number of stripes to allocate */
5220 /* sub_stripes info for map */
5222 /* Stripes per device */
5224 /* Maximum number of devices to use */
5226 /* Minimum number of devices to use */
5228 /* ndevs has to be a multiple of this */
5230 /* Number of copies */
5232 /* Number of stripes worth of bytes to store parity information */
5234 u64 max_stripe_size
;
5242 static void init_alloc_chunk_ctl_policy_regular(
5243 struct btrfs_fs_devices
*fs_devices
,
5244 struct alloc_chunk_ctl
*ctl
)
5246 struct btrfs_space_info
*space_info
;
5248 space_info
= btrfs_find_space_info(fs_devices
->fs_info
, ctl
->type
);
5251 ctl
->max_chunk_size
= READ_ONCE(space_info
->chunk_size
);
5252 ctl
->max_stripe_size
= min_t(u64
, ctl
->max_chunk_size
, SZ_1G
);
5254 if (ctl
->type
& BTRFS_BLOCK_GROUP_SYSTEM
)
5255 ctl
->devs_max
= min_t(int, ctl
->devs_max
, BTRFS_MAX_DEVS_SYS_CHUNK
);
5257 /* We don't want a chunk larger than 10% of writable space */
5258 ctl
->max_chunk_size
= min(mult_perc(fs_devices
->total_rw_bytes
, 10),
5259 ctl
->max_chunk_size
);
5260 ctl
->dev_extent_min
= btrfs_stripe_nr_to_offset(ctl
->dev_stripes
);
5263 static void init_alloc_chunk_ctl_policy_zoned(
5264 struct btrfs_fs_devices
*fs_devices
,
5265 struct alloc_chunk_ctl
*ctl
)
5267 u64 zone_size
= fs_devices
->fs_info
->zone_size
;
5269 int min_num_stripes
= ctl
->devs_min
* ctl
->dev_stripes
;
5270 int min_data_stripes
= (min_num_stripes
- ctl
->nparity
) / ctl
->ncopies
;
5271 u64 min_chunk_size
= min_data_stripes
* zone_size
;
5272 u64 type
= ctl
->type
;
5274 ctl
->max_stripe_size
= zone_size
;
5275 if (type
& BTRFS_BLOCK_GROUP_DATA
) {
5276 ctl
->max_chunk_size
= round_down(BTRFS_MAX_DATA_CHUNK_SIZE
,
5278 } else if (type
& BTRFS_BLOCK_GROUP_METADATA
) {
5279 ctl
->max_chunk_size
= ctl
->max_stripe_size
;
5280 } else if (type
& BTRFS_BLOCK_GROUP_SYSTEM
) {
5281 ctl
->max_chunk_size
= 2 * ctl
->max_stripe_size
;
5282 ctl
->devs_max
= min_t(int, ctl
->devs_max
,
5283 BTRFS_MAX_DEVS_SYS_CHUNK
);
5288 /* We don't want a chunk larger than 10% of writable space */
5289 limit
= max(round_down(mult_perc(fs_devices
->total_rw_bytes
, 10),
5292 ctl
->max_chunk_size
= min(limit
, ctl
->max_chunk_size
);
5293 ctl
->dev_extent_min
= zone_size
* ctl
->dev_stripes
;
5296 static void init_alloc_chunk_ctl(struct btrfs_fs_devices
*fs_devices
,
5297 struct alloc_chunk_ctl
*ctl
)
5299 int index
= btrfs_bg_flags_to_raid_index(ctl
->type
);
5301 ctl
->sub_stripes
= btrfs_raid_array
[index
].sub_stripes
;
5302 ctl
->dev_stripes
= btrfs_raid_array
[index
].dev_stripes
;
5303 ctl
->devs_max
= btrfs_raid_array
[index
].devs_max
;
5305 ctl
->devs_max
= BTRFS_MAX_DEVS(fs_devices
->fs_info
);
5306 ctl
->devs_min
= btrfs_raid_array
[index
].devs_min
;
5307 ctl
->devs_increment
= btrfs_raid_array
[index
].devs_increment
;
5308 ctl
->ncopies
= btrfs_raid_array
[index
].ncopies
;
5309 ctl
->nparity
= btrfs_raid_array
[index
].nparity
;
5312 switch (fs_devices
->chunk_alloc_policy
) {
5313 case BTRFS_CHUNK_ALLOC_REGULAR
:
5314 init_alloc_chunk_ctl_policy_regular(fs_devices
, ctl
);
5316 case BTRFS_CHUNK_ALLOC_ZONED
:
5317 init_alloc_chunk_ctl_policy_zoned(fs_devices
, ctl
);
5324 static int gather_device_info(struct btrfs_fs_devices
*fs_devices
,
5325 struct alloc_chunk_ctl
*ctl
,
5326 struct btrfs_device_info
*devices_info
)
5328 struct btrfs_fs_info
*info
= fs_devices
->fs_info
;
5329 struct btrfs_device
*device
;
5331 u64 dev_extent_want
= ctl
->max_stripe_size
* ctl
->dev_stripes
;
5338 * in the first pass through the devices list, we gather information
5339 * about the available holes on each device.
5341 list_for_each_entry(device
, &fs_devices
->alloc_list
, dev_alloc_list
) {
5342 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
5344 "BTRFS: read-only device in alloc_list\n");
5348 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA
,
5349 &device
->dev_state
) ||
5350 test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
))
5353 if (device
->total_bytes
> device
->bytes_used
)
5354 total_avail
= device
->total_bytes
- device
->bytes_used
;
5358 /* If there is no space on this device, skip it. */
5359 if (total_avail
< ctl
->dev_extent_min
)
5362 ret
= find_free_dev_extent(device
, dev_extent_want
, &dev_offset
,
5364 if (ret
&& ret
!= -ENOSPC
)
5368 max_avail
= dev_extent_want
;
5370 if (max_avail
< ctl
->dev_extent_min
) {
5371 if (btrfs_test_opt(info
, ENOSPC_DEBUG
))
5373 "%s: devid %llu has no free space, have=%llu want=%llu",
5374 __func__
, device
->devid
, max_avail
,
5375 ctl
->dev_extent_min
);
5379 if (ndevs
== fs_devices
->rw_devices
) {
5380 WARN(1, "%s: found more than %llu devices\n",
5381 __func__
, fs_devices
->rw_devices
);
5384 devices_info
[ndevs
].dev_offset
= dev_offset
;
5385 devices_info
[ndevs
].max_avail
= max_avail
;
5386 devices_info
[ndevs
].total_avail
= total_avail
;
5387 devices_info
[ndevs
].dev
= device
;
5393 * now sort the devices by hole size / available space
5395 sort(devices_info
, ndevs
, sizeof(struct btrfs_device_info
),
5396 btrfs_cmp_device_info
, NULL
);
5401 static int decide_stripe_size_regular(struct alloc_chunk_ctl
*ctl
,
5402 struct btrfs_device_info
*devices_info
)
5404 /* Number of stripes that count for block group size */
5408 * The primary goal is to maximize the number of stripes, so use as
5409 * many devices as possible, even if the stripes are not maximum sized.
5411 * The DUP profile stores more than one stripe per device, the
5412 * max_avail is the total size so we have to adjust.
5414 ctl
->stripe_size
= div_u64(devices_info
[ctl
->ndevs
- 1].max_avail
,
5416 ctl
->num_stripes
= ctl
->ndevs
* ctl
->dev_stripes
;
5418 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5419 data_stripes
= (ctl
->num_stripes
- ctl
->nparity
) / ctl
->ncopies
;
5422 * Use the number of data stripes to figure out how big this chunk is
5423 * really going to be in terms of logical address space, and compare
5424 * that answer with the max chunk size. If it's higher, we try to
5425 * reduce stripe_size.
5427 if (ctl
->stripe_size
* data_stripes
> ctl
->max_chunk_size
) {
5429 * Reduce stripe_size, round it up to a 16MB boundary again and
5430 * then use it, unless it ends up being even bigger than the
5431 * previous value we had already.
5433 ctl
->stripe_size
= min(round_up(div_u64(ctl
->max_chunk_size
,
5434 data_stripes
), SZ_16M
),
5438 /* Stripe size should not go beyond 1G. */
5439 ctl
->stripe_size
= min_t(u64
, ctl
->stripe_size
, SZ_1G
);
5441 /* Align to BTRFS_STRIPE_LEN */
5442 ctl
->stripe_size
= round_down(ctl
->stripe_size
, BTRFS_STRIPE_LEN
);
5443 ctl
->chunk_size
= ctl
->stripe_size
* data_stripes
;
5448 static int decide_stripe_size_zoned(struct alloc_chunk_ctl
*ctl
,
5449 struct btrfs_device_info
*devices_info
)
5451 u64 zone_size
= devices_info
[0].dev
->zone_info
->zone_size
;
5452 /* Number of stripes that count for block group size */
5456 * It should hold because:
5457 * dev_extent_min == dev_extent_want == zone_size * dev_stripes
5459 ASSERT(devices_info
[ctl
->ndevs
- 1].max_avail
== ctl
->dev_extent_min
);
5461 ctl
->stripe_size
= zone_size
;
5462 ctl
->num_stripes
= ctl
->ndevs
* ctl
->dev_stripes
;
5463 data_stripes
= (ctl
->num_stripes
- ctl
->nparity
) / ctl
->ncopies
;
5465 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */
5466 if (ctl
->stripe_size
* data_stripes
> ctl
->max_chunk_size
) {
5467 ctl
->ndevs
= div_u64(div_u64(ctl
->max_chunk_size
* ctl
->ncopies
,
5468 ctl
->stripe_size
) + ctl
->nparity
,
5470 ctl
->num_stripes
= ctl
->ndevs
* ctl
->dev_stripes
;
5471 data_stripes
= (ctl
->num_stripes
- ctl
->nparity
) / ctl
->ncopies
;
5472 ASSERT(ctl
->stripe_size
* data_stripes
<= ctl
->max_chunk_size
);
5475 ctl
->chunk_size
= ctl
->stripe_size
* data_stripes
;
5480 static int decide_stripe_size(struct btrfs_fs_devices
*fs_devices
,
5481 struct alloc_chunk_ctl
*ctl
,
5482 struct btrfs_device_info
*devices_info
)
5484 struct btrfs_fs_info
*info
= fs_devices
->fs_info
;
5487 * Round down to number of usable stripes, devs_increment can be any
5488 * number so we can't use round_down() that requires power of 2, while
5489 * rounddown is safe.
5491 ctl
->ndevs
= rounddown(ctl
->ndevs
, ctl
->devs_increment
);
5493 if (ctl
->ndevs
< ctl
->devs_min
) {
5494 if (btrfs_test_opt(info
, ENOSPC_DEBUG
)) {
5496 "%s: not enough devices with free space: have=%d minimum required=%d",
5497 __func__
, ctl
->ndevs
, ctl
->devs_min
);
5502 ctl
->ndevs
= min(ctl
->ndevs
, ctl
->devs_max
);
5504 switch (fs_devices
->chunk_alloc_policy
) {
5505 case BTRFS_CHUNK_ALLOC_REGULAR
:
5506 return decide_stripe_size_regular(ctl
, devices_info
);
5507 case BTRFS_CHUNK_ALLOC_ZONED
:
5508 return decide_stripe_size_zoned(ctl
, devices_info
);
5514 static void chunk_map_device_set_bits(struct btrfs_chunk_map
*map
, unsigned int bits
)
5516 for (int i
= 0; i
< map
->num_stripes
; i
++) {
5517 struct btrfs_io_stripe
*stripe
= &map
->stripes
[i
];
5518 struct btrfs_device
*device
= stripe
->dev
;
5520 set_extent_bit(&device
->alloc_state
, stripe
->physical
,
5521 stripe
->physical
+ map
->stripe_size
- 1,
5522 bits
| EXTENT_NOWAIT
, NULL
);
5526 static void chunk_map_device_clear_bits(struct btrfs_chunk_map
*map
, unsigned int bits
)
5528 for (int i
= 0; i
< map
->num_stripes
; i
++) {
5529 struct btrfs_io_stripe
*stripe
= &map
->stripes
[i
];
5530 struct btrfs_device
*device
= stripe
->dev
;
5532 __clear_extent_bit(&device
->alloc_state
, stripe
->physical
,
5533 stripe
->physical
+ map
->stripe_size
- 1,
5534 bits
| EXTENT_NOWAIT
,
5539 void btrfs_remove_chunk_map(struct btrfs_fs_info
*fs_info
, struct btrfs_chunk_map
*map
)
5541 write_lock(&fs_info
->mapping_tree_lock
);
5542 rb_erase_cached(&map
->rb_node
, &fs_info
->mapping_tree
);
5543 RB_CLEAR_NODE(&map
->rb_node
);
5544 chunk_map_device_clear_bits(map
, CHUNK_ALLOCATED
);
5545 write_unlock(&fs_info
->mapping_tree_lock
);
5547 /* Once for the tree reference. */
5548 btrfs_free_chunk_map(map
);
5552 int btrfs_add_chunk_map(struct btrfs_fs_info
*fs_info
, struct btrfs_chunk_map
*map
)
5555 struct rb_node
*parent
= NULL
;
5556 bool leftmost
= true;
5558 write_lock(&fs_info
->mapping_tree_lock
);
5559 p
= &fs_info
->mapping_tree
.rb_root
.rb_node
;
5561 struct btrfs_chunk_map
*entry
;
5564 entry
= rb_entry(parent
, struct btrfs_chunk_map
, rb_node
);
5566 if (map
->start
< entry
->start
) {
5568 } else if (map
->start
> entry
->start
) {
5569 p
= &(*p
)->rb_right
;
5572 write_unlock(&fs_info
->mapping_tree_lock
);
5576 rb_link_node(&map
->rb_node
, parent
, p
);
5577 rb_insert_color_cached(&map
->rb_node
, &fs_info
->mapping_tree
, leftmost
);
5578 chunk_map_device_set_bits(map
, CHUNK_ALLOCATED
);
5579 chunk_map_device_clear_bits(map
, CHUNK_TRIMMED
);
5580 write_unlock(&fs_info
->mapping_tree_lock
);
5586 struct btrfs_chunk_map
*btrfs_alloc_chunk_map(int num_stripes
, gfp_t gfp
)
5588 struct btrfs_chunk_map
*map
;
5590 map
= kmalloc(btrfs_chunk_map_size(num_stripes
), gfp
);
5594 refcount_set(&map
->refs
, 1);
5595 RB_CLEAR_NODE(&map
->rb_node
);
5600 struct btrfs_chunk_map
*btrfs_clone_chunk_map(struct btrfs_chunk_map
*map
, gfp_t gfp
)
5602 const int size
= btrfs_chunk_map_size(map
->num_stripes
);
5603 struct btrfs_chunk_map
*clone
;
5605 clone
= kmemdup(map
, size
, gfp
);
5609 refcount_set(&clone
->refs
, 1);
5610 RB_CLEAR_NODE(&clone
->rb_node
);
5615 static struct btrfs_block_group
*create_chunk(struct btrfs_trans_handle
*trans
,
5616 struct alloc_chunk_ctl
*ctl
,
5617 struct btrfs_device_info
*devices_info
)
5619 struct btrfs_fs_info
*info
= trans
->fs_info
;
5620 struct btrfs_chunk_map
*map
;
5621 struct btrfs_block_group
*block_group
;
5622 u64 start
= ctl
->start
;
5623 u64 type
= ctl
->type
;
5628 map
= btrfs_alloc_chunk_map(ctl
->num_stripes
, GFP_NOFS
);
5630 return ERR_PTR(-ENOMEM
);
5633 map
->chunk_len
= ctl
->chunk_size
;
5634 map
->stripe_size
= ctl
->stripe_size
;
5636 map
->io_align
= BTRFS_STRIPE_LEN
;
5637 map
->io_width
= BTRFS_STRIPE_LEN
;
5638 map
->sub_stripes
= ctl
->sub_stripes
;
5639 map
->num_stripes
= ctl
->num_stripes
;
5641 for (i
= 0; i
< ctl
->ndevs
; ++i
) {
5642 for (j
= 0; j
< ctl
->dev_stripes
; ++j
) {
5643 int s
= i
* ctl
->dev_stripes
+ j
;
5644 map
->stripes
[s
].dev
= devices_info
[i
].dev
;
5645 map
->stripes
[s
].physical
= devices_info
[i
].dev_offset
+
5646 j
* ctl
->stripe_size
;
5650 trace_btrfs_chunk_alloc(info
, map
, start
, ctl
->chunk_size
);
5652 ret
= btrfs_add_chunk_map(info
, map
);
5654 btrfs_free_chunk_map(map
);
5655 return ERR_PTR(ret
);
5658 block_group
= btrfs_make_block_group(trans
, type
, start
, ctl
->chunk_size
);
5659 if (IS_ERR(block_group
)) {
5660 btrfs_remove_chunk_map(info
, map
);
5664 for (int i
= 0; i
< map
->num_stripes
; i
++) {
5665 struct btrfs_device
*dev
= map
->stripes
[i
].dev
;
5667 btrfs_device_set_bytes_used(dev
,
5668 dev
->bytes_used
+ ctl
->stripe_size
);
5669 if (list_empty(&dev
->post_commit_list
))
5670 list_add_tail(&dev
->post_commit_list
,
5671 &trans
->transaction
->dev_update_list
);
5674 atomic64_sub(ctl
->stripe_size
* map
->num_stripes
,
5675 &info
->free_chunk_space
);
5677 check_raid56_incompat_flag(info
, type
);
5678 check_raid1c34_incompat_flag(info
, type
);
5683 struct btrfs_block_group
*btrfs_create_chunk(struct btrfs_trans_handle
*trans
,
5686 struct btrfs_fs_info
*info
= trans
->fs_info
;
5687 struct btrfs_fs_devices
*fs_devices
= info
->fs_devices
;
5688 struct btrfs_device_info
*devices_info
= NULL
;
5689 struct alloc_chunk_ctl ctl
;
5690 struct btrfs_block_group
*block_group
;
5693 lockdep_assert_held(&info
->chunk_mutex
);
5695 if (!alloc_profile_is_valid(type
, 0)) {
5697 return ERR_PTR(-EINVAL
);
5700 if (list_empty(&fs_devices
->alloc_list
)) {
5701 if (btrfs_test_opt(info
, ENOSPC_DEBUG
))
5702 btrfs_debug(info
, "%s: no writable device", __func__
);
5703 return ERR_PTR(-ENOSPC
);
5706 if (!(type
& BTRFS_BLOCK_GROUP_TYPE_MASK
)) {
5707 btrfs_err(info
, "invalid chunk type 0x%llx requested", type
);
5709 return ERR_PTR(-EINVAL
);
5712 ctl
.start
= find_next_chunk(info
);
5714 init_alloc_chunk_ctl(fs_devices
, &ctl
);
5716 devices_info
= kcalloc(fs_devices
->rw_devices
, sizeof(*devices_info
),
5719 return ERR_PTR(-ENOMEM
);
5721 ret
= gather_device_info(fs_devices
, &ctl
, devices_info
);
5723 block_group
= ERR_PTR(ret
);
5727 ret
= decide_stripe_size(fs_devices
, &ctl
, devices_info
);
5729 block_group
= ERR_PTR(ret
);
5733 block_group
= create_chunk(trans
, &ctl
, devices_info
);
5736 kfree(devices_info
);
5741 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5742 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5745 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5748 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle
*trans
,
5749 struct btrfs_block_group
*bg
)
5751 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
5752 struct btrfs_root
*chunk_root
= fs_info
->chunk_root
;
5753 struct btrfs_key key
;
5754 struct btrfs_chunk
*chunk
;
5755 struct btrfs_stripe
*stripe
;
5756 struct btrfs_chunk_map
*map
;
5762 * We take the chunk_mutex for 2 reasons:
5764 * 1) Updates and insertions in the chunk btree must be done while holding
5765 * the chunk_mutex, as well as updating the system chunk array in the
5766 * superblock. See the comment on top of btrfs_chunk_alloc() for the
5769 * 2) To prevent races with the final phase of a device replace operation
5770 * that replaces the device object associated with the map's stripes,
5771 * because the device object's id can change at any time during that
5772 * final phase of the device replace operation
5773 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5774 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5775 * which would cause a failure when updating the device item, which does
5776 * not exists, or persisting a stripe of the chunk item with such ID.
5777 * Here we can't use the device_list_mutex because our caller already
5778 * has locked the chunk_mutex, and the final phase of device replace
5779 * acquires both mutexes - first the device_list_mutex and then the
5780 * chunk_mutex. Using any of those two mutexes protects us from a
5781 * concurrent device replace.
5783 lockdep_assert_held(&fs_info
->chunk_mutex
);
5785 map
= btrfs_get_chunk_map(fs_info
, bg
->start
, bg
->length
);
5788 btrfs_abort_transaction(trans
, ret
);
5792 item_size
= btrfs_chunk_item_size(map
->num_stripes
);
5794 chunk
= kzalloc(item_size
, GFP_NOFS
);
5797 btrfs_abort_transaction(trans
, ret
);
5801 for (i
= 0; i
< map
->num_stripes
; i
++) {
5802 struct btrfs_device
*device
= map
->stripes
[i
].dev
;
5804 ret
= btrfs_update_device(trans
, device
);
5809 stripe
= &chunk
->stripe
;
5810 for (i
= 0; i
< map
->num_stripes
; i
++) {
5811 struct btrfs_device
*device
= map
->stripes
[i
].dev
;
5812 const u64 dev_offset
= map
->stripes
[i
].physical
;
5814 btrfs_set_stack_stripe_devid(stripe
, device
->devid
);
5815 btrfs_set_stack_stripe_offset(stripe
, dev_offset
);
5816 memcpy(stripe
->dev_uuid
, device
->uuid
, BTRFS_UUID_SIZE
);
5820 btrfs_set_stack_chunk_length(chunk
, bg
->length
);
5821 btrfs_set_stack_chunk_owner(chunk
, BTRFS_EXTENT_TREE_OBJECTID
);
5822 btrfs_set_stack_chunk_stripe_len(chunk
, BTRFS_STRIPE_LEN
);
5823 btrfs_set_stack_chunk_type(chunk
, map
->type
);
5824 btrfs_set_stack_chunk_num_stripes(chunk
, map
->num_stripes
);
5825 btrfs_set_stack_chunk_io_align(chunk
, BTRFS_STRIPE_LEN
);
5826 btrfs_set_stack_chunk_io_width(chunk
, BTRFS_STRIPE_LEN
);
5827 btrfs_set_stack_chunk_sector_size(chunk
, fs_info
->sectorsize
);
5828 btrfs_set_stack_chunk_sub_stripes(chunk
, map
->sub_stripes
);
5830 key
.objectid
= BTRFS_FIRST_CHUNK_TREE_OBJECTID
;
5831 key
.type
= BTRFS_CHUNK_ITEM_KEY
;
5832 key
.offset
= bg
->start
;
5834 ret
= btrfs_insert_item(trans
, chunk_root
, &key
, chunk
, item_size
);
5838 set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED
, &bg
->runtime_flags
);
5840 if (map
->type
& BTRFS_BLOCK_GROUP_SYSTEM
) {
5841 ret
= btrfs_add_system_chunk(fs_info
, &key
, chunk
, item_size
);
5848 btrfs_free_chunk_map(map
);
5852 static noinline
int init_first_rw_device(struct btrfs_trans_handle
*trans
)
5854 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
5856 struct btrfs_block_group
*meta_bg
;
5857 struct btrfs_block_group
*sys_bg
;
5860 * When adding a new device for sprouting, the seed device is read-only
5861 * so we must first allocate a metadata and a system chunk. But before
5862 * adding the block group items to the extent, device and chunk btrees,
5865 * 1) Create both chunks without doing any changes to the btrees, as
5866 * otherwise we would get -ENOSPC since the block groups from the
5867 * seed device are read-only;
5869 * 2) Add the device item for the new sprout device - finishing the setup
5870 * of a new block group requires updating the device item in the chunk
5871 * btree, so it must exist when we attempt to do it. The previous step
5872 * ensures this does not fail with -ENOSPC.
5874 * After that we can add the block group items to their btrees:
5875 * update existing device item in the chunk btree, add a new block group
5876 * item to the extent btree, add a new chunk item to the chunk btree and
5877 * finally add the new device extent items to the devices btree.
5880 alloc_profile
= btrfs_metadata_alloc_profile(fs_info
);
5881 meta_bg
= btrfs_create_chunk(trans
, alloc_profile
);
5882 if (IS_ERR(meta_bg
))
5883 return PTR_ERR(meta_bg
);
5885 alloc_profile
= btrfs_system_alloc_profile(fs_info
);
5886 sys_bg
= btrfs_create_chunk(trans
, alloc_profile
);
5888 return PTR_ERR(sys_bg
);
5893 static inline int btrfs_chunk_max_errors(struct btrfs_chunk_map
*map
)
5895 const int index
= btrfs_bg_flags_to_raid_index(map
->type
);
5897 return btrfs_raid_array
[index
].tolerated_failures
;
5900 bool btrfs_chunk_writeable(struct btrfs_fs_info
*fs_info
, u64 chunk_offset
)
5902 struct btrfs_chunk_map
*map
;
5907 map
= btrfs_get_chunk_map(fs_info
, chunk_offset
, 1);
5911 for (i
= 0; i
< map
->num_stripes
; i
++) {
5912 if (test_bit(BTRFS_DEV_STATE_MISSING
,
5913 &map
->stripes
[i
].dev
->dev_state
)) {
5917 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE
,
5918 &map
->stripes
[i
].dev
->dev_state
)) {
5925 * If the number of missing devices is larger than max errors, we can
5926 * not write the data into that chunk successfully.
5928 if (miss_ndevs
> btrfs_chunk_max_errors(map
))
5931 btrfs_free_chunk_map(map
);
5935 void btrfs_mapping_tree_free(struct btrfs_fs_info
*fs_info
)
5937 write_lock(&fs_info
->mapping_tree_lock
);
5938 while (!RB_EMPTY_ROOT(&fs_info
->mapping_tree
.rb_root
)) {
5939 struct btrfs_chunk_map
*map
;
5940 struct rb_node
*node
;
5942 node
= rb_first_cached(&fs_info
->mapping_tree
);
5943 map
= rb_entry(node
, struct btrfs_chunk_map
, rb_node
);
5944 rb_erase_cached(&map
->rb_node
, &fs_info
->mapping_tree
);
5945 RB_CLEAR_NODE(&map
->rb_node
);
5946 chunk_map_device_clear_bits(map
, CHUNK_ALLOCATED
);
5947 /* Once for the tree ref. */
5948 btrfs_free_chunk_map(map
);
5949 cond_resched_rwlock_write(&fs_info
->mapping_tree_lock
);
5951 write_unlock(&fs_info
->mapping_tree_lock
);
5954 int btrfs_num_copies(struct btrfs_fs_info
*fs_info
, u64 logical
, u64 len
)
5956 struct btrfs_chunk_map
*map
;
5957 enum btrfs_raid_types index
;
5960 map
= btrfs_get_chunk_map(fs_info
, logical
, len
);
5963 * We could return errors for these cases, but that could get
5964 * ugly and we'd probably do the same thing which is just not do
5965 * anything else and exit, so return 1 so the callers don't try
5966 * to use other copies.
5970 index
= btrfs_bg_flags_to_raid_index(map
->type
);
5972 /* Non-RAID56, use their ncopies from btrfs_raid_array. */
5973 if (!(map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
))
5974 ret
= btrfs_raid_array
[index
].ncopies
;
5975 else if (map
->type
& BTRFS_BLOCK_GROUP_RAID5
)
5977 else if (map
->type
& BTRFS_BLOCK_GROUP_RAID6
)
5979 * There could be two corrupted data stripes, we need
5980 * to loop retry in order to rebuild the correct data.
5982 * Fail a stripe at a time on every retry except the
5983 * stripe under reconstruction.
5985 ret
= map
->num_stripes
;
5986 btrfs_free_chunk_map(map
);
5990 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info
*fs_info
,
5993 struct btrfs_chunk_map
*map
;
5994 unsigned long len
= fs_info
->sectorsize
;
5996 if (!btrfs_fs_incompat(fs_info
, RAID56
))
5999 map
= btrfs_get_chunk_map(fs_info
, logical
, len
);
6001 if (!WARN_ON(IS_ERR(map
))) {
6002 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
)
6003 len
= btrfs_stripe_nr_to_offset(nr_data_stripes(map
));
6004 btrfs_free_chunk_map(map
);
6009 int btrfs_is_parity_mirror(struct btrfs_fs_info
*fs_info
, u64 logical
, u64 len
)
6011 struct btrfs_chunk_map
*map
;
6014 if (!btrfs_fs_incompat(fs_info
, RAID56
))
6017 map
= btrfs_get_chunk_map(fs_info
, logical
, len
);
6019 if (!WARN_ON(IS_ERR(map
))) {
6020 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
)
6022 btrfs_free_chunk_map(map
);
6027 static int find_live_mirror(struct btrfs_fs_info
*fs_info
,
6028 struct btrfs_chunk_map
*map
, int first
,
6029 int dev_replace_is_ongoing
)
6031 const enum btrfs_read_policy policy
= READ_ONCE(fs_info
->fs_devices
->read_policy
);
6034 int preferred_mirror
;
6036 struct btrfs_device
*srcdev
;
6039 (BTRFS_BLOCK_GROUP_RAID1_MASK
| BTRFS_BLOCK_GROUP_RAID10
)));
6041 if (map
->type
& BTRFS_BLOCK_GROUP_RAID10
)
6042 num_stripes
= map
->sub_stripes
;
6044 num_stripes
= map
->num_stripes
;
6048 /* Shouldn't happen, just warn and use pid instead of failing */
6049 btrfs_warn_rl(fs_info
, "unknown read_policy type %u, reset to pid",
6051 WRITE_ONCE(fs_info
->fs_devices
->read_policy
, BTRFS_READ_POLICY_PID
);
6053 case BTRFS_READ_POLICY_PID
:
6054 preferred_mirror
= first
+ (current
->pid
% num_stripes
);
6058 if (dev_replace_is_ongoing
&&
6059 fs_info
->dev_replace
.cont_reading_from_srcdev_mode
==
6060 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID
)
6061 srcdev
= fs_info
->dev_replace
.srcdev
;
6066 * try to avoid the drive that is the source drive for a
6067 * dev-replace procedure, only choose it if no other non-missing
6068 * mirror is available
6070 for (tolerance
= 0; tolerance
< 2; tolerance
++) {
6071 if (map
->stripes
[preferred_mirror
].dev
->bdev
&&
6072 (tolerance
|| map
->stripes
[preferred_mirror
].dev
!= srcdev
))
6073 return preferred_mirror
;
6074 for (i
= first
; i
< first
+ num_stripes
; i
++) {
6075 if (map
->stripes
[i
].dev
->bdev
&&
6076 (tolerance
|| map
->stripes
[i
].dev
!= srcdev
))
6081 /* we couldn't find one that doesn't fail. Just return something
6082 * and the io error handling code will clean up eventually
6084 return preferred_mirror
;
6087 static struct btrfs_io_context
*alloc_btrfs_io_context(struct btrfs_fs_info
*fs_info
,
6091 struct btrfs_io_context
*bioc
;
6094 /* The size of btrfs_io_context */
6095 sizeof(struct btrfs_io_context
) +
6096 /* Plus the variable array for the stripes */
6097 sizeof(struct btrfs_io_stripe
) * (total_stripes
),
6103 refcount_set(&bioc
->refs
, 1);
6105 bioc
->fs_info
= fs_info
;
6106 bioc
->replace_stripe_src
= -1;
6107 bioc
->full_stripe_logical
= (u64
)-1;
6108 bioc
->logical
= logical
;
6113 void btrfs_get_bioc(struct btrfs_io_context
*bioc
)
6115 WARN_ON(!refcount_read(&bioc
->refs
));
6116 refcount_inc(&bioc
->refs
);
6119 void btrfs_put_bioc(struct btrfs_io_context
*bioc
)
6123 if (refcount_dec_and_test(&bioc
->refs
))
6128 * Please note that, discard won't be sent to target device of device
6131 struct btrfs_discard_stripe
*btrfs_map_discard(struct btrfs_fs_info
*fs_info
,
6132 u64 logical
, u64
*length_ret
,
6135 struct btrfs_chunk_map
*map
;
6136 struct btrfs_discard_stripe
*stripes
;
6137 u64 length
= *length_ret
;
6142 u64 stripe_end_offset
;
6146 u32 sub_stripes
= 0;
6147 u32 stripes_per_dev
= 0;
6148 u32 remaining_stripes
= 0;
6149 u32 last_stripe
= 0;
6153 map
= btrfs_get_chunk_map(fs_info
, logical
, length
);
6155 return ERR_CAST(map
);
6157 /* we don't discard raid56 yet */
6158 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
) {
6163 offset
= logical
- map
->start
;
6164 length
= min_t(u64
, map
->start
+ map
->chunk_len
- logical
, length
);
6165 *length_ret
= length
;
6168 * stripe_nr counts the total number of stripes we have to stride
6169 * to get to this block
6171 stripe_nr
= offset
>> BTRFS_STRIPE_LEN_SHIFT
;
6173 /* stripe_offset is the offset of this block in its stripe */
6174 stripe_offset
= offset
- btrfs_stripe_nr_to_offset(stripe_nr
);
6176 stripe_nr_end
= round_up(offset
+ length
, BTRFS_STRIPE_LEN
) >>
6177 BTRFS_STRIPE_LEN_SHIFT
;
6178 stripe_cnt
= stripe_nr_end
- stripe_nr
;
6179 stripe_end_offset
= btrfs_stripe_nr_to_offset(stripe_nr_end
) -
6182 * after this, stripe_nr is the number of stripes on this
6183 * device we have to walk to find the data, and stripe_index is
6184 * the number of our device in the stripe array
6188 if (map
->type
& (BTRFS_BLOCK_GROUP_RAID0
|
6189 BTRFS_BLOCK_GROUP_RAID10
)) {
6190 if (map
->type
& BTRFS_BLOCK_GROUP_RAID0
)
6193 sub_stripes
= map
->sub_stripes
;
6195 factor
= map
->num_stripes
/ sub_stripes
;
6196 *num_stripes
= min_t(u64
, map
->num_stripes
,
6197 sub_stripes
* stripe_cnt
);
6198 stripe_index
= stripe_nr
% factor
;
6199 stripe_nr
/= factor
;
6200 stripe_index
*= sub_stripes
;
6202 remaining_stripes
= stripe_cnt
% factor
;
6203 stripes_per_dev
= stripe_cnt
/ factor
;
6204 last_stripe
= ((stripe_nr_end
- 1) % factor
) * sub_stripes
;
6205 } else if (map
->type
& (BTRFS_BLOCK_GROUP_RAID1_MASK
|
6206 BTRFS_BLOCK_GROUP_DUP
)) {
6207 *num_stripes
= map
->num_stripes
;
6209 stripe_index
= stripe_nr
% map
->num_stripes
;
6210 stripe_nr
/= map
->num_stripes
;
6213 stripes
= kcalloc(*num_stripes
, sizeof(*stripes
), GFP_NOFS
);
6219 for (i
= 0; i
< *num_stripes
; i
++) {
6220 stripes
[i
].physical
=
6221 map
->stripes
[stripe_index
].physical
+
6222 stripe_offset
+ btrfs_stripe_nr_to_offset(stripe_nr
);
6223 stripes
[i
].dev
= map
->stripes
[stripe_index
].dev
;
6225 if (map
->type
& (BTRFS_BLOCK_GROUP_RAID0
|
6226 BTRFS_BLOCK_GROUP_RAID10
)) {
6227 stripes
[i
].length
= btrfs_stripe_nr_to_offset(stripes_per_dev
);
6229 if (i
/ sub_stripes
< remaining_stripes
)
6230 stripes
[i
].length
+= BTRFS_STRIPE_LEN
;
6233 * Special for the first stripe and
6236 * |-------|...|-------|
6240 if (i
< sub_stripes
)
6241 stripes
[i
].length
-= stripe_offset
;
6243 if (stripe_index
>= last_stripe
&&
6244 stripe_index
<= (last_stripe
+
6246 stripes
[i
].length
-= stripe_end_offset
;
6248 if (i
== sub_stripes
- 1)
6251 stripes
[i
].length
= length
;
6255 if (stripe_index
== map
->num_stripes
) {
6261 btrfs_free_chunk_map(map
);
6264 btrfs_free_chunk_map(map
);
6265 return ERR_PTR(ret
);
6268 static bool is_block_group_to_copy(struct btrfs_fs_info
*fs_info
, u64 logical
)
6270 struct btrfs_block_group
*cache
;
6273 /* Non zoned filesystem does not use "to_copy" flag */
6274 if (!btrfs_is_zoned(fs_info
))
6277 cache
= btrfs_lookup_block_group(fs_info
, logical
);
6279 ret
= test_bit(BLOCK_GROUP_FLAG_TO_COPY
, &cache
->runtime_flags
);
6281 btrfs_put_block_group(cache
);
6285 static void handle_ops_on_dev_replace(enum btrfs_map_op op
,
6286 struct btrfs_io_context
*bioc
,
6287 struct btrfs_dev_replace
*dev_replace
,
6289 int *num_stripes_ret
, int *max_errors_ret
)
6291 u64 srcdev_devid
= dev_replace
->srcdev
->devid
;
6293 * At this stage, num_stripes is still the real number of stripes,
6294 * excluding the duplicated stripes.
6296 int num_stripes
= *num_stripes_ret
;
6297 int nr_extra_stripes
= 0;
6298 int max_errors
= *max_errors_ret
;
6302 * A block group which has "to_copy" set will eventually be copied by
6303 * the dev-replace process. We can avoid cloning IO here.
6305 if (is_block_group_to_copy(dev_replace
->srcdev
->fs_info
, logical
))
6309 * Duplicate the write operations while the dev-replace procedure is
6310 * running. Since the copying of the old disk to the new disk takes
6311 * place at run time while the filesystem is mounted writable, the
6312 * regular write operations to the old disk have to be duplicated to go
6313 * to the new disk as well.
6315 * Note that device->missing is handled by the caller, and that the
6316 * write to the old disk is already set up in the stripes array.
6318 for (i
= 0; i
< num_stripes
; i
++) {
6319 struct btrfs_io_stripe
*old
= &bioc
->stripes
[i
];
6320 struct btrfs_io_stripe
*new = &bioc
->stripes
[num_stripes
+ nr_extra_stripes
];
6322 if (old
->dev
->devid
!= srcdev_devid
)
6325 new->physical
= old
->physical
;
6326 new->dev
= dev_replace
->tgtdev
;
6327 if (bioc
->map_type
& BTRFS_BLOCK_GROUP_RAID56_MASK
)
6328 bioc
->replace_stripe_src
= i
;
6332 /* We can only have at most 2 extra nr_stripes (for DUP). */
6333 ASSERT(nr_extra_stripes
<= 2);
6335 * For GET_READ_MIRRORS, we can only return at most 1 extra stripe for
6337 * If we have 2 extra stripes, only choose the one with smaller physical.
6339 if (op
== BTRFS_MAP_GET_READ_MIRRORS
&& nr_extra_stripes
== 2) {
6340 struct btrfs_io_stripe
*first
= &bioc
->stripes
[num_stripes
];
6341 struct btrfs_io_stripe
*second
= &bioc
->stripes
[num_stripes
+ 1];
6343 /* Only DUP can have two extra stripes. */
6344 ASSERT(bioc
->map_type
& BTRFS_BLOCK_GROUP_DUP
);
6347 * Swap the last stripe stripes and reduce @nr_extra_stripes.
6348 * The extra stripe would still be there, but won't be accessed.
6350 if (first
->physical
> second
->physical
) {
6351 swap(second
->physical
, first
->physical
);
6352 swap(second
->dev
, first
->dev
);
6357 *num_stripes_ret
= num_stripes
+ nr_extra_stripes
;
6358 *max_errors_ret
= max_errors
+ nr_extra_stripes
;
6359 bioc
->replace_nr_stripes
= nr_extra_stripes
;
6362 static u64
btrfs_max_io_len(struct btrfs_chunk_map
*map
, u64 offset
,
6363 struct btrfs_io_geometry
*io_geom
)
6366 * Stripe_nr is the stripe where this block falls. stripe_offset is
6367 * the offset of this block in its stripe.
6369 io_geom
->stripe_offset
= offset
& BTRFS_STRIPE_LEN_MASK
;
6370 io_geom
->stripe_nr
= offset
>> BTRFS_STRIPE_LEN_SHIFT
;
6371 ASSERT(io_geom
->stripe_offset
< U32_MAX
);
6373 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
) {
6374 unsigned long full_stripe_len
=
6375 btrfs_stripe_nr_to_offset(nr_data_stripes(map
));
6378 * For full stripe start, we use previously calculated
6379 * @stripe_nr. Align it to nr_data_stripes, then multiply with
6382 * By this we can avoid u64 division completely. And we have
6383 * to go rounddown(), not round_down(), as nr_data_stripes is
6384 * not ensured to be power of 2.
6386 io_geom
->raid56_full_stripe_start
= btrfs_stripe_nr_to_offset(
6387 rounddown(io_geom
->stripe_nr
, nr_data_stripes(map
)));
6389 ASSERT(io_geom
->raid56_full_stripe_start
+ full_stripe_len
> offset
);
6390 ASSERT(io_geom
->raid56_full_stripe_start
<= offset
);
6392 * For writes to RAID56, allow to write a full stripe set, but
6393 * no straddling of stripe sets.
6395 if (io_geom
->op
== BTRFS_MAP_WRITE
)
6396 return full_stripe_len
- (offset
- io_geom
->raid56_full_stripe_start
);
6400 * For other RAID types and for RAID56 reads, allow a single stripe (on
6403 if (map
->type
& BTRFS_BLOCK_GROUP_STRIPE_MASK
)
6404 return BTRFS_STRIPE_LEN
- io_geom
->stripe_offset
;
6408 static int set_io_stripe(struct btrfs_fs_info
*fs_info
, u64 logical
,
6409 u64
*length
, struct btrfs_io_stripe
*dst
,
6410 struct btrfs_chunk_map
*map
,
6411 struct btrfs_io_geometry
*io_geom
)
6413 dst
->dev
= map
->stripes
[io_geom
->stripe_index
].dev
;
6415 if (io_geom
->op
== BTRFS_MAP_READ
&&
6416 btrfs_need_stripe_tree_update(fs_info
, map
->type
))
6417 return btrfs_get_raid_extent_offset(fs_info
, logical
, length
,
6419 io_geom
->stripe_index
, dst
);
6421 dst
->physical
= map
->stripes
[io_geom
->stripe_index
].physical
+
6422 io_geom
->stripe_offset
+
6423 btrfs_stripe_nr_to_offset(io_geom
->stripe_nr
);
6427 static bool is_single_device_io(struct btrfs_fs_info
*fs_info
,
6428 const struct btrfs_io_stripe
*smap
,
6429 const struct btrfs_chunk_map
*map
,
6430 int num_alloc_stripes
,
6431 enum btrfs_map_op op
, int mirror_num
)
6436 if (num_alloc_stripes
!= 1)
6439 if (btrfs_need_stripe_tree_update(fs_info
, map
->type
) && op
!= BTRFS_MAP_READ
)
6442 if ((map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
) && mirror_num
> 1)
6448 static void map_blocks_raid0(const struct btrfs_chunk_map
*map
,
6449 struct btrfs_io_geometry
*io_geom
)
6451 io_geom
->stripe_index
= io_geom
->stripe_nr
% map
->num_stripes
;
6452 io_geom
->stripe_nr
/= map
->num_stripes
;
6453 if (io_geom
->op
== BTRFS_MAP_READ
)
6454 io_geom
->mirror_num
= 1;
6457 static void map_blocks_raid1(struct btrfs_fs_info
*fs_info
,
6458 struct btrfs_chunk_map
*map
,
6459 struct btrfs_io_geometry
*io_geom
,
6460 bool dev_replace_is_ongoing
)
6462 if (io_geom
->op
!= BTRFS_MAP_READ
) {
6463 io_geom
->num_stripes
= map
->num_stripes
;
6467 if (io_geom
->mirror_num
) {
6468 io_geom
->stripe_index
= io_geom
->mirror_num
- 1;
6472 io_geom
->stripe_index
= find_live_mirror(fs_info
, map
, 0,
6473 dev_replace_is_ongoing
);
6474 io_geom
->mirror_num
= io_geom
->stripe_index
+ 1;
6477 static void map_blocks_dup(const struct btrfs_chunk_map
*map
,
6478 struct btrfs_io_geometry
*io_geom
)
6480 if (io_geom
->op
!= BTRFS_MAP_READ
) {
6481 io_geom
->num_stripes
= map
->num_stripes
;
6485 if (io_geom
->mirror_num
) {
6486 io_geom
->stripe_index
= io_geom
->mirror_num
- 1;
6490 io_geom
->mirror_num
= 1;
6493 static void map_blocks_raid10(struct btrfs_fs_info
*fs_info
,
6494 struct btrfs_chunk_map
*map
,
6495 struct btrfs_io_geometry
*io_geom
,
6496 bool dev_replace_is_ongoing
)
6498 u32 factor
= map
->num_stripes
/ map
->sub_stripes
;
6499 int old_stripe_index
;
6501 io_geom
->stripe_index
= (io_geom
->stripe_nr
% factor
) * map
->sub_stripes
;
6502 io_geom
->stripe_nr
/= factor
;
6504 if (io_geom
->op
!= BTRFS_MAP_READ
) {
6505 io_geom
->num_stripes
= map
->sub_stripes
;
6509 if (io_geom
->mirror_num
) {
6510 io_geom
->stripe_index
+= io_geom
->mirror_num
- 1;
6514 old_stripe_index
= io_geom
->stripe_index
;
6515 io_geom
->stripe_index
= find_live_mirror(fs_info
, map
,
6516 io_geom
->stripe_index
,
6517 dev_replace_is_ongoing
);
6518 io_geom
->mirror_num
= io_geom
->stripe_index
- old_stripe_index
+ 1;
6521 static void map_blocks_raid56_write(struct btrfs_chunk_map
*map
,
6522 struct btrfs_io_geometry
*io_geom
,
6523 u64 logical
, u64
*length
)
6525 int data_stripes
= nr_data_stripes(map
);
6528 * Needs full stripe mapping.
6530 * Push stripe_nr back to the start of the full stripe For those cases
6531 * needing a full stripe, @stripe_nr is the full stripe number.
6533 * Originally we go raid56_full_stripe_start / full_stripe_len, but
6534 * that can be expensive. Here we just divide @stripe_nr with
6537 io_geom
->stripe_nr
/= data_stripes
;
6539 /* RAID[56] write or recovery. Return all stripes */
6540 io_geom
->num_stripes
= map
->num_stripes
;
6541 io_geom
->max_errors
= btrfs_chunk_max_errors(map
);
6543 /* Return the length to the full stripe end. */
6544 *length
= min(logical
+ *length
,
6545 io_geom
->raid56_full_stripe_start
+ map
->start
+
6546 btrfs_stripe_nr_to_offset(data_stripes
)) -
6548 io_geom
->stripe_index
= 0;
6549 io_geom
->stripe_offset
= 0;
6552 static void map_blocks_raid56_read(struct btrfs_chunk_map
*map
,
6553 struct btrfs_io_geometry
*io_geom
)
6555 int data_stripes
= nr_data_stripes(map
);
6557 ASSERT(io_geom
->mirror_num
<= 1);
6558 /* Just grab the data stripe directly. */
6559 io_geom
->stripe_index
= io_geom
->stripe_nr
% data_stripes
;
6560 io_geom
->stripe_nr
/= data_stripes
;
6562 /* We distribute the parity blocks across stripes. */
6563 io_geom
->stripe_index
=
6564 (io_geom
->stripe_nr
+ io_geom
->stripe_index
) % map
->num_stripes
;
6566 if (io_geom
->op
== BTRFS_MAP_READ
&& io_geom
->mirror_num
< 1)
6567 io_geom
->mirror_num
= 1;
6570 static void map_blocks_single(const struct btrfs_chunk_map
*map
,
6571 struct btrfs_io_geometry
*io_geom
)
6573 io_geom
->stripe_index
= io_geom
->stripe_nr
% map
->num_stripes
;
6574 io_geom
->stripe_nr
/= map
->num_stripes
;
6575 io_geom
->mirror_num
= io_geom
->stripe_index
+ 1;
6579 * Map one logical range to one or more physical ranges.
6581 * @length: (Mandatory) mapped length of this run.
6582 * One logical range can be split into different segments
6583 * due to factors like zones and RAID0/5/6/10 stripe
6586 * @bioc_ret: (Mandatory) returned btrfs_io_context structure.
6587 * which has one or more physical ranges (btrfs_io_stripe)
6589 * Caller should call btrfs_put_bioc() to free it after use.
6591 * @smap: (Optional) single physical range optimization.
6592 * If the map request can be fulfilled by one single
6593 * physical range, and this is parameter is not NULL,
6594 * then @bioc_ret would be NULL, and @smap would be
6597 * @mirror_num_ret: (Mandatory) returned mirror number if the original
6600 * Mirror number 0 means to choose any live mirrors.
6602 * For non-RAID56 profiles, non-zero mirror_num means
6603 * the Nth mirror. (e.g. mirror_num 1 means the first
6606 * For RAID56 profile, mirror 1 means rebuild from P and
6607 * the remaining data stripes.
6609 * For RAID6 profile, mirror > 2 means mark another
6610 * data/P stripe error and rebuild from the remaining
6613 int btrfs_map_block(struct btrfs_fs_info
*fs_info
, enum btrfs_map_op op
,
6614 u64 logical
, u64
*length
,
6615 struct btrfs_io_context
**bioc_ret
,
6616 struct btrfs_io_stripe
*smap
, int *mirror_num_ret
)
6618 struct btrfs_chunk_map
*map
;
6619 struct btrfs_io_geometry io_geom
= { 0 };
6624 struct btrfs_io_context
*bioc
= NULL
;
6625 struct btrfs_dev_replace
*dev_replace
= &fs_info
->dev_replace
;
6626 int dev_replace_is_ongoing
= 0;
6627 u16 num_alloc_stripes
;
6632 io_geom
.mirror_num
= (mirror_num_ret
? *mirror_num_ret
: 0);
6633 io_geom
.num_stripes
= 1;
6634 io_geom
.stripe_index
= 0;
6637 num_copies
= btrfs_num_copies(fs_info
, logical
, fs_info
->sectorsize
);
6638 if (io_geom
.mirror_num
> num_copies
)
6641 map
= btrfs_get_chunk_map(fs_info
, logical
, *length
);
6643 return PTR_ERR(map
);
6645 map_offset
= logical
- map
->start
;
6646 io_geom
.raid56_full_stripe_start
= (u64
)-1;
6647 max_len
= btrfs_max_io_len(map
, map_offset
, &io_geom
);
6648 *length
= min_t(u64
, map
->chunk_len
- map_offset
, max_len
);
6650 down_read(&dev_replace
->rwsem
);
6651 dev_replace_is_ongoing
= btrfs_dev_replace_is_ongoing(dev_replace
);
6653 * Hold the semaphore for read during the whole operation, write is
6654 * requested at commit time but must wait.
6656 if (!dev_replace_is_ongoing
)
6657 up_read(&dev_replace
->rwsem
);
6659 switch (map
->type
& BTRFS_BLOCK_GROUP_PROFILE_MASK
) {
6660 case BTRFS_BLOCK_GROUP_RAID0
:
6661 map_blocks_raid0(map
, &io_geom
);
6663 case BTRFS_BLOCK_GROUP_RAID1
:
6664 case BTRFS_BLOCK_GROUP_RAID1C3
:
6665 case BTRFS_BLOCK_GROUP_RAID1C4
:
6666 map_blocks_raid1(fs_info
, map
, &io_geom
, dev_replace_is_ongoing
);
6668 case BTRFS_BLOCK_GROUP_DUP
:
6669 map_blocks_dup(map
, &io_geom
);
6671 case BTRFS_BLOCK_GROUP_RAID10
:
6672 map_blocks_raid10(fs_info
, map
, &io_geom
, dev_replace_is_ongoing
);
6674 case BTRFS_BLOCK_GROUP_RAID5
:
6675 case BTRFS_BLOCK_GROUP_RAID6
:
6676 if (op
!= BTRFS_MAP_READ
|| io_geom
.mirror_num
> 1)
6677 map_blocks_raid56_write(map
, &io_geom
, logical
, length
);
6679 map_blocks_raid56_read(map
, &io_geom
);
6683 * After this, stripe_nr is the number of stripes on this
6684 * device we have to walk to find the data, and stripe_index is
6685 * the number of our device in the stripe array
6687 map_blocks_single(map
, &io_geom
);
6690 if (io_geom
.stripe_index
>= map
->num_stripes
) {
6692 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6693 io_geom
.stripe_index
, map
->num_stripes
);
6698 num_alloc_stripes
= io_geom
.num_stripes
;
6699 if (dev_replace_is_ongoing
&& dev_replace
->tgtdev
!= NULL
&&
6700 op
!= BTRFS_MAP_READ
)
6702 * For replace case, we need to add extra stripes for extra
6703 * duplicated stripes.
6705 * For both WRITE and GET_READ_MIRRORS, we may have at most
6706 * 2 more stripes (DUP types, otherwise 1).
6708 num_alloc_stripes
+= 2;
6711 * If this I/O maps to a single device, try to return the device and
6712 * physical block information on the stack instead of allocating an
6713 * I/O context structure.
6715 if (is_single_device_io(fs_info
, smap
, map
, num_alloc_stripes
, op
,
6716 io_geom
.mirror_num
)) {
6717 ret
= set_io_stripe(fs_info
, logical
, length
, smap
, map
, &io_geom
);
6719 *mirror_num_ret
= io_geom
.mirror_num
;
6724 bioc
= alloc_btrfs_io_context(fs_info
, logical
, num_alloc_stripes
);
6729 bioc
->map_type
= map
->type
;
6732 * For RAID56 full map, we need to make sure the stripes[] follows the
6733 * rule that data stripes are all ordered, then followed with P and Q
6736 * It's still mostly the same as other profiles, just with extra rotation.
6738 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
&&
6739 (op
!= BTRFS_MAP_READ
|| io_geom
.mirror_num
> 1)) {
6741 * For RAID56 @stripe_nr is already the number of full stripes
6742 * before us, which is also the rotation value (needs to modulo
6743 * with num_stripes).
6745 * In this case, we just add @stripe_nr with @i, then do the
6746 * modulo, to reduce one modulo call.
6748 bioc
->full_stripe_logical
= map
->start
+
6749 btrfs_stripe_nr_to_offset(io_geom
.stripe_nr
*
6750 nr_data_stripes(map
));
6751 for (int i
= 0; i
< io_geom
.num_stripes
; i
++) {
6752 struct btrfs_io_stripe
*dst
= &bioc
->stripes
[i
];
6755 stripe_index
= (i
+ io_geom
.stripe_nr
) % io_geom
.num_stripes
;
6756 dst
->dev
= map
->stripes
[stripe_index
].dev
;
6758 map
->stripes
[stripe_index
].physical
+
6759 io_geom
.stripe_offset
+
6760 btrfs_stripe_nr_to_offset(io_geom
.stripe_nr
);
6764 * For all other non-RAID56 profiles, just copy the target
6765 * stripe into the bioc.
6767 for (i
= 0; i
< io_geom
.num_stripes
; i
++) {
6768 ret
= set_io_stripe(fs_info
, logical
, length
,
6769 &bioc
->stripes
[i
], map
, &io_geom
);
6772 io_geom
.stripe_index
++;
6778 btrfs_put_bioc(bioc
);
6782 if (op
!= BTRFS_MAP_READ
)
6783 io_geom
.max_errors
= btrfs_chunk_max_errors(map
);
6785 if (dev_replace_is_ongoing
&& dev_replace
->tgtdev
!= NULL
&&
6786 op
!= BTRFS_MAP_READ
) {
6787 handle_ops_on_dev_replace(op
, bioc
, dev_replace
, logical
,
6788 &io_geom
.num_stripes
, &io_geom
.max_errors
);
6792 bioc
->num_stripes
= io_geom
.num_stripes
;
6793 bioc
->max_errors
= io_geom
.max_errors
;
6794 bioc
->mirror_num
= io_geom
.mirror_num
;
6797 if (dev_replace_is_ongoing
) {
6798 lockdep_assert_held(&dev_replace
->rwsem
);
6799 /* Unlock and let waiting writers proceed */
6800 up_read(&dev_replace
->rwsem
);
6802 btrfs_free_chunk_map(map
);
6806 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args
*args
,
6807 const struct btrfs_fs_devices
*fs_devices
)
6809 if (args
->fsid
== NULL
)
6811 if (memcmp(fs_devices
->metadata_uuid
, args
->fsid
, BTRFS_FSID_SIZE
) == 0)
6816 static bool dev_args_match_device(const struct btrfs_dev_lookup_args
*args
,
6817 const struct btrfs_device
*device
)
6819 if (args
->missing
) {
6820 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
) &&
6826 if (device
->devid
!= args
->devid
)
6828 if (args
->uuid
&& memcmp(device
->uuid
, args
->uuid
, BTRFS_UUID_SIZE
) != 0)
6834 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6837 * If devid and uuid are both specified, the match must be exact, otherwise
6838 * only devid is used.
6840 struct btrfs_device
*btrfs_find_device(const struct btrfs_fs_devices
*fs_devices
,
6841 const struct btrfs_dev_lookup_args
*args
)
6843 struct btrfs_device
*device
;
6844 struct btrfs_fs_devices
*seed_devs
;
6846 if (dev_args_match_fs_devices(args
, fs_devices
)) {
6847 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
) {
6848 if (dev_args_match_device(args
, device
))
6853 list_for_each_entry(seed_devs
, &fs_devices
->seed_list
, seed_list
) {
6854 if (!dev_args_match_fs_devices(args
, seed_devs
))
6856 list_for_each_entry(device
, &seed_devs
->devices
, dev_list
) {
6857 if (dev_args_match_device(args
, device
))
6865 static struct btrfs_device
*add_missing_dev(struct btrfs_fs_devices
*fs_devices
,
6866 u64 devid
, u8
*dev_uuid
)
6868 struct btrfs_device
*device
;
6869 unsigned int nofs_flag
;
6872 * We call this under the chunk_mutex, so we want to use NOFS for this
6873 * allocation, however we don't want to change btrfs_alloc_device() to
6874 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6878 nofs_flag
= memalloc_nofs_save();
6879 device
= btrfs_alloc_device(NULL
, &devid
, dev_uuid
, NULL
);
6880 memalloc_nofs_restore(nofs_flag
);
6884 list_add(&device
->dev_list
, &fs_devices
->devices
);
6885 device
->fs_devices
= fs_devices
;
6886 fs_devices
->num_devices
++;
6888 set_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
);
6889 fs_devices
->missing_devices
++;
6895 * Allocate new device struct, set up devid and UUID.
6897 * @fs_info: used only for generating a new devid, can be NULL if
6898 * devid is provided (i.e. @devid != NULL).
6899 * @devid: a pointer to devid for this device. If NULL a new devid
6901 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6903 * @path: a pointer to device path if available, NULL otherwise.
6905 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6906 * on error. Returned struct is not linked onto any lists and must be
6907 * destroyed with btrfs_free_device.
6909 struct btrfs_device
*btrfs_alloc_device(struct btrfs_fs_info
*fs_info
,
6910 const u64
*devid
, const u8
*uuid
,
6913 struct btrfs_device
*dev
;
6916 if (WARN_ON(!devid
&& !fs_info
))
6917 return ERR_PTR(-EINVAL
);
6919 dev
= kzalloc(sizeof(*dev
), GFP_KERNEL
);
6921 return ERR_PTR(-ENOMEM
);
6923 INIT_LIST_HEAD(&dev
->dev_list
);
6924 INIT_LIST_HEAD(&dev
->dev_alloc_list
);
6925 INIT_LIST_HEAD(&dev
->post_commit_list
);
6927 atomic_set(&dev
->dev_stats_ccnt
, 0);
6928 btrfs_device_data_ordered_init(dev
);
6929 extent_io_tree_init(fs_info
, &dev
->alloc_state
, IO_TREE_DEVICE_ALLOC_STATE
);
6936 ret
= find_next_devid(fs_info
, &tmp
);
6938 btrfs_free_device(dev
);
6939 return ERR_PTR(ret
);
6945 memcpy(dev
->uuid
, uuid
, BTRFS_UUID_SIZE
);
6947 generate_random_uuid(dev
->uuid
);
6950 struct rcu_string
*name
;
6952 name
= rcu_string_strdup(path
, GFP_KERNEL
);
6954 btrfs_free_device(dev
);
6955 return ERR_PTR(-ENOMEM
);
6957 rcu_assign_pointer(dev
->name
, name
);
6963 static void btrfs_report_missing_device(struct btrfs_fs_info
*fs_info
,
6964 u64 devid
, u8
*uuid
, bool error
)
6967 btrfs_err_rl(fs_info
, "devid %llu uuid %pU is missing",
6970 btrfs_warn_rl(fs_info
, "devid %llu uuid %pU is missing",
6974 u64
btrfs_calc_stripe_length(const struct btrfs_chunk_map
*map
)
6976 const int data_stripes
= calc_data_stripes(map
->type
, map
->num_stripes
);
6978 return div_u64(map
->chunk_len
, data_stripes
);
6981 #if BITS_PER_LONG == 32
6983 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
6984 * can't be accessed on 32bit systems.
6986 * This function do mount time check to reject the fs if it already has
6987 * metadata chunk beyond that limit.
6989 static int check_32bit_meta_chunk(struct btrfs_fs_info
*fs_info
,
6990 u64 logical
, u64 length
, u64 type
)
6992 if (!(type
& BTRFS_BLOCK_GROUP_METADATA
))
6995 if (logical
+ length
< MAX_LFS_FILESIZE
)
6998 btrfs_err_32bit_limit(fs_info
);
7003 * This is to give early warning for any metadata chunk reaching
7004 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
7005 * Although we can still access the metadata, it's not going to be possible
7006 * once the limit is reached.
7008 static void warn_32bit_meta_chunk(struct btrfs_fs_info
*fs_info
,
7009 u64 logical
, u64 length
, u64 type
)
7011 if (!(type
& BTRFS_BLOCK_GROUP_METADATA
))
7014 if (logical
+ length
< BTRFS_32BIT_EARLY_WARN_THRESHOLD
)
7017 btrfs_warn_32bit_limit(fs_info
);
7021 static struct btrfs_device
*handle_missing_device(struct btrfs_fs_info
*fs_info
,
7022 u64 devid
, u8
*uuid
)
7024 struct btrfs_device
*dev
;
7026 if (!btrfs_test_opt(fs_info
, DEGRADED
)) {
7027 btrfs_report_missing_device(fs_info
, devid
, uuid
, true);
7028 return ERR_PTR(-ENOENT
);
7031 dev
= add_missing_dev(fs_info
->fs_devices
, devid
, uuid
);
7033 btrfs_err(fs_info
, "failed to init missing device %llu: %ld",
7034 devid
, PTR_ERR(dev
));
7037 btrfs_report_missing_device(fs_info
, devid
, uuid
, false);
7042 static int read_one_chunk(struct btrfs_key
*key
, struct extent_buffer
*leaf
,
7043 struct btrfs_chunk
*chunk
)
7045 BTRFS_DEV_LOOKUP_ARGS(args
);
7046 struct btrfs_fs_info
*fs_info
= leaf
->fs_info
;
7047 struct btrfs_chunk_map
*map
;
7052 u8 uuid
[BTRFS_UUID_SIZE
];
7058 logical
= key
->offset
;
7059 length
= btrfs_chunk_length(leaf
, chunk
);
7060 type
= btrfs_chunk_type(leaf
, chunk
);
7061 index
= btrfs_bg_flags_to_raid_index(type
);
7062 num_stripes
= btrfs_chunk_num_stripes(leaf
, chunk
);
7064 #if BITS_PER_LONG == 32
7065 ret
= check_32bit_meta_chunk(fs_info
, logical
, length
, type
);
7068 warn_32bit_meta_chunk(fs_info
, logical
, length
, type
);
7072 * Only need to verify chunk item if we're reading from sys chunk array,
7073 * as chunk item in tree block is already verified by tree-checker.
7075 if (leaf
->start
== BTRFS_SUPER_INFO_OFFSET
) {
7076 ret
= btrfs_check_chunk_valid(leaf
, chunk
, logical
);
7081 map
= btrfs_find_chunk_map(fs_info
, logical
, 1);
7083 /* already mapped? */
7084 if (map
&& map
->start
<= logical
&& map
->start
+ map
->chunk_len
> logical
) {
7085 btrfs_free_chunk_map(map
);
7088 btrfs_free_chunk_map(map
);
7091 map
= btrfs_alloc_chunk_map(num_stripes
, GFP_NOFS
);
7095 map
->start
= logical
;
7096 map
->chunk_len
= length
;
7097 map
->num_stripes
= num_stripes
;
7098 map
->io_width
= btrfs_chunk_io_width(leaf
, chunk
);
7099 map
->io_align
= btrfs_chunk_io_align(leaf
, chunk
);
7102 * We can't use the sub_stripes value, as for profiles other than
7103 * RAID10, they may have 0 as sub_stripes for filesystems created by
7104 * older mkfs (<v5.4).
7105 * In that case, it can cause divide-by-zero errors later.
7106 * Since currently sub_stripes is fixed for each profile, let's
7107 * use the trusted value instead.
7109 map
->sub_stripes
= btrfs_raid_array
[index
].sub_stripes
;
7110 map
->verified_stripes
= 0;
7111 map
->stripe_size
= btrfs_calc_stripe_length(map
);
7112 for (i
= 0; i
< num_stripes
; i
++) {
7113 map
->stripes
[i
].physical
=
7114 btrfs_stripe_offset_nr(leaf
, chunk
, i
);
7115 devid
= btrfs_stripe_devid_nr(leaf
, chunk
, i
);
7117 read_extent_buffer(leaf
, uuid
, (unsigned long)
7118 btrfs_stripe_dev_uuid_nr(chunk
, i
),
7121 map
->stripes
[i
].dev
= btrfs_find_device(fs_info
->fs_devices
, &args
);
7122 if (!map
->stripes
[i
].dev
) {
7123 map
->stripes
[i
].dev
= handle_missing_device(fs_info
,
7125 if (IS_ERR(map
->stripes
[i
].dev
)) {
7126 ret
= PTR_ERR(map
->stripes
[i
].dev
);
7127 btrfs_free_chunk_map(map
);
7132 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA
,
7133 &(map
->stripes
[i
].dev
->dev_state
));
7136 ret
= btrfs_add_chunk_map(fs_info
, map
);
7139 "failed to add chunk map, start=%llu len=%llu: %d",
7140 map
->start
, map
->chunk_len
, ret
);
7146 static void fill_device_from_item(struct extent_buffer
*leaf
,
7147 struct btrfs_dev_item
*dev_item
,
7148 struct btrfs_device
*device
)
7152 device
->devid
= btrfs_device_id(leaf
, dev_item
);
7153 device
->disk_total_bytes
= btrfs_device_total_bytes(leaf
, dev_item
);
7154 device
->total_bytes
= device
->disk_total_bytes
;
7155 device
->commit_total_bytes
= device
->disk_total_bytes
;
7156 device
->bytes_used
= btrfs_device_bytes_used(leaf
, dev_item
);
7157 device
->commit_bytes_used
= device
->bytes_used
;
7158 device
->type
= btrfs_device_type(leaf
, dev_item
);
7159 device
->io_align
= btrfs_device_io_align(leaf
, dev_item
);
7160 device
->io_width
= btrfs_device_io_width(leaf
, dev_item
);
7161 device
->sector_size
= btrfs_device_sector_size(leaf
, dev_item
);
7162 WARN_ON(device
->devid
== BTRFS_DEV_REPLACE_DEVID
);
7163 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
);
7165 ptr
= btrfs_device_uuid(dev_item
);
7166 read_extent_buffer(leaf
, device
->uuid
, ptr
, BTRFS_UUID_SIZE
);
7169 static struct btrfs_fs_devices
*open_seed_devices(struct btrfs_fs_info
*fs_info
,
7172 struct btrfs_fs_devices
*fs_devices
;
7175 lockdep_assert_held(&uuid_mutex
);
7178 /* This will match only for multi-device seed fs */
7179 list_for_each_entry(fs_devices
, &fs_info
->fs_devices
->seed_list
, seed_list
)
7180 if (!memcmp(fs_devices
->fsid
, fsid
, BTRFS_FSID_SIZE
))
7184 fs_devices
= find_fsid(fsid
, NULL
);
7186 if (!btrfs_test_opt(fs_info
, DEGRADED
))
7187 return ERR_PTR(-ENOENT
);
7189 fs_devices
= alloc_fs_devices(fsid
);
7190 if (IS_ERR(fs_devices
))
7193 fs_devices
->seeding
= true;
7194 fs_devices
->opened
= 1;
7199 * Upon first call for a seed fs fsid, just create a private copy of the
7200 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7202 fs_devices
= clone_fs_devices(fs_devices
);
7203 if (IS_ERR(fs_devices
))
7206 ret
= open_fs_devices(fs_devices
, BLK_OPEN_READ
, fs_info
->bdev_holder
);
7208 free_fs_devices(fs_devices
);
7209 return ERR_PTR(ret
);
7212 if (!fs_devices
->seeding
) {
7213 close_fs_devices(fs_devices
);
7214 free_fs_devices(fs_devices
);
7215 return ERR_PTR(-EINVAL
);
7218 list_add(&fs_devices
->seed_list
, &fs_info
->fs_devices
->seed_list
);
7223 static int read_one_dev(struct extent_buffer
*leaf
,
7224 struct btrfs_dev_item
*dev_item
)
7226 BTRFS_DEV_LOOKUP_ARGS(args
);
7227 struct btrfs_fs_info
*fs_info
= leaf
->fs_info
;
7228 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
7229 struct btrfs_device
*device
;
7232 u8 fs_uuid
[BTRFS_FSID_SIZE
];
7233 u8 dev_uuid
[BTRFS_UUID_SIZE
];
7235 devid
= btrfs_device_id(leaf
, dev_item
);
7237 read_extent_buffer(leaf
, dev_uuid
, btrfs_device_uuid(dev_item
),
7239 read_extent_buffer(leaf
, fs_uuid
, btrfs_device_fsid(dev_item
),
7241 args
.uuid
= dev_uuid
;
7242 args
.fsid
= fs_uuid
;
7244 if (memcmp(fs_uuid
, fs_devices
->metadata_uuid
, BTRFS_FSID_SIZE
)) {
7245 fs_devices
= open_seed_devices(fs_info
, fs_uuid
);
7246 if (IS_ERR(fs_devices
))
7247 return PTR_ERR(fs_devices
);
7250 device
= btrfs_find_device(fs_info
->fs_devices
, &args
);
7252 if (!btrfs_test_opt(fs_info
, DEGRADED
)) {
7253 btrfs_report_missing_device(fs_info
, devid
,
7258 device
= add_missing_dev(fs_devices
, devid
, dev_uuid
);
7259 if (IS_ERR(device
)) {
7261 "failed to add missing dev %llu: %ld",
7262 devid
, PTR_ERR(device
));
7263 return PTR_ERR(device
);
7265 btrfs_report_missing_device(fs_info
, devid
, dev_uuid
, false);
7267 if (!device
->bdev
) {
7268 if (!btrfs_test_opt(fs_info
, DEGRADED
)) {
7269 btrfs_report_missing_device(fs_info
,
7270 devid
, dev_uuid
, true);
7273 btrfs_report_missing_device(fs_info
, devid
,
7277 if (!device
->bdev
&&
7278 !test_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
)) {
7280 * this happens when a device that was properly setup
7281 * in the device info lists suddenly goes bad.
7282 * device->bdev is NULL, and so we have to set
7283 * device->missing to one here
7285 device
->fs_devices
->missing_devices
++;
7286 set_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
);
7289 /* Move the device to its own fs_devices */
7290 if (device
->fs_devices
!= fs_devices
) {
7291 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING
,
7292 &device
->dev_state
));
7294 list_move(&device
->dev_list
, &fs_devices
->devices
);
7295 device
->fs_devices
->num_devices
--;
7296 fs_devices
->num_devices
++;
7298 device
->fs_devices
->missing_devices
--;
7299 fs_devices
->missing_devices
++;
7301 device
->fs_devices
= fs_devices
;
7305 if (device
->fs_devices
!= fs_info
->fs_devices
) {
7306 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
));
7307 if (device
->generation
!=
7308 btrfs_device_generation(leaf
, dev_item
))
7312 fill_device_from_item(leaf
, dev_item
, device
);
7314 u64 max_total_bytes
= bdev_nr_bytes(device
->bdev
);
7316 if (device
->total_bytes
> max_total_bytes
) {
7318 "device total_bytes should be at most %llu but found %llu",
7319 max_total_bytes
, device
->total_bytes
);
7323 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
);
7324 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
) &&
7325 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
)) {
7326 device
->fs_devices
->total_rw_bytes
+= device
->total_bytes
;
7327 atomic64_add(device
->total_bytes
- device
->bytes_used
,
7328 &fs_info
->free_chunk_space
);
7334 int btrfs_read_sys_array(struct btrfs_fs_info
*fs_info
)
7336 struct btrfs_super_block
*super_copy
= fs_info
->super_copy
;
7337 struct extent_buffer
*sb
;
7338 struct btrfs_disk_key
*disk_key
;
7339 struct btrfs_chunk
*chunk
;
7341 unsigned long sb_array_offset
;
7348 struct btrfs_key key
;
7350 ASSERT(BTRFS_SUPER_INFO_SIZE
<= fs_info
->nodesize
);
7353 * We allocated a dummy extent, just to use extent buffer accessors.
7354 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
7355 * that's fine, we will not go beyond system chunk array anyway.
7357 sb
= alloc_dummy_extent_buffer(fs_info
, BTRFS_SUPER_INFO_OFFSET
);
7360 set_extent_buffer_uptodate(sb
);
7362 write_extent_buffer(sb
, super_copy
, 0, BTRFS_SUPER_INFO_SIZE
);
7363 array_size
= btrfs_super_sys_array_size(super_copy
);
7365 array_ptr
= super_copy
->sys_chunk_array
;
7366 sb_array_offset
= offsetof(struct btrfs_super_block
, sys_chunk_array
);
7369 while (cur_offset
< array_size
) {
7370 disk_key
= (struct btrfs_disk_key
*)array_ptr
;
7371 len
= sizeof(*disk_key
);
7372 if (cur_offset
+ len
> array_size
)
7373 goto out_short_read
;
7375 btrfs_disk_key_to_cpu(&key
, disk_key
);
7378 sb_array_offset
+= len
;
7381 if (key
.type
!= BTRFS_CHUNK_ITEM_KEY
) {
7383 "unexpected item type %u in sys_array at offset %u",
7384 (u32
)key
.type
, cur_offset
);
7389 chunk
= (struct btrfs_chunk
*)sb_array_offset
;
7391 * At least one btrfs_chunk with one stripe must be present,
7392 * exact stripe count check comes afterwards
7394 len
= btrfs_chunk_item_size(1);
7395 if (cur_offset
+ len
> array_size
)
7396 goto out_short_read
;
7398 num_stripes
= btrfs_chunk_num_stripes(sb
, chunk
);
7401 "invalid number of stripes %u in sys_array at offset %u",
7402 num_stripes
, cur_offset
);
7407 type
= btrfs_chunk_type(sb
, chunk
);
7408 if ((type
& BTRFS_BLOCK_GROUP_SYSTEM
) == 0) {
7410 "invalid chunk type %llu in sys_array at offset %u",
7416 len
= btrfs_chunk_item_size(num_stripes
);
7417 if (cur_offset
+ len
> array_size
)
7418 goto out_short_read
;
7420 ret
= read_one_chunk(&key
, sb
, chunk
);
7425 sb_array_offset
+= len
;
7428 clear_extent_buffer_uptodate(sb
);
7429 free_extent_buffer_stale(sb
);
7433 btrfs_err(fs_info
, "sys_array too short to read %u bytes at offset %u",
7435 clear_extent_buffer_uptodate(sb
);
7436 free_extent_buffer_stale(sb
);
7441 * Check if all chunks in the fs are OK for read-write degraded mount
7443 * If the @failing_dev is specified, it's accounted as missing.
7445 * Return true if all chunks meet the minimal RW mount requirements.
7446 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7448 bool btrfs_check_rw_degradable(struct btrfs_fs_info
*fs_info
,
7449 struct btrfs_device
*failing_dev
)
7451 struct btrfs_chunk_map
*map
;
7455 map
= btrfs_find_chunk_map(fs_info
, 0, U64_MAX
);
7456 /* No chunk at all? Return false anyway */
7467 btrfs_get_num_tolerated_disk_barrier_failures(
7469 for (i
= 0; i
< map
->num_stripes
; i
++) {
7470 struct btrfs_device
*dev
= map
->stripes
[i
].dev
;
7472 if (!dev
|| !dev
->bdev
||
7473 test_bit(BTRFS_DEV_STATE_MISSING
, &dev
->dev_state
) ||
7474 dev
->last_flush_error
)
7476 else if (failing_dev
&& failing_dev
== dev
)
7479 if (missing
> max_tolerated
) {
7482 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7483 map
->start
, missing
, max_tolerated
);
7484 btrfs_free_chunk_map(map
);
7488 next_start
= map
->start
+ map
->chunk_len
;
7489 btrfs_free_chunk_map(map
);
7491 map
= btrfs_find_chunk_map(fs_info
, next_start
, U64_MAX
- next_start
);
7497 static void readahead_tree_node_children(struct extent_buffer
*node
)
7500 const int nr_items
= btrfs_header_nritems(node
);
7502 for (i
= 0; i
< nr_items
; i
++)
7503 btrfs_readahead_node_child(node
, i
);
7506 int btrfs_read_chunk_tree(struct btrfs_fs_info
*fs_info
)
7508 struct btrfs_root
*root
= fs_info
->chunk_root
;
7509 struct btrfs_path
*path
;
7510 struct extent_buffer
*leaf
;
7511 struct btrfs_key key
;
7512 struct btrfs_key found_key
;
7517 u64 last_ra_node
= 0;
7519 path
= btrfs_alloc_path();
7524 * uuid_mutex is needed only if we are mounting a sprout FS
7525 * otherwise we don't need it.
7527 mutex_lock(&uuid_mutex
);
7530 * It is possible for mount and umount to race in such a way that
7531 * we execute this code path, but open_fs_devices failed to clear
7532 * total_rw_bytes. We certainly want it cleared before reading the
7533 * device items, so clear it here.
7535 fs_info
->fs_devices
->total_rw_bytes
= 0;
7538 * Lockdep complains about possible circular locking dependency between
7539 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7540 * used for freeze procection of a fs (struct super_block.s_writers),
7541 * which we take when starting a transaction, and extent buffers of the
7542 * chunk tree if we call read_one_dev() while holding a lock on an
7543 * extent buffer of the chunk tree. Since we are mounting the filesystem
7544 * and at this point there can't be any concurrent task modifying the
7545 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7547 ASSERT(!test_bit(BTRFS_FS_OPEN
, &fs_info
->flags
));
7548 path
->skip_locking
= 1;
7551 * Read all device items, and then all the chunk items. All
7552 * device items are found before any chunk item (their object id
7553 * is smaller than the lowest possible object id for a chunk
7554 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7556 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
7559 btrfs_for_each_slot(root
, &key
, &found_key
, path
, iter_ret
) {
7560 struct extent_buffer
*node
= path
->nodes
[1];
7562 leaf
= path
->nodes
[0];
7563 slot
= path
->slots
[0];
7566 if (last_ra_node
!= node
->start
) {
7567 readahead_tree_node_children(node
);
7568 last_ra_node
= node
->start
;
7571 if (found_key
.type
== BTRFS_DEV_ITEM_KEY
) {
7572 struct btrfs_dev_item
*dev_item
;
7573 dev_item
= btrfs_item_ptr(leaf
, slot
,
7574 struct btrfs_dev_item
);
7575 ret
= read_one_dev(leaf
, dev_item
);
7579 } else if (found_key
.type
== BTRFS_CHUNK_ITEM_KEY
) {
7580 struct btrfs_chunk
*chunk
;
7583 * We are only called at mount time, so no need to take
7584 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7585 * we always lock first fs_info->chunk_mutex before
7586 * acquiring any locks on the chunk tree. This is a
7587 * requirement for chunk allocation, see the comment on
7588 * top of btrfs_chunk_alloc() for details.
7590 chunk
= btrfs_item_ptr(leaf
, slot
, struct btrfs_chunk
);
7591 ret
= read_one_chunk(&found_key
, leaf
, chunk
);
7596 /* Catch error found during iteration */
7603 * After loading chunk tree, we've got all device information,
7604 * do another round of validation checks.
7606 if (total_dev
!= fs_info
->fs_devices
->total_devices
) {
7608 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7609 btrfs_super_num_devices(fs_info
->super_copy
),
7611 fs_info
->fs_devices
->total_devices
= total_dev
;
7612 btrfs_set_super_num_devices(fs_info
->super_copy
, total_dev
);
7614 if (btrfs_super_total_bytes(fs_info
->super_copy
) <
7615 fs_info
->fs_devices
->total_rw_bytes
) {
7617 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7618 btrfs_super_total_bytes(fs_info
->super_copy
),
7619 fs_info
->fs_devices
->total_rw_bytes
);
7625 mutex_unlock(&uuid_mutex
);
7627 btrfs_free_path(path
);
7631 int btrfs_init_devices_late(struct btrfs_fs_info
*fs_info
)
7633 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
, *seed_devs
;
7634 struct btrfs_device
*device
;
7637 fs_devices
->fs_info
= fs_info
;
7639 mutex_lock(&fs_devices
->device_list_mutex
);
7640 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
)
7641 device
->fs_info
= fs_info
;
7643 list_for_each_entry(seed_devs
, &fs_devices
->seed_list
, seed_list
) {
7644 list_for_each_entry(device
, &seed_devs
->devices
, dev_list
) {
7645 device
->fs_info
= fs_info
;
7646 ret
= btrfs_get_dev_zone_info(device
, false);
7651 seed_devs
->fs_info
= fs_info
;
7653 mutex_unlock(&fs_devices
->device_list_mutex
);
7658 static u64
btrfs_dev_stats_value(const struct extent_buffer
*eb
,
7659 const struct btrfs_dev_stats_item
*ptr
,
7664 read_extent_buffer(eb
, &val
,
7665 offsetof(struct btrfs_dev_stats_item
, values
) +
7666 ((unsigned long)ptr
) + (index
* sizeof(u64
)),
7671 static void btrfs_set_dev_stats_value(struct extent_buffer
*eb
,
7672 struct btrfs_dev_stats_item
*ptr
,
7675 write_extent_buffer(eb
, &val
,
7676 offsetof(struct btrfs_dev_stats_item
, values
) +
7677 ((unsigned long)ptr
) + (index
* sizeof(u64
)),
7681 static int btrfs_device_init_dev_stats(struct btrfs_device
*device
,
7682 struct btrfs_path
*path
)
7684 struct btrfs_dev_stats_item
*ptr
;
7685 struct extent_buffer
*eb
;
7686 struct btrfs_key key
;
7690 if (!device
->fs_info
->dev_root
)
7693 key
.objectid
= BTRFS_DEV_STATS_OBJECTID
;
7694 key
.type
= BTRFS_PERSISTENT_ITEM_KEY
;
7695 key
.offset
= device
->devid
;
7696 ret
= btrfs_search_slot(NULL
, device
->fs_info
->dev_root
, &key
, path
, 0, 0);
7698 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++)
7699 btrfs_dev_stat_set(device
, i
, 0);
7700 device
->dev_stats_valid
= 1;
7701 btrfs_release_path(path
);
7702 return ret
< 0 ? ret
: 0;
7704 slot
= path
->slots
[0];
7705 eb
= path
->nodes
[0];
7706 item_size
= btrfs_item_size(eb
, slot
);
7708 ptr
= btrfs_item_ptr(eb
, slot
, struct btrfs_dev_stats_item
);
7710 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++) {
7711 if (item_size
>= (1 + i
) * sizeof(__le64
))
7712 btrfs_dev_stat_set(device
, i
,
7713 btrfs_dev_stats_value(eb
, ptr
, i
));
7715 btrfs_dev_stat_set(device
, i
, 0);
7718 device
->dev_stats_valid
= 1;
7719 btrfs_dev_stat_print_on_load(device
);
7720 btrfs_release_path(path
);
7725 int btrfs_init_dev_stats(struct btrfs_fs_info
*fs_info
)
7727 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
, *seed_devs
;
7728 struct btrfs_device
*device
;
7729 struct btrfs_path
*path
= NULL
;
7732 path
= btrfs_alloc_path();
7736 mutex_lock(&fs_devices
->device_list_mutex
);
7737 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
) {
7738 ret
= btrfs_device_init_dev_stats(device
, path
);
7742 list_for_each_entry(seed_devs
, &fs_devices
->seed_list
, seed_list
) {
7743 list_for_each_entry(device
, &seed_devs
->devices
, dev_list
) {
7744 ret
= btrfs_device_init_dev_stats(device
, path
);
7750 mutex_unlock(&fs_devices
->device_list_mutex
);
7752 btrfs_free_path(path
);
7756 static int update_dev_stat_item(struct btrfs_trans_handle
*trans
,
7757 struct btrfs_device
*device
)
7759 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
7760 struct btrfs_root
*dev_root
= fs_info
->dev_root
;
7761 struct btrfs_path
*path
;
7762 struct btrfs_key key
;
7763 struct extent_buffer
*eb
;
7764 struct btrfs_dev_stats_item
*ptr
;
7768 key
.objectid
= BTRFS_DEV_STATS_OBJECTID
;
7769 key
.type
= BTRFS_PERSISTENT_ITEM_KEY
;
7770 key
.offset
= device
->devid
;
7772 path
= btrfs_alloc_path();
7775 ret
= btrfs_search_slot(trans
, dev_root
, &key
, path
, -1, 1);
7777 btrfs_warn_in_rcu(fs_info
,
7778 "error %d while searching for dev_stats item for device %s",
7779 ret
, btrfs_dev_name(device
));
7784 btrfs_item_size(path
->nodes
[0], path
->slots
[0]) < sizeof(*ptr
)) {
7785 /* need to delete old one and insert a new one */
7786 ret
= btrfs_del_item(trans
, dev_root
, path
);
7788 btrfs_warn_in_rcu(fs_info
,
7789 "delete too small dev_stats item for device %s failed %d",
7790 btrfs_dev_name(device
), ret
);
7797 /* need to insert a new item */
7798 btrfs_release_path(path
);
7799 ret
= btrfs_insert_empty_item(trans
, dev_root
, path
,
7800 &key
, sizeof(*ptr
));
7802 btrfs_warn_in_rcu(fs_info
,
7803 "insert dev_stats item for device %s failed %d",
7804 btrfs_dev_name(device
), ret
);
7809 eb
= path
->nodes
[0];
7810 ptr
= btrfs_item_ptr(eb
, path
->slots
[0], struct btrfs_dev_stats_item
);
7811 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++)
7812 btrfs_set_dev_stats_value(eb
, ptr
, i
,
7813 btrfs_dev_stat_read(device
, i
));
7814 btrfs_mark_buffer_dirty(trans
, eb
);
7817 btrfs_free_path(path
);
7822 * called from commit_transaction. Writes all changed device stats to disk.
7824 int btrfs_run_dev_stats(struct btrfs_trans_handle
*trans
)
7826 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
7827 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
7828 struct btrfs_device
*device
;
7832 mutex_lock(&fs_devices
->device_list_mutex
);
7833 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
) {
7834 stats_cnt
= atomic_read(&device
->dev_stats_ccnt
);
7835 if (!device
->dev_stats_valid
|| stats_cnt
== 0)
7840 * There is a LOAD-LOAD control dependency between the value of
7841 * dev_stats_ccnt and updating the on-disk values which requires
7842 * reading the in-memory counters. Such control dependencies
7843 * require explicit read memory barriers.
7845 * This memory barriers pairs with smp_mb__before_atomic in
7846 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7847 * barrier implied by atomic_xchg in
7848 * btrfs_dev_stats_read_and_reset
7852 ret
= update_dev_stat_item(trans
, device
);
7854 atomic_sub(stats_cnt
, &device
->dev_stats_ccnt
);
7856 mutex_unlock(&fs_devices
->device_list_mutex
);
7861 void btrfs_dev_stat_inc_and_print(struct btrfs_device
*dev
, int index
)
7863 btrfs_dev_stat_inc(dev
, index
);
7865 if (!dev
->dev_stats_valid
)
7867 btrfs_err_rl_in_rcu(dev
->fs_info
,
7868 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7869 btrfs_dev_name(dev
),
7870 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_WRITE_ERRS
),
7871 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_READ_ERRS
),
7872 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_FLUSH_ERRS
),
7873 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_CORRUPTION_ERRS
),
7874 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_GENERATION_ERRS
));
7877 static void btrfs_dev_stat_print_on_load(struct btrfs_device
*dev
)
7881 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++)
7882 if (btrfs_dev_stat_read(dev
, i
) != 0)
7884 if (i
== BTRFS_DEV_STAT_VALUES_MAX
)
7885 return; /* all values == 0, suppress message */
7887 btrfs_info_in_rcu(dev
->fs_info
,
7888 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7889 btrfs_dev_name(dev
),
7890 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_WRITE_ERRS
),
7891 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_READ_ERRS
),
7892 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_FLUSH_ERRS
),
7893 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_CORRUPTION_ERRS
),
7894 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_GENERATION_ERRS
));
7897 int btrfs_get_dev_stats(struct btrfs_fs_info
*fs_info
,
7898 struct btrfs_ioctl_get_dev_stats
*stats
)
7900 BTRFS_DEV_LOOKUP_ARGS(args
);
7901 struct btrfs_device
*dev
;
7902 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
7905 mutex_lock(&fs_devices
->device_list_mutex
);
7906 args
.devid
= stats
->devid
;
7907 dev
= btrfs_find_device(fs_info
->fs_devices
, &args
);
7908 mutex_unlock(&fs_devices
->device_list_mutex
);
7911 btrfs_warn(fs_info
, "get dev_stats failed, device not found");
7913 } else if (!dev
->dev_stats_valid
) {
7914 btrfs_warn(fs_info
, "get dev_stats failed, not yet valid");
7916 } else if (stats
->flags
& BTRFS_DEV_STATS_RESET
) {
7917 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++) {
7918 if (stats
->nr_items
> i
)
7920 btrfs_dev_stat_read_and_reset(dev
, i
);
7922 btrfs_dev_stat_set(dev
, i
, 0);
7924 btrfs_info(fs_info
, "device stats zeroed by %s (%d)",
7925 current
->comm
, task_pid_nr(current
));
7927 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++)
7928 if (stats
->nr_items
> i
)
7929 stats
->values
[i
] = btrfs_dev_stat_read(dev
, i
);
7931 if (stats
->nr_items
> BTRFS_DEV_STAT_VALUES_MAX
)
7932 stats
->nr_items
= BTRFS_DEV_STAT_VALUES_MAX
;
7937 * Update the size and bytes used for each device where it changed. This is
7938 * delayed since we would otherwise get errors while writing out the
7941 * Must be invoked during transaction commit.
7943 void btrfs_commit_device_sizes(struct btrfs_transaction
*trans
)
7945 struct btrfs_device
*curr
, *next
;
7947 ASSERT(trans
->state
== TRANS_STATE_COMMIT_DOING
);
7949 if (list_empty(&trans
->dev_update_list
))
7953 * We don't need the device_list_mutex here. This list is owned by the
7954 * transaction and the transaction must complete before the device is
7957 mutex_lock(&trans
->fs_info
->chunk_mutex
);
7958 list_for_each_entry_safe(curr
, next
, &trans
->dev_update_list
,
7960 list_del_init(&curr
->post_commit_list
);
7961 curr
->commit_total_bytes
= curr
->disk_total_bytes
;
7962 curr
->commit_bytes_used
= curr
->bytes_used
;
7964 mutex_unlock(&trans
->fs_info
->chunk_mutex
);
7968 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7970 int btrfs_bg_type_to_factor(u64 flags
)
7972 const int index
= btrfs_bg_flags_to_raid_index(flags
);
7974 return btrfs_raid_array
[index
].ncopies
;
7979 static int verify_one_dev_extent(struct btrfs_fs_info
*fs_info
,
7980 u64 chunk_offset
, u64 devid
,
7981 u64 physical_offset
, u64 physical_len
)
7983 struct btrfs_dev_lookup_args args
= { .devid
= devid
};
7984 struct btrfs_chunk_map
*map
;
7985 struct btrfs_device
*dev
;
7991 map
= btrfs_find_chunk_map(fs_info
, chunk_offset
, 1);
7994 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7995 physical_offset
, devid
);
8000 stripe_len
= btrfs_calc_stripe_length(map
);
8001 if (physical_len
!= stripe_len
) {
8003 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
8004 physical_offset
, devid
, map
->start
, physical_len
,
8011 * Very old mkfs.btrfs (before v4.1) will not respect the reserved
8012 * space. Although kernel can handle it without problem, better to warn
8015 if (physical_offset
< BTRFS_DEVICE_RANGE_RESERVED
)
8017 "devid %llu physical %llu len %llu inside the reserved space",
8018 devid
, physical_offset
, physical_len
);
8020 for (i
= 0; i
< map
->num_stripes
; i
++) {
8021 if (map
->stripes
[i
].dev
->devid
== devid
&&
8022 map
->stripes
[i
].physical
== physical_offset
) {
8024 if (map
->verified_stripes
>= map
->num_stripes
) {
8026 "too many dev extents for chunk %llu found",
8031 map
->verified_stripes
++;
8037 "dev extent physical offset %llu devid %llu has no corresponding chunk",
8038 physical_offset
, devid
);
8042 /* Make sure no dev extent is beyond device boundary */
8043 dev
= btrfs_find_device(fs_info
->fs_devices
, &args
);
8045 btrfs_err(fs_info
, "failed to find devid %llu", devid
);
8050 if (physical_offset
+ physical_len
> dev
->disk_total_bytes
) {
8052 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
8053 devid
, physical_offset
, physical_len
,
8054 dev
->disk_total_bytes
);
8059 if (dev
->zone_info
) {
8060 u64 zone_size
= dev
->zone_info
->zone_size
;
8062 if (!IS_ALIGNED(physical_offset
, zone_size
) ||
8063 !IS_ALIGNED(physical_len
, zone_size
)) {
8065 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
8066 devid
, physical_offset
, physical_len
);
8073 btrfs_free_chunk_map(map
);
8077 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info
*fs_info
)
8079 struct rb_node
*node
;
8082 read_lock(&fs_info
->mapping_tree_lock
);
8083 for (node
= rb_first_cached(&fs_info
->mapping_tree
); node
; node
= rb_next(node
)) {
8084 struct btrfs_chunk_map
*map
;
8086 map
= rb_entry(node
, struct btrfs_chunk_map
, rb_node
);
8087 if (map
->num_stripes
!= map
->verified_stripes
) {
8089 "chunk %llu has missing dev extent, have %d expect %d",
8090 map
->start
, map
->verified_stripes
, map
->num_stripes
);
8096 read_unlock(&fs_info
->mapping_tree_lock
);
8101 * Ensure that all dev extents are mapped to correct chunk, otherwise
8102 * later chunk allocation/free would cause unexpected behavior.
8104 * NOTE: This will iterate through the whole device tree, which should be of
8105 * the same size level as the chunk tree. This slightly increases mount time.
8107 int btrfs_verify_dev_extents(struct btrfs_fs_info
*fs_info
)
8109 struct btrfs_path
*path
;
8110 struct btrfs_root
*root
= fs_info
->dev_root
;
8111 struct btrfs_key key
;
8113 u64 prev_dev_ext_end
= 0;
8117 * We don't have a dev_root because we mounted with ignorebadroots and
8118 * failed to load the root, so we want to skip the verification in this
8121 * However if the dev root is fine, but the tree itself is corrupted
8122 * we'd still fail to mount. This verification is only to make sure
8123 * writes can happen safely, so instead just bypass this check
8124 * completely in the case of IGNOREBADROOTS.
8126 if (btrfs_test_opt(fs_info
, IGNOREBADROOTS
))
8130 key
.type
= BTRFS_DEV_EXTENT_KEY
;
8133 path
= btrfs_alloc_path();
8137 path
->reada
= READA_FORWARD
;
8138 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
8142 if (path
->slots
[0] >= btrfs_header_nritems(path
->nodes
[0])) {
8143 ret
= btrfs_next_leaf(root
, path
);
8146 /* No dev extents at all? Not good */
8153 struct extent_buffer
*leaf
= path
->nodes
[0];
8154 struct btrfs_dev_extent
*dext
;
8155 int slot
= path
->slots
[0];
8157 u64 physical_offset
;
8161 btrfs_item_key_to_cpu(leaf
, &key
, slot
);
8162 if (key
.type
!= BTRFS_DEV_EXTENT_KEY
)
8164 devid
= key
.objectid
;
8165 physical_offset
= key
.offset
;
8167 dext
= btrfs_item_ptr(leaf
, slot
, struct btrfs_dev_extent
);
8168 chunk_offset
= btrfs_dev_extent_chunk_offset(leaf
, dext
);
8169 physical_len
= btrfs_dev_extent_length(leaf
, dext
);
8171 /* Check if this dev extent overlaps with the previous one */
8172 if (devid
== prev_devid
&& physical_offset
< prev_dev_ext_end
) {
8174 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8175 devid
, physical_offset
, prev_dev_ext_end
);
8180 ret
= verify_one_dev_extent(fs_info
, chunk_offset
, devid
,
8181 physical_offset
, physical_len
);
8185 prev_dev_ext_end
= physical_offset
+ physical_len
;
8187 ret
= btrfs_next_item(root
, path
);
8196 /* Ensure all chunks have corresponding dev extents */
8197 ret
= verify_chunk_dev_extent_mapping(fs_info
);
8199 btrfs_free_path(path
);
8204 * Check whether the given block group or device is pinned by any inode being
8205 * used as a swapfile.
8207 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info
*fs_info
, void *ptr
)
8209 struct btrfs_swapfile_pin
*sp
;
8210 struct rb_node
*node
;
8212 spin_lock(&fs_info
->swapfile_pins_lock
);
8213 node
= fs_info
->swapfile_pins
.rb_node
;
8215 sp
= rb_entry(node
, struct btrfs_swapfile_pin
, node
);
8217 node
= node
->rb_left
;
8218 else if (ptr
> sp
->ptr
)
8219 node
= node
->rb_right
;
8223 spin_unlock(&fs_info
->swapfile_pins_lock
);
8224 return node
!= NULL
;
8227 static int relocating_repair_kthread(void *data
)
8229 struct btrfs_block_group
*cache
= data
;
8230 struct btrfs_fs_info
*fs_info
= cache
->fs_info
;
8234 target
= cache
->start
;
8235 btrfs_put_block_group(cache
);
8237 sb_start_write(fs_info
->sb
);
8238 if (!btrfs_exclop_start(fs_info
, BTRFS_EXCLOP_BALANCE
)) {
8240 "zoned: skip relocating block group %llu to repair: EBUSY",
8242 sb_end_write(fs_info
->sb
);
8246 mutex_lock(&fs_info
->reclaim_bgs_lock
);
8248 /* Ensure block group still exists */
8249 cache
= btrfs_lookup_block_group(fs_info
, target
);
8253 if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR
, &cache
->runtime_flags
))
8256 ret
= btrfs_may_alloc_data_chunk(fs_info
, target
);
8261 "zoned: relocating block group %llu to repair IO failure",
8263 ret
= btrfs_relocate_chunk(fs_info
, target
);
8267 btrfs_put_block_group(cache
);
8268 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
8269 btrfs_exclop_finish(fs_info
);
8270 sb_end_write(fs_info
->sb
);
8275 bool btrfs_repair_one_zone(struct btrfs_fs_info
*fs_info
, u64 logical
)
8277 struct btrfs_block_group
*cache
;
8279 if (!btrfs_is_zoned(fs_info
))
8282 /* Do not attempt to repair in degraded state */
8283 if (btrfs_test_opt(fs_info
, DEGRADED
))
8286 cache
= btrfs_lookup_block_group(fs_info
, logical
);
8290 if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR
, &cache
->runtime_flags
)) {
8291 btrfs_put_block_group(cache
);
8295 kthread_run(relocating_repair_kthread
, cache
,
8296 "btrfs-relocating-repair");
8301 static void map_raid56_repair_block(struct btrfs_io_context
*bioc
,
8302 struct btrfs_io_stripe
*smap
,
8305 int data_stripes
= nr_bioc_data_stripes(bioc
);
8308 for (i
= 0; i
< data_stripes
; i
++) {
8309 u64 stripe_start
= bioc
->full_stripe_logical
+
8310 btrfs_stripe_nr_to_offset(i
);
8312 if (logical
>= stripe_start
&&
8313 logical
< stripe_start
+ BTRFS_STRIPE_LEN
)
8316 ASSERT(i
< data_stripes
);
8317 smap
->dev
= bioc
->stripes
[i
].dev
;
8318 smap
->physical
= bioc
->stripes
[i
].physical
+
8319 ((logical
- bioc
->full_stripe_logical
) &
8320 BTRFS_STRIPE_LEN_MASK
);
8324 * Map a repair write into a single device.
8326 * A repair write is triggered by read time repair or scrub, which would only
8327 * update the contents of a single device.
8328 * Not update any other mirrors nor go through RMW path.
8330 * Callers should ensure:
8332 * - Call btrfs_bio_counter_inc_blocked() first
8333 * - The range does not cross stripe boundary
8334 * - Has a valid @mirror_num passed in.
8336 int btrfs_map_repair_block(struct btrfs_fs_info
*fs_info
,
8337 struct btrfs_io_stripe
*smap
, u64 logical
,
8338 u32 length
, int mirror_num
)
8340 struct btrfs_io_context
*bioc
= NULL
;
8341 u64 map_length
= length
;
8342 int mirror_ret
= mirror_num
;
8345 ASSERT(mirror_num
> 0);
8347 ret
= btrfs_map_block(fs_info
, BTRFS_MAP_WRITE
, logical
, &map_length
,
8348 &bioc
, smap
, &mirror_ret
);
8352 /* The map range should not cross stripe boundary. */
8353 ASSERT(map_length
>= length
);
8355 /* Already mapped to single stripe. */
8359 /* Map the RAID56 multi-stripe writes to a single one. */
8360 if (bioc
->map_type
& BTRFS_BLOCK_GROUP_RAID56_MASK
) {
8361 map_raid56_repair_block(bioc
, smap
, logical
);
8365 ASSERT(mirror_num
<= bioc
->num_stripes
);
8366 smap
->dev
= bioc
->stripes
[mirror_num
- 1].dev
;
8367 smap
->physical
= bioc
->stripes
[mirror_num
- 1].physical
;
8369 btrfs_put_bioc(bioc
);