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>
17 #include "extent_map.h"
19 #include "transaction.h"
20 #include "print-tree.h"
23 #include "rcu-string.h"
24 #include "dev-replace.h"
26 #include "tree-checker.h"
27 #include "space-info.h"
28 #include "block-group.h"
32 #include "accessors.h"
33 #include "uuid-tree.h"
35 #include "relocation.h"
38 #include "raid-stripe-tree.h"
40 #define BTRFS_BLOCK_GROUP_STRIPE_MASK (BTRFS_BLOCK_GROUP_RAID0 | \
41 BTRFS_BLOCK_GROUP_RAID10 | \
42 BTRFS_BLOCK_GROUP_RAID56_MASK)
44 const struct btrfs_raid_attr btrfs_raid_array
[BTRFS_NR_RAID_TYPES
] = {
45 [BTRFS_RAID_RAID10
] = {
48 .devs_max
= 0, /* 0 == as many as possible */
50 .tolerated_failures
= 1,
54 .raid_name
= "raid10",
55 .bg_flag
= BTRFS_BLOCK_GROUP_RAID10
,
56 .mindev_error
= BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET
,
58 [BTRFS_RAID_RAID1
] = {
63 .tolerated_failures
= 1,
68 .bg_flag
= BTRFS_BLOCK_GROUP_RAID1
,
69 .mindev_error
= BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET
,
71 [BTRFS_RAID_RAID1C3
] = {
76 .tolerated_failures
= 2,
80 .raid_name
= "raid1c3",
81 .bg_flag
= BTRFS_BLOCK_GROUP_RAID1C3
,
82 .mindev_error
= BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET
,
84 [BTRFS_RAID_RAID1C4
] = {
89 .tolerated_failures
= 3,
93 .raid_name
= "raid1c4",
94 .bg_flag
= BTRFS_BLOCK_GROUP_RAID1C4
,
95 .mindev_error
= BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET
,
102 .tolerated_failures
= 0,
107 .bg_flag
= BTRFS_BLOCK_GROUP_DUP
,
110 [BTRFS_RAID_RAID0
] = {
115 .tolerated_failures
= 0,
119 .raid_name
= "raid0",
120 .bg_flag
= BTRFS_BLOCK_GROUP_RAID0
,
123 [BTRFS_RAID_SINGLE
] = {
128 .tolerated_failures
= 0,
132 .raid_name
= "single",
136 [BTRFS_RAID_RAID5
] = {
141 .tolerated_failures
= 1,
145 .raid_name
= "raid5",
146 .bg_flag
= BTRFS_BLOCK_GROUP_RAID5
,
147 .mindev_error
= BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET
,
149 [BTRFS_RAID_RAID6
] = {
154 .tolerated_failures
= 2,
158 .raid_name
= "raid6",
159 .bg_flag
= BTRFS_BLOCK_GROUP_RAID6
,
160 .mindev_error
= BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET
,
165 * Convert block group flags (BTRFS_BLOCK_GROUP_*) to btrfs_raid_types, which
166 * can be used as index to access btrfs_raid_array[].
168 enum btrfs_raid_types __attribute_const__
btrfs_bg_flags_to_raid_index(u64 flags
)
170 const u64 profile
= (flags
& BTRFS_BLOCK_GROUP_PROFILE_MASK
);
173 return BTRFS_RAID_SINGLE
;
175 return BTRFS_BG_FLAG_TO_INDEX(profile
);
178 const char *btrfs_bg_type_to_raid_name(u64 flags
)
180 const int index
= btrfs_bg_flags_to_raid_index(flags
);
182 if (index
>= BTRFS_NR_RAID_TYPES
)
185 return btrfs_raid_array
[index
].raid_name
;
188 int btrfs_nr_parity_stripes(u64 type
)
190 enum btrfs_raid_types index
= btrfs_bg_flags_to_raid_index(type
);
192 return btrfs_raid_array
[index
].nparity
;
196 * Fill @buf with textual description of @bg_flags, no more than @size_buf
197 * bytes including terminating null byte.
199 void btrfs_describe_block_groups(u64 bg_flags
, char *buf
, u32 size_buf
)
204 u64 flags
= bg_flags
;
205 u32 size_bp
= size_buf
;
212 #define DESCRIBE_FLAG(flag, desc) \
214 if (flags & (flag)) { \
215 ret = snprintf(bp, size_bp, "%s|", (desc)); \
216 if (ret < 0 || ret >= size_bp) \
224 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA
, "data");
225 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM
, "system");
226 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA
, "metadata");
228 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE
, "single");
229 for (i
= 0; i
< BTRFS_NR_RAID_TYPES
; i
++)
230 DESCRIBE_FLAG(btrfs_raid_array
[i
].bg_flag
,
231 btrfs_raid_array
[i
].raid_name
);
235 ret
= snprintf(bp
, size_bp
, "0x%llx|", flags
);
239 if (size_bp
< size_buf
)
240 buf
[size_buf
- size_bp
- 1] = '\0'; /* remove last | */
243 * The text is trimmed, it's up to the caller to provide sufficiently
249 static int init_first_rw_device(struct btrfs_trans_handle
*trans
);
250 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info
*fs_info
);
251 static void btrfs_dev_stat_print_on_load(struct btrfs_device
*device
);
257 * There are several mutexes that protect manipulation of devices and low-level
258 * structures like chunks but not block groups, extents or files
260 * uuid_mutex (global lock)
261 * ------------------------
262 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
263 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
264 * device) or requested by the device= mount option
266 * the mutex can be very coarse and can cover long-running operations
268 * protects: updates to fs_devices counters like missing devices, rw devices,
269 * seeding, structure cloning, opening/closing devices at mount/umount time
271 * global::fs_devs - add, remove, updates to the global list
273 * does not protect: manipulation of the fs_devices::devices list in general
274 * but in mount context it could be used to exclude list modifications by eg.
277 * btrfs_device::name - renames (write side), read is RCU
279 * fs_devices::device_list_mutex (per-fs, with RCU)
280 * ------------------------------------------------
281 * protects updates to fs_devices::devices, ie. adding and deleting
283 * simple list traversal with read-only actions can be done with RCU protection
285 * may be used to exclude some operations from running concurrently without any
286 * modifications to the list (see write_all_supers)
288 * Is not required at mount and close times, because our device list is
289 * protected by the uuid_mutex at that point.
293 * protects balance structures (status, state) and context accessed from
294 * several places (internally, ioctl)
298 * protects chunks, adding or removing during allocation, trim or when a new
299 * device is added/removed. Additionally it also protects post_commit_list of
300 * individual devices, since they can be added to the transaction's
301 * post_commit_list only with chunk_mutex held.
305 * a big lock that is held by the cleaner thread and prevents running subvolume
306 * cleaning together with relocation or delayed iputs
318 * Exclusive operations
319 * ====================
321 * Maintains the exclusivity of the following operations that apply to the
322 * whole filesystem and cannot run in parallel.
327 * - Device replace (*)
330 * The device operations (as above) can be in one of the following states:
336 * Only device operations marked with (*) can go into the Paused state for the
339 * - ioctl (only Balance can be Paused through ioctl)
340 * - filesystem remounted as read-only
341 * - filesystem unmounted and mounted as read-only
342 * - system power-cycle and filesystem mounted as read-only
343 * - filesystem or device errors leading to forced read-only
345 * The status of exclusive operation is set and cleared atomically.
346 * During the course of Paused state, fs_info::exclusive_operation remains set.
347 * A device operation in Paused or Running state can be canceled or resumed
348 * either by ioctl (Balance only) or when remounted as read-write.
349 * The exclusive status is cleared when the device operation is canceled or
353 DEFINE_MUTEX(uuid_mutex
);
354 static LIST_HEAD(fs_uuids
);
355 struct list_head
* __attribute_const__
btrfs_get_fs_uuids(void)
361 * Allocate new btrfs_fs_devices structure identified by a fsid.
363 * @fsid: if not NULL, copy the UUID to fs_devices::fsid and to
364 * fs_devices::metadata_fsid
366 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
367 * The returned struct is not linked onto any lists and can be destroyed with
368 * kfree() right away.
370 static struct btrfs_fs_devices
*alloc_fs_devices(const u8
*fsid
)
372 struct btrfs_fs_devices
*fs_devs
;
374 fs_devs
= kzalloc(sizeof(*fs_devs
), GFP_KERNEL
);
376 return ERR_PTR(-ENOMEM
);
378 mutex_init(&fs_devs
->device_list_mutex
);
380 INIT_LIST_HEAD(&fs_devs
->devices
);
381 INIT_LIST_HEAD(&fs_devs
->alloc_list
);
382 INIT_LIST_HEAD(&fs_devs
->fs_list
);
383 INIT_LIST_HEAD(&fs_devs
->seed_list
);
386 memcpy(fs_devs
->fsid
, fsid
, BTRFS_FSID_SIZE
);
387 memcpy(fs_devs
->metadata_uuid
, fsid
, BTRFS_FSID_SIZE
);
393 static void btrfs_free_device(struct btrfs_device
*device
)
395 WARN_ON(!list_empty(&device
->post_commit_list
));
396 rcu_string_free(device
->name
);
397 extent_io_tree_release(&device
->alloc_state
);
398 btrfs_destroy_dev_zone_info(device
);
402 static void free_fs_devices(struct btrfs_fs_devices
*fs_devices
)
404 struct btrfs_device
*device
;
406 WARN_ON(fs_devices
->opened
);
407 while (!list_empty(&fs_devices
->devices
)) {
408 device
= list_entry(fs_devices
->devices
.next
,
409 struct btrfs_device
, dev_list
);
410 list_del(&device
->dev_list
);
411 btrfs_free_device(device
);
416 void __exit
btrfs_cleanup_fs_uuids(void)
418 struct btrfs_fs_devices
*fs_devices
;
420 while (!list_empty(&fs_uuids
)) {
421 fs_devices
= list_entry(fs_uuids
.next
,
422 struct btrfs_fs_devices
, fs_list
);
423 list_del(&fs_devices
->fs_list
);
424 free_fs_devices(fs_devices
);
428 static bool match_fsid_fs_devices(const struct btrfs_fs_devices
*fs_devices
,
429 const u8
*fsid
, const u8
*metadata_fsid
)
431 if (memcmp(fsid
, fs_devices
->fsid
, BTRFS_FSID_SIZE
) != 0)
437 if (memcmp(metadata_fsid
, fs_devices
->metadata_uuid
, BTRFS_FSID_SIZE
) != 0)
443 static noinline
struct btrfs_fs_devices
*find_fsid(
444 const u8
*fsid
, const u8
*metadata_fsid
)
446 struct btrfs_fs_devices
*fs_devices
;
450 /* Handle non-split brain cases */
451 list_for_each_entry(fs_devices
, &fs_uuids
, fs_list
) {
452 if (match_fsid_fs_devices(fs_devices
, fsid
, metadata_fsid
))
459 btrfs_get_bdev_and_sb(const char *device_path
, blk_mode_t flags
, void *holder
,
460 int flush
, struct block_device
**bdev
,
461 struct btrfs_super_block
**disk_super
)
465 *bdev
= blkdev_get_by_path(device_path
, flags
, holder
, NULL
);
468 ret
= PTR_ERR(*bdev
);
473 sync_blockdev(*bdev
);
474 ret
= set_blocksize(*bdev
, BTRFS_BDEV_BLOCKSIZE
);
476 blkdev_put(*bdev
, holder
);
479 invalidate_bdev(*bdev
);
480 *disk_super
= btrfs_read_dev_super(*bdev
);
481 if (IS_ERR(*disk_super
)) {
482 ret
= PTR_ERR(*disk_super
);
483 blkdev_put(*bdev
, holder
);
495 * Search and remove all stale devices (which are not mounted). When both
496 * inputs are NULL, it will search and release all stale devices.
498 * @devt: Optional. When provided will it release all unmounted devices
499 * matching this devt only.
500 * @skip_device: Optional. Will skip this device when searching for the stale
503 * Return: 0 for success or if @devt is 0.
504 * -EBUSY if @devt is a mounted device.
505 * -ENOENT if @devt does not match any device in the list.
507 static int btrfs_free_stale_devices(dev_t devt
, struct btrfs_device
*skip_device
)
509 struct btrfs_fs_devices
*fs_devices
, *tmp_fs_devices
;
510 struct btrfs_device
*device
, *tmp_device
;
514 lockdep_assert_held(&uuid_mutex
);
516 /* Return good status if there is no instance of devt. */
518 list_for_each_entry_safe(fs_devices
, tmp_fs_devices
, &fs_uuids
, fs_list
) {
520 mutex_lock(&fs_devices
->device_list_mutex
);
521 list_for_each_entry_safe(device
, tmp_device
,
522 &fs_devices
->devices
, dev_list
) {
523 if (skip_device
&& skip_device
== device
)
525 if (devt
&& devt
!= device
->devt
)
527 if (fs_devices
->opened
) {
533 /* delete the stale device */
534 fs_devices
->num_devices
--;
535 list_del(&device
->dev_list
);
536 btrfs_free_device(device
);
540 mutex_unlock(&fs_devices
->device_list_mutex
);
542 if (fs_devices
->num_devices
== 0) {
543 btrfs_sysfs_remove_fsid(fs_devices
);
544 list_del(&fs_devices
->fs_list
);
545 free_fs_devices(fs_devices
);
549 /* If there is at least one freed device return 0. */
556 static struct btrfs_fs_devices
*find_fsid_by_device(
557 struct btrfs_super_block
*disk_super
,
558 dev_t devt
, bool *same_fsid_diff_dev
)
560 struct btrfs_fs_devices
*fsid_fs_devices
;
561 struct btrfs_fs_devices
*devt_fs_devices
;
562 const bool has_metadata_uuid
= (btrfs_super_incompat_flags(disk_super
) &
563 BTRFS_FEATURE_INCOMPAT_METADATA_UUID
);
564 bool found_by_devt
= false;
566 /* Find the fs_device by the usual method, if found use it. */
567 fsid_fs_devices
= find_fsid(disk_super
->fsid
,
568 has_metadata_uuid
? disk_super
->metadata_uuid
: NULL
);
570 /* The temp_fsid feature is supported only with single device filesystem. */
571 if (btrfs_super_num_devices(disk_super
) != 1)
572 return fsid_fs_devices
;
575 * A seed device is an integral component of the sprout device, which
576 * functions as a multi-device filesystem. So, temp-fsid feature is
579 if (btrfs_super_flags(disk_super
) & BTRFS_SUPER_FLAG_SEEDING
)
580 return fsid_fs_devices
;
582 /* Try to find a fs_devices by matching devt. */
583 list_for_each_entry(devt_fs_devices
, &fs_uuids
, fs_list
) {
584 struct btrfs_device
*device
;
586 list_for_each_entry(device
, &devt_fs_devices
->devices
, dev_list
) {
587 if (device
->devt
== devt
) {
588 found_by_devt
= true;
597 /* Existing device. */
598 if (fsid_fs_devices
== NULL
) {
599 if (devt_fs_devices
->opened
== 0) {
603 /* temp_fsid is mounting a subvol. */
604 return devt_fs_devices
;
607 /* Regular or temp_fsid device mounting a subvol. */
608 return devt_fs_devices
;
612 if (fsid_fs_devices
== NULL
) {
615 /* sb::fsid is already used create a new temp_fsid. */
616 *same_fsid_diff_dev
= true;
625 * This is only used on mount, and we are protected from competing things
626 * messing with our fs_devices by the uuid_mutex, thus we do not need the
627 * fs_devices->device_list_mutex here.
629 static int btrfs_open_one_device(struct btrfs_fs_devices
*fs_devices
,
630 struct btrfs_device
*device
, blk_mode_t flags
,
633 struct block_device
*bdev
;
634 struct btrfs_super_block
*disk_super
;
643 ret
= btrfs_get_bdev_and_sb(device
->name
->str
, flags
, holder
, 1,
648 devid
= btrfs_stack_device_id(&disk_super
->dev_item
);
649 if (devid
!= device
->devid
)
650 goto error_free_page
;
652 if (memcmp(device
->uuid
, disk_super
->dev_item
.uuid
, BTRFS_UUID_SIZE
))
653 goto error_free_page
;
655 device
->generation
= btrfs_super_generation(disk_super
);
657 if (btrfs_super_flags(disk_super
) & BTRFS_SUPER_FLAG_SEEDING
) {
658 if (btrfs_super_incompat_flags(disk_super
) &
659 BTRFS_FEATURE_INCOMPAT_METADATA_UUID
) {
661 "BTRFS: Invalid seeding and uuid-changed device detected\n");
662 goto error_free_page
;
665 clear_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
666 fs_devices
->seeding
= true;
668 if (bdev_read_only(bdev
))
669 clear_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
671 set_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
674 if (!bdev_nonrot(bdev
))
675 fs_devices
->rotating
= true;
677 if (bdev_max_discard_sectors(bdev
))
678 fs_devices
->discardable
= true;
681 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
);
682 device
->holder
= holder
;
684 fs_devices
->open_devices
++;
685 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
) &&
686 device
->devid
!= BTRFS_DEV_REPLACE_DEVID
) {
687 fs_devices
->rw_devices
++;
688 list_add_tail(&device
->dev_alloc_list
, &fs_devices
->alloc_list
);
690 btrfs_release_disk_super(disk_super
);
695 btrfs_release_disk_super(disk_super
);
696 blkdev_put(bdev
, holder
);
701 u8
*btrfs_sb_fsid_ptr(struct btrfs_super_block
*sb
)
703 bool has_metadata_uuid
= (btrfs_super_incompat_flags(sb
) &
704 BTRFS_FEATURE_INCOMPAT_METADATA_UUID
);
706 return has_metadata_uuid
? sb
->metadata_uuid
: sb
->fsid
;
710 * Add new device to list of registered devices
713 * device pointer which was just added or updated when successful
714 * error pointer when failed
716 static noinline
struct btrfs_device
*device_list_add(const char *path
,
717 struct btrfs_super_block
*disk_super
,
718 bool *new_device_added
)
720 struct btrfs_device
*device
;
721 struct btrfs_fs_devices
*fs_devices
= NULL
;
722 struct rcu_string
*name
;
723 u64 found_transid
= btrfs_super_generation(disk_super
);
724 u64 devid
= btrfs_stack_device_id(&disk_super
->dev_item
);
727 bool same_fsid_diff_dev
= false;
728 bool has_metadata_uuid
= (btrfs_super_incompat_flags(disk_super
) &
729 BTRFS_FEATURE_INCOMPAT_METADATA_UUID
);
731 if (btrfs_super_flags(disk_super
) & BTRFS_SUPER_FLAG_CHANGING_FSID_V2
) {
733 "device %s has incomplete metadata_uuid change, please use btrfstune to complete",
735 return ERR_PTR(-EAGAIN
);
738 error
= lookup_bdev(path
, &path_devt
);
740 btrfs_err(NULL
, "failed to lookup block device for path %s: %d",
742 return ERR_PTR(error
);
745 fs_devices
= find_fsid_by_device(disk_super
, path_devt
, &same_fsid_diff_dev
);
748 fs_devices
= alloc_fs_devices(disk_super
->fsid
);
749 if (IS_ERR(fs_devices
))
750 return ERR_CAST(fs_devices
);
752 if (has_metadata_uuid
)
753 memcpy(fs_devices
->metadata_uuid
,
754 disk_super
->metadata_uuid
, BTRFS_FSID_SIZE
);
756 if (same_fsid_diff_dev
) {
757 generate_random_uuid(fs_devices
->fsid
);
758 fs_devices
->temp_fsid
= true;
759 pr_info("BTRFS: device %s using temp-fsid %pU\n",
760 path
, fs_devices
->fsid
);
763 mutex_lock(&fs_devices
->device_list_mutex
);
764 list_add(&fs_devices
->fs_list
, &fs_uuids
);
768 struct btrfs_dev_lookup_args args
= {
770 .uuid
= disk_super
->dev_item
.uuid
,
773 mutex_lock(&fs_devices
->device_list_mutex
);
774 device
= btrfs_find_device(fs_devices
, &args
);
776 if (found_transid
> fs_devices
->latest_generation
) {
777 memcpy(fs_devices
->fsid
, disk_super
->fsid
,
779 memcpy(fs_devices
->metadata_uuid
,
780 btrfs_sb_fsid_ptr(disk_super
), BTRFS_FSID_SIZE
);
785 unsigned int nofs_flag
;
787 if (fs_devices
->opened
) {
789 "device %s belongs to fsid %pU, and the fs is already mounted, scanned by %s (%d)",
790 path
, fs_devices
->fsid
, current
->comm
,
791 task_pid_nr(current
));
792 mutex_unlock(&fs_devices
->device_list_mutex
);
793 return ERR_PTR(-EBUSY
);
796 nofs_flag
= memalloc_nofs_save();
797 device
= btrfs_alloc_device(NULL
, &devid
,
798 disk_super
->dev_item
.uuid
, path
);
799 memalloc_nofs_restore(nofs_flag
);
800 if (IS_ERR(device
)) {
801 mutex_unlock(&fs_devices
->device_list_mutex
);
802 /* we can safely leave the fs_devices entry around */
806 device
->devt
= path_devt
;
808 list_add_rcu(&device
->dev_list
, &fs_devices
->devices
);
809 fs_devices
->num_devices
++;
811 device
->fs_devices
= fs_devices
;
812 *new_device_added
= true;
814 if (disk_super
->label
[0])
816 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
817 disk_super
->label
, devid
, found_transid
, path
,
818 current
->comm
, task_pid_nr(current
));
821 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
822 disk_super
->fsid
, devid
, found_transid
, path
,
823 current
->comm
, task_pid_nr(current
));
825 } else if (!device
->name
|| strcmp(device
->name
->str
, path
)) {
827 * When FS is already mounted.
828 * 1. If you are here and if the device->name is NULL that
829 * means this device was missing at time of FS mount.
830 * 2. If you are here and if the device->name is different
831 * from 'path' that means either
832 * a. The same device disappeared and reappeared with
834 * b. The missing-disk-which-was-replaced, has
837 * We must allow 1 and 2a above. But 2b would be a spurious
840 * Further in case of 1 and 2a above, the disk at 'path'
841 * would have missed some transaction when it was away and
842 * in case of 2a the stale bdev has to be updated as well.
843 * 2b must not be allowed at all time.
847 * For now, we do allow update to btrfs_fs_device through the
848 * btrfs dev scan cli after FS has been mounted. We're still
849 * tracking a problem where systems fail mount by subvolume id
850 * when we reject replacement on a mounted FS.
852 if (!fs_devices
->opened
&& found_transid
< device
->generation
) {
854 * That is if the FS is _not_ mounted and if you
855 * are here, that means there is more than one
856 * disk with same uuid and devid.We keep the one
857 * with larger generation number or the last-in if
858 * generation are equal.
860 mutex_unlock(&fs_devices
->device_list_mutex
);
862 "device %s already registered with a higher generation, found %llu expect %llu",
863 path
, found_transid
, device
->generation
);
864 return ERR_PTR(-EEXIST
);
868 * We are going to replace the device path for a given devid,
869 * make sure it's the same device if the device is mounted
871 * NOTE: the device->fs_info may not be reliable here so pass
872 * in a NULL to message helpers instead. This avoids a possible
873 * use-after-free when the fs_info and fs_info->sb are already
877 if (device
->devt
!= path_devt
) {
878 mutex_unlock(&fs_devices
->device_list_mutex
);
879 btrfs_warn_in_rcu(NULL
,
880 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
881 path
, devid
, found_transid
,
883 task_pid_nr(current
));
884 return ERR_PTR(-EEXIST
);
886 btrfs_info_in_rcu(NULL
,
887 "devid %llu device path %s changed to %s scanned by %s (%d)",
888 devid
, btrfs_dev_name(device
),
890 task_pid_nr(current
));
893 name
= rcu_string_strdup(path
, GFP_NOFS
);
895 mutex_unlock(&fs_devices
->device_list_mutex
);
896 return ERR_PTR(-ENOMEM
);
898 rcu_string_free(device
->name
);
899 rcu_assign_pointer(device
->name
, name
);
900 if (test_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
)) {
901 fs_devices
->missing_devices
--;
902 clear_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
);
904 device
->devt
= path_devt
;
908 * Unmount does not free the btrfs_device struct but would zero
909 * generation along with most of the other members. So just update
910 * it back. We need it to pick the disk with largest generation
913 if (!fs_devices
->opened
) {
914 device
->generation
= found_transid
;
915 fs_devices
->latest_generation
= max_t(u64
, found_transid
,
916 fs_devices
->latest_generation
);
919 fs_devices
->total_devices
= btrfs_super_num_devices(disk_super
);
921 mutex_unlock(&fs_devices
->device_list_mutex
);
925 static struct btrfs_fs_devices
*clone_fs_devices(struct btrfs_fs_devices
*orig
)
927 struct btrfs_fs_devices
*fs_devices
;
928 struct btrfs_device
*device
;
929 struct btrfs_device
*orig_dev
;
932 lockdep_assert_held(&uuid_mutex
);
934 fs_devices
= alloc_fs_devices(orig
->fsid
);
935 if (IS_ERR(fs_devices
))
938 fs_devices
->total_devices
= orig
->total_devices
;
940 list_for_each_entry(orig_dev
, &orig
->devices
, dev_list
) {
941 const char *dev_path
= NULL
;
944 * This is ok to do without RCU read locked because we hold the
945 * uuid mutex so nothing we touch in here is going to disappear.
948 dev_path
= orig_dev
->name
->str
;
950 device
= btrfs_alloc_device(NULL
, &orig_dev
->devid
,
951 orig_dev
->uuid
, dev_path
);
952 if (IS_ERR(device
)) {
953 ret
= PTR_ERR(device
);
957 if (orig_dev
->zone_info
) {
958 struct btrfs_zoned_device_info
*zone_info
;
960 zone_info
= btrfs_clone_dev_zone_info(orig_dev
);
962 btrfs_free_device(device
);
966 device
->zone_info
= zone_info
;
969 list_add(&device
->dev_list
, &fs_devices
->devices
);
970 device
->fs_devices
= fs_devices
;
971 fs_devices
->num_devices
++;
975 free_fs_devices(fs_devices
);
979 static void __btrfs_free_extra_devids(struct btrfs_fs_devices
*fs_devices
,
980 struct btrfs_device
**latest_dev
)
982 struct btrfs_device
*device
, *next
;
984 /* This is the initialized path, it is safe to release the devices. */
985 list_for_each_entry_safe(device
, next
, &fs_devices
->devices
, dev_list
) {
986 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
)) {
987 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT
,
988 &device
->dev_state
) &&
989 !test_bit(BTRFS_DEV_STATE_MISSING
,
990 &device
->dev_state
) &&
992 device
->generation
> (*latest_dev
)->generation
)) {
993 *latest_dev
= device
;
999 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1000 * in btrfs_init_dev_replace() so just continue.
1002 if (device
->devid
== BTRFS_DEV_REPLACE_DEVID
)
1006 blkdev_put(device
->bdev
, device
->holder
);
1007 device
->bdev
= NULL
;
1008 fs_devices
->open_devices
--;
1010 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
1011 list_del_init(&device
->dev_alloc_list
);
1012 clear_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
1013 fs_devices
->rw_devices
--;
1015 list_del_init(&device
->dev_list
);
1016 fs_devices
->num_devices
--;
1017 btrfs_free_device(device
);
1023 * After we have read the system tree and know devids belonging to this
1024 * filesystem, remove the device which does not belong there.
1026 void btrfs_free_extra_devids(struct btrfs_fs_devices
*fs_devices
)
1028 struct btrfs_device
*latest_dev
= NULL
;
1029 struct btrfs_fs_devices
*seed_dev
;
1031 mutex_lock(&uuid_mutex
);
1032 __btrfs_free_extra_devids(fs_devices
, &latest_dev
);
1034 list_for_each_entry(seed_dev
, &fs_devices
->seed_list
, seed_list
)
1035 __btrfs_free_extra_devids(seed_dev
, &latest_dev
);
1037 fs_devices
->latest_dev
= latest_dev
;
1039 mutex_unlock(&uuid_mutex
);
1042 static void btrfs_close_bdev(struct btrfs_device
*device
)
1047 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
1048 sync_blockdev(device
->bdev
);
1049 invalidate_bdev(device
->bdev
);
1052 blkdev_put(device
->bdev
, device
->holder
);
1055 static void btrfs_close_one_device(struct btrfs_device
*device
)
1057 struct btrfs_fs_devices
*fs_devices
= device
->fs_devices
;
1059 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
) &&
1060 device
->devid
!= BTRFS_DEV_REPLACE_DEVID
) {
1061 list_del_init(&device
->dev_alloc_list
);
1062 fs_devices
->rw_devices
--;
1065 if (device
->devid
== BTRFS_DEV_REPLACE_DEVID
)
1066 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
);
1068 if (test_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
)) {
1069 clear_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
);
1070 fs_devices
->missing_devices
--;
1073 btrfs_close_bdev(device
);
1075 fs_devices
->open_devices
--;
1076 device
->bdev
= NULL
;
1078 clear_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
1079 btrfs_destroy_dev_zone_info(device
);
1081 device
->fs_info
= NULL
;
1082 atomic_set(&device
->dev_stats_ccnt
, 0);
1083 extent_io_tree_release(&device
->alloc_state
);
1086 * Reset the flush error record. We might have a transient flush error
1087 * in this mount, and if so we aborted the current transaction and set
1088 * the fs to an error state, guaranteeing no super blocks can be further
1089 * committed. However that error might be transient and if we unmount the
1090 * filesystem and mount it again, we should allow the mount to succeed
1091 * (btrfs_check_rw_degradable() should not fail) - if after mounting the
1092 * filesystem again we still get flush errors, then we will again abort
1093 * any transaction and set the error state, guaranteeing no commits of
1094 * unsafe super blocks.
1096 device
->last_flush_error
= 0;
1098 /* Verify the device is back in a pristine state */
1099 WARN_ON(test_bit(BTRFS_DEV_STATE_FLUSH_SENT
, &device
->dev_state
));
1100 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
));
1101 WARN_ON(!list_empty(&device
->dev_alloc_list
));
1102 WARN_ON(!list_empty(&device
->post_commit_list
));
1105 static void close_fs_devices(struct btrfs_fs_devices
*fs_devices
)
1107 struct btrfs_device
*device
, *tmp
;
1109 lockdep_assert_held(&uuid_mutex
);
1111 if (--fs_devices
->opened
> 0)
1114 list_for_each_entry_safe(device
, tmp
, &fs_devices
->devices
, dev_list
)
1115 btrfs_close_one_device(device
);
1117 WARN_ON(fs_devices
->open_devices
);
1118 WARN_ON(fs_devices
->rw_devices
);
1119 fs_devices
->opened
= 0;
1120 fs_devices
->seeding
= false;
1121 fs_devices
->fs_info
= NULL
;
1124 void btrfs_close_devices(struct btrfs_fs_devices
*fs_devices
)
1127 struct btrfs_fs_devices
*tmp
;
1129 mutex_lock(&uuid_mutex
);
1130 close_fs_devices(fs_devices
);
1131 if (!fs_devices
->opened
) {
1132 list_splice_init(&fs_devices
->seed_list
, &list
);
1135 * If the struct btrfs_fs_devices is not assembled with any
1136 * other device, it can be re-initialized during the next mount
1137 * without the needing device-scan step. Therefore, it can be
1140 if (fs_devices
->num_devices
== 1) {
1141 list_del(&fs_devices
->fs_list
);
1142 free_fs_devices(fs_devices
);
1147 list_for_each_entry_safe(fs_devices
, tmp
, &list
, seed_list
) {
1148 close_fs_devices(fs_devices
);
1149 list_del(&fs_devices
->seed_list
);
1150 free_fs_devices(fs_devices
);
1152 mutex_unlock(&uuid_mutex
);
1155 static int open_fs_devices(struct btrfs_fs_devices
*fs_devices
,
1156 blk_mode_t flags
, void *holder
)
1158 struct btrfs_device
*device
;
1159 struct btrfs_device
*latest_dev
= NULL
;
1160 struct btrfs_device
*tmp_device
;
1162 list_for_each_entry_safe(device
, tmp_device
, &fs_devices
->devices
,
1166 ret
= btrfs_open_one_device(fs_devices
, device
, flags
, holder
);
1168 (!latest_dev
|| device
->generation
> latest_dev
->generation
)) {
1169 latest_dev
= device
;
1170 } else if (ret
== -ENODATA
) {
1171 fs_devices
->num_devices
--;
1172 list_del(&device
->dev_list
);
1173 btrfs_free_device(device
);
1176 if (fs_devices
->open_devices
== 0)
1179 fs_devices
->opened
= 1;
1180 fs_devices
->latest_dev
= latest_dev
;
1181 fs_devices
->total_rw_bytes
= 0;
1182 fs_devices
->chunk_alloc_policy
= BTRFS_CHUNK_ALLOC_REGULAR
;
1183 fs_devices
->read_policy
= BTRFS_READ_POLICY_PID
;
1188 static int devid_cmp(void *priv
, const struct list_head
*a
,
1189 const struct list_head
*b
)
1191 const struct btrfs_device
*dev1
, *dev2
;
1193 dev1
= list_entry(a
, struct btrfs_device
, dev_list
);
1194 dev2
= list_entry(b
, struct btrfs_device
, dev_list
);
1196 if (dev1
->devid
< dev2
->devid
)
1198 else if (dev1
->devid
> dev2
->devid
)
1203 int btrfs_open_devices(struct btrfs_fs_devices
*fs_devices
,
1204 blk_mode_t flags
, void *holder
)
1208 lockdep_assert_held(&uuid_mutex
);
1210 * The device_list_mutex cannot be taken here in case opening the
1211 * underlying device takes further locks like open_mutex.
1213 * We also don't need the lock here as this is called during mount and
1214 * exclusion is provided by uuid_mutex
1217 if (fs_devices
->opened
) {
1218 fs_devices
->opened
++;
1221 list_sort(NULL
, &fs_devices
->devices
, devid_cmp
);
1222 ret
= open_fs_devices(fs_devices
, flags
, holder
);
1228 void btrfs_release_disk_super(struct btrfs_super_block
*super
)
1230 struct page
*page
= virt_to_page(super
);
1235 static struct btrfs_super_block
*btrfs_read_disk_super(struct block_device
*bdev
,
1236 u64 bytenr
, u64 bytenr_orig
)
1238 struct btrfs_super_block
*disk_super
;
1243 /* make sure our super fits in the device */
1244 if (bytenr
+ PAGE_SIZE
>= bdev_nr_bytes(bdev
))
1245 return ERR_PTR(-EINVAL
);
1247 /* make sure our super fits in the page */
1248 if (sizeof(*disk_super
) > PAGE_SIZE
)
1249 return ERR_PTR(-EINVAL
);
1251 /* make sure our super doesn't straddle pages on disk */
1252 index
= bytenr
>> PAGE_SHIFT
;
1253 if ((bytenr
+ sizeof(*disk_super
) - 1) >> PAGE_SHIFT
!= index
)
1254 return ERR_PTR(-EINVAL
);
1256 /* pull in the page with our super */
1257 page
= read_cache_page_gfp(bdev
->bd_inode
->i_mapping
, index
, GFP_KERNEL
);
1260 return ERR_CAST(page
);
1262 p
= page_address(page
);
1264 /* align our pointer to the offset of the super block */
1265 disk_super
= p
+ offset_in_page(bytenr
);
1267 if (btrfs_super_bytenr(disk_super
) != bytenr_orig
||
1268 btrfs_super_magic(disk_super
) != BTRFS_MAGIC
) {
1269 btrfs_release_disk_super(p
);
1270 return ERR_PTR(-EINVAL
);
1273 if (disk_super
->label
[0] && disk_super
->label
[BTRFS_LABEL_SIZE
- 1])
1274 disk_super
->label
[BTRFS_LABEL_SIZE
- 1] = 0;
1279 int btrfs_forget_devices(dev_t devt
)
1283 mutex_lock(&uuid_mutex
);
1284 ret
= btrfs_free_stale_devices(devt
, NULL
);
1285 mutex_unlock(&uuid_mutex
);
1291 * Look for a btrfs signature on a device. This may be called out of the mount path
1292 * and we are not allowed to call set_blocksize during the scan. The superblock
1293 * is read via pagecache.
1295 * With @mount_arg_dev it's a scan during mount time that will always register
1296 * the device or return an error. Multi-device and seeding devices are registered
1299 struct btrfs_device
*btrfs_scan_one_device(const char *path
, blk_mode_t flags
,
1302 struct btrfs_super_block
*disk_super
;
1303 bool new_device_added
= false;
1304 struct btrfs_device
*device
= NULL
;
1305 struct block_device
*bdev
;
1306 u64 bytenr
, bytenr_orig
;
1309 lockdep_assert_held(&uuid_mutex
);
1312 * we would like to check all the supers, but that would make
1313 * a btrfs mount succeed after a mkfs from a different FS.
1314 * So, we need to add a special mount option to scan for
1315 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1319 * Avoid an exclusive open here, as the systemd-udev may initiate the
1320 * device scan which may race with the user's mount or mkfs command,
1321 * resulting in failure.
1322 * Since the device scan is solely for reading purposes, there is no
1323 * need for an exclusive open. Additionally, the devices are read again
1324 * during the mount process. It is ok to get some inconsistent
1325 * values temporarily, as the device paths of the fsid are the only
1326 * required information for assembling the volume.
1328 bdev
= blkdev_get_by_path(path
, flags
, NULL
, NULL
);
1330 return ERR_CAST(bdev
);
1332 bytenr_orig
= btrfs_sb_offset(0);
1333 ret
= btrfs_sb_log_location_bdev(bdev
, 0, READ
, &bytenr
);
1335 device
= ERR_PTR(ret
);
1336 goto error_bdev_put
;
1339 disk_super
= btrfs_read_disk_super(bdev
, bytenr
, bytenr_orig
);
1340 if (IS_ERR(disk_super
)) {
1341 device
= ERR_CAST(disk_super
);
1342 goto error_bdev_put
;
1345 if (!mount_arg_dev
&& btrfs_super_num_devices(disk_super
) == 1 &&
1346 !(btrfs_super_flags(disk_super
) & BTRFS_SUPER_FLAG_SEEDING
)) {
1349 ret
= lookup_bdev(path
, &devt
);
1351 btrfs_warn(NULL
, "lookup bdev failed for path %s: %d",
1354 btrfs_free_stale_devices(devt
, NULL
);
1356 pr_debug("BTRFS: skip registering single non-seed device %s\n", path
);
1358 goto free_disk_super
;
1361 device
= device_list_add(path
, disk_super
, &new_device_added
);
1362 if (!IS_ERR(device
) && new_device_added
)
1363 btrfs_free_stale_devices(device
->devt
, device
);
1366 btrfs_release_disk_super(disk_super
);
1369 blkdev_put(bdev
, NULL
);
1375 * Try to find a chunk that intersects [start, start + len] range and when one
1376 * such is found, record the end of it in *start
1378 static bool contains_pending_extent(struct btrfs_device
*device
, u64
*start
,
1381 u64 physical_start
, physical_end
;
1383 lockdep_assert_held(&device
->fs_info
->chunk_mutex
);
1385 if (find_first_extent_bit(&device
->alloc_state
, *start
,
1386 &physical_start
, &physical_end
,
1387 CHUNK_ALLOCATED
, NULL
)) {
1389 if (in_range(physical_start
, *start
, len
) ||
1390 in_range(*start
, physical_start
,
1391 physical_end
- physical_start
)) {
1392 *start
= physical_end
+ 1;
1399 static u64
dev_extent_search_start(struct btrfs_device
*device
)
1401 switch (device
->fs_devices
->chunk_alloc_policy
) {
1402 case BTRFS_CHUNK_ALLOC_REGULAR
:
1403 return BTRFS_DEVICE_RANGE_RESERVED
;
1404 case BTRFS_CHUNK_ALLOC_ZONED
:
1406 * We don't care about the starting region like regular
1407 * allocator, because we anyway use/reserve the first two zones
1408 * for superblock logging.
1416 static bool dev_extent_hole_check_zoned(struct btrfs_device
*device
,
1417 u64
*hole_start
, u64
*hole_size
,
1420 u64 zone_size
= device
->zone_info
->zone_size
;
1423 bool changed
= false;
1425 ASSERT(IS_ALIGNED(*hole_start
, zone_size
));
1427 while (*hole_size
> 0) {
1428 pos
= btrfs_find_allocatable_zones(device
, *hole_start
,
1429 *hole_start
+ *hole_size
,
1431 if (pos
!= *hole_start
) {
1432 *hole_size
= *hole_start
+ *hole_size
- pos
;
1435 if (*hole_size
< num_bytes
)
1439 ret
= btrfs_ensure_empty_zones(device
, pos
, num_bytes
);
1441 /* Range is ensured to be empty */
1445 /* Given hole range was invalid (outside of device) */
1446 if (ret
== -ERANGE
) {
1447 *hole_start
+= *hole_size
;
1452 *hole_start
+= zone_size
;
1453 *hole_size
-= zone_size
;
1461 * Check if specified hole is suitable for allocation.
1463 * @device: the device which we have the hole
1464 * @hole_start: starting position of the hole
1465 * @hole_size: the size of the hole
1466 * @num_bytes: the size of the free space that we need
1468 * This function may modify @hole_start and @hole_size to reflect the suitable
1469 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1471 static bool dev_extent_hole_check(struct btrfs_device
*device
, u64
*hole_start
,
1472 u64
*hole_size
, u64 num_bytes
)
1474 bool changed
= false;
1475 u64 hole_end
= *hole_start
+ *hole_size
;
1479 * Check before we set max_hole_start, otherwise we could end up
1480 * sending back this offset anyway.
1482 if (contains_pending_extent(device
, hole_start
, *hole_size
)) {
1483 if (hole_end
>= *hole_start
)
1484 *hole_size
= hole_end
- *hole_start
;
1490 switch (device
->fs_devices
->chunk_alloc_policy
) {
1491 case BTRFS_CHUNK_ALLOC_REGULAR
:
1492 /* No extra check */
1494 case BTRFS_CHUNK_ALLOC_ZONED
:
1495 if (dev_extent_hole_check_zoned(device
, hole_start
,
1496 hole_size
, num_bytes
)) {
1499 * The changed hole can contain pending extent.
1500 * Loop again to check that.
1516 * Find free space in the specified device.
1518 * @device: the device which we search the free space in
1519 * @num_bytes: the size of the free space that we need
1520 * @search_start: the position from which to begin the search
1521 * @start: store the start of the free space.
1522 * @len: the size of the free space. that we find, or the size
1523 * of the max free space if we don't find suitable free space
1525 * This does a pretty simple search, the expectation is that it is called very
1526 * infrequently and that a given device has a small number of extents.
1528 * @start is used to store the start of the free space if we find. But if we
1529 * don't find suitable free space, it will be used to store the start position
1530 * of the max free space.
1532 * @len is used to store the size of the free space that we find.
1533 * But if we don't find suitable free space, it is used to store the size of
1534 * the max free space.
1536 * NOTE: This function will search *commit* root of device tree, and does extra
1537 * check to ensure dev extents are not double allocated.
1538 * This makes the function safe to allocate dev extents but may not report
1539 * correct usable device space, as device extent freed in current transaction
1540 * is not reported as available.
1542 static int find_free_dev_extent(struct btrfs_device
*device
, u64 num_bytes
,
1543 u64
*start
, u64
*len
)
1545 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
1546 struct btrfs_root
*root
= fs_info
->dev_root
;
1547 struct btrfs_key key
;
1548 struct btrfs_dev_extent
*dev_extent
;
1549 struct btrfs_path
*path
;
1553 u64 max_hole_size
= 0;
1555 u64 search_end
= device
->total_bytes
;
1558 struct extent_buffer
*l
;
1560 search_start
= dev_extent_search_start(device
);
1561 max_hole_start
= search_start
;
1563 WARN_ON(device
->zone_info
&&
1564 !IS_ALIGNED(num_bytes
, device
->zone_info
->zone_size
));
1566 path
= btrfs_alloc_path();
1572 if (search_start
>= search_end
||
1573 test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
)) {
1578 path
->reada
= READA_FORWARD
;
1579 path
->search_commit_root
= 1;
1580 path
->skip_locking
= 1;
1582 key
.objectid
= device
->devid
;
1583 key
.offset
= search_start
;
1584 key
.type
= BTRFS_DEV_EXTENT_KEY
;
1586 ret
= btrfs_search_backwards(root
, &key
, path
);
1590 while (search_start
< search_end
) {
1592 slot
= path
->slots
[0];
1593 if (slot
>= btrfs_header_nritems(l
)) {
1594 ret
= btrfs_next_leaf(root
, path
);
1602 btrfs_item_key_to_cpu(l
, &key
, slot
);
1604 if (key
.objectid
< device
->devid
)
1607 if (key
.objectid
> device
->devid
)
1610 if (key
.type
!= BTRFS_DEV_EXTENT_KEY
)
1613 if (key
.offset
> search_end
)
1616 if (key
.offset
> search_start
) {
1617 hole_size
= key
.offset
- search_start
;
1618 dev_extent_hole_check(device
, &search_start
, &hole_size
,
1621 if (hole_size
> max_hole_size
) {
1622 max_hole_start
= search_start
;
1623 max_hole_size
= hole_size
;
1627 * If this free space is greater than which we need,
1628 * it must be the max free space that we have found
1629 * until now, so max_hole_start must point to the start
1630 * of this free space and the length of this free space
1631 * is stored in max_hole_size. Thus, we return
1632 * max_hole_start and max_hole_size and go back to the
1635 if (hole_size
>= num_bytes
) {
1641 dev_extent
= btrfs_item_ptr(l
, slot
, struct btrfs_dev_extent
);
1642 extent_end
= key
.offset
+ btrfs_dev_extent_length(l
,
1644 if (extent_end
> search_start
)
1645 search_start
= extent_end
;
1652 * At this point, search_start should be the end of
1653 * allocated dev extents, and when shrinking the device,
1654 * search_end may be smaller than search_start.
1656 if (search_end
> search_start
) {
1657 hole_size
= search_end
- search_start
;
1658 if (dev_extent_hole_check(device
, &search_start
, &hole_size
,
1660 btrfs_release_path(path
);
1664 if (hole_size
> max_hole_size
) {
1665 max_hole_start
= search_start
;
1666 max_hole_size
= hole_size
;
1671 if (max_hole_size
< num_bytes
)
1676 ASSERT(max_hole_start
+ max_hole_size
<= search_end
);
1678 btrfs_free_path(path
);
1679 *start
= max_hole_start
;
1681 *len
= max_hole_size
;
1685 static int btrfs_free_dev_extent(struct btrfs_trans_handle
*trans
,
1686 struct btrfs_device
*device
,
1687 u64 start
, u64
*dev_extent_len
)
1689 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
1690 struct btrfs_root
*root
= fs_info
->dev_root
;
1692 struct btrfs_path
*path
;
1693 struct btrfs_key key
;
1694 struct btrfs_key found_key
;
1695 struct extent_buffer
*leaf
= NULL
;
1696 struct btrfs_dev_extent
*extent
= NULL
;
1698 path
= btrfs_alloc_path();
1702 key
.objectid
= device
->devid
;
1704 key
.type
= BTRFS_DEV_EXTENT_KEY
;
1706 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
1708 ret
= btrfs_previous_item(root
, path
, key
.objectid
,
1709 BTRFS_DEV_EXTENT_KEY
);
1712 leaf
= path
->nodes
[0];
1713 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
1714 extent
= btrfs_item_ptr(leaf
, path
->slots
[0],
1715 struct btrfs_dev_extent
);
1716 BUG_ON(found_key
.offset
> start
|| found_key
.offset
+
1717 btrfs_dev_extent_length(leaf
, extent
) < start
);
1719 btrfs_release_path(path
);
1721 } else if (ret
== 0) {
1722 leaf
= path
->nodes
[0];
1723 extent
= btrfs_item_ptr(leaf
, path
->slots
[0],
1724 struct btrfs_dev_extent
);
1729 *dev_extent_len
= btrfs_dev_extent_length(leaf
, extent
);
1731 ret
= btrfs_del_item(trans
, root
, path
);
1733 set_bit(BTRFS_TRANS_HAVE_FREE_BGS
, &trans
->transaction
->flags
);
1735 btrfs_free_path(path
);
1739 static u64
find_next_chunk(struct btrfs_fs_info
*fs_info
)
1741 struct extent_map_tree
*em_tree
;
1742 struct extent_map
*em
;
1746 em_tree
= &fs_info
->mapping_tree
;
1747 read_lock(&em_tree
->lock
);
1748 n
= rb_last(&em_tree
->map
.rb_root
);
1750 em
= rb_entry(n
, struct extent_map
, rb_node
);
1751 ret
= em
->start
+ em
->len
;
1753 read_unlock(&em_tree
->lock
);
1758 static noinline
int find_next_devid(struct btrfs_fs_info
*fs_info
,
1762 struct btrfs_key key
;
1763 struct btrfs_key found_key
;
1764 struct btrfs_path
*path
;
1766 path
= btrfs_alloc_path();
1770 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
1771 key
.type
= BTRFS_DEV_ITEM_KEY
;
1772 key
.offset
= (u64
)-1;
1774 ret
= btrfs_search_slot(NULL
, fs_info
->chunk_root
, &key
, path
, 0, 0);
1780 btrfs_err(fs_info
, "corrupted chunk tree devid -1 matched");
1785 ret
= btrfs_previous_item(fs_info
->chunk_root
, path
,
1786 BTRFS_DEV_ITEMS_OBJECTID
,
1787 BTRFS_DEV_ITEM_KEY
);
1791 btrfs_item_key_to_cpu(path
->nodes
[0], &found_key
,
1793 *devid_ret
= found_key
.offset
+ 1;
1797 btrfs_free_path(path
);
1802 * the device information is stored in the chunk root
1803 * the btrfs_device struct should be fully filled in
1805 static int btrfs_add_dev_item(struct btrfs_trans_handle
*trans
,
1806 struct btrfs_device
*device
)
1809 struct btrfs_path
*path
;
1810 struct btrfs_dev_item
*dev_item
;
1811 struct extent_buffer
*leaf
;
1812 struct btrfs_key key
;
1815 path
= btrfs_alloc_path();
1819 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
1820 key
.type
= BTRFS_DEV_ITEM_KEY
;
1821 key
.offset
= device
->devid
;
1823 btrfs_reserve_chunk_metadata(trans
, true);
1824 ret
= btrfs_insert_empty_item(trans
, trans
->fs_info
->chunk_root
, path
,
1825 &key
, sizeof(*dev_item
));
1826 btrfs_trans_release_chunk_metadata(trans
);
1830 leaf
= path
->nodes
[0];
1831 dev_item
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_dev_item
);
1833 btrfs_set_device_id(leaf
, dev_item
, device
->devid
);
1834 btrfs_set_device_generation(leaf
, dev_item
, 0);
1835 btrfs_set_device_type(leaf
, dev_item
, device
->type
);
1836 btrfs_set_device_io_align(leaf
, dev_item
, device
->io_align
);
1837 btrfs_set_device_io_width(leaf
, dev_item
, device
->io_width
);
1838 btrfs_set_device_sector_size(leaf
, dev_item
, device
->sector_size
);
1839 btrfs_set_device_total_bytes(leaf
, dev_item
,
1840 btrfs_device_get_disk_total_bytes(device
));
1841 btrfs_set_device_bytes_used(leaf
, dev_item
,
1842 btrfs_device_get_bytes_used(device
));
1843 btrfs_set_device_group(leaf
, dev_item
, 0);
1844 btrfs_set_device_seek_speed(leaf
, dev_item
, 0);
1845 btrfs_set_device_bandwidth(leaf
, dev_item
, 0);
1846 btrfs_set_device_start_offset(leaf
, dev_item
, 0);
1848 ptr
= btrfs_device_uuid(dev_item
);
1849 write_extent_buffer(leaf
, device
->uuid
, ptr
, BTRFS_UUID_SIZE
);
1850 ptr
= btrfs_device_fsid(dev_item
);
1851 write_extent_buffer(leaf
, trans
->fs_info
->fs_devices
->metadata_uuid
,
1852 ptr
, BTRFS_FSID_SIZE
);
1853 btrfs_mark_buffer_dirty(trans
, leaf
);
1857 btrfs_free_path(path
);
1862 * Function to update ctime/mtime for a given device path.
1863 * Mainly used for ctime/mtime based probe like libblkid.
1865 * We don't care about errors here, this is just to be kind to userspace.
1867 static void update_dev_time(const char *device_path
)
1872 ret
= kern_path(device_path
, LOOKUP_FOLLOW
, &path
);
1876 inode_update_time(d_inode(path
.dentry
), S_MTIME
| S_CTIME
| S_VERSION
);
1880 static int btrfs_rm_dev_item(struct btrfs_trans_handle
*trans
,
1881 struct btrfs_device
*device
)
1883 struct btrfs_root
*root
= device
->fs_info
->chunk_root
;
1885 struct btrfs_path
*path
;
1886 struct btrfs_key key
;
1888 path
= btrfs_alloc_path();
1892 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
1893 key
.type
= BTRFS_DEV_ITEM_KEY
;
1894 key
.offset
= device
->devid
;
1896 btrfs_reserve_chunk_metadata(trans
, false);
1897 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
1898 btrfs_trans_release_chunk_metadata(trans
);
1905 ret
= btrfs_del_item(trans
, root
, path
);
1907 btrfs_free_path(path
);
1912 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1913 * filesystem. It's up to the caller to adjust that number regarding eg. device
1916 static int btrfs_check_raid_min_devices(struct btrfs_fs_info
*fs_info
,
1924 seq
= read_seqbegin(&fs_info
->profiles_lock
);
1926 all_avail
= fs_info
->avail_data_alloc_bits
|
1927 fs_info
->avail_system_alloc_bits
|
1928 fs_info
->avail_metadata_alloc_bits
;
1929 } while (read_seqretry(&fs_info
->profiles_lock
, seq
));
1931 for (i
= 0; i
< BTRFS_NR_RAID_TYPES
; i
++) {
1932 if (!(all_avail
& btrfs_raid_array
[i
].bg_flag
))
1935 if (num_devices
< btrfs_raid_array
[i
].devs_min
)
1936 return btrfs_raid_array
[i
].mindev_error
;
1942 static struct btrfs_device
* btrfs_find_next_active_device(
1943 struct btrfs_fs_devices
*fs_devs
, struct btrfs_device
*device
)
1945 struct btrfs_device
*next_device
;
1947 list_for_each_entry(next_device
, &fs_devs
->devices
, dev_list
) {
1948 if (next_device
!= device
&&
1949 !test_bit(BTRFS_DEV_STATE_MISSING
, &next_device
->dev_state
)
1950 && next_device
->bdev
)
1958 * Helper function to check if the given device is part of s_bdev / latest_dev
1959 * and replace it with the provided or the next active device, in the context
1960 * where this function called, there should be always be another device (or
1961 * this_dev) which is active.
1963 void __cold
btrfs_assign_next_active_device(struct btrfs_device
*device
,
1964 struct btrfs_device
*next_device
)
1966 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
1969 next_device
= btrfs_find_next_active_device(fs_info
->fs_devices
,
1971 ASSERT(next_device
);
1973 if (fs_info
->sb
->s_bdev
&&
1974 (fs_info
->sb
->s_bdev
== device
->bdev
))
1975 fs_info
->sb
->s_bdev
= next_device
->bdev
;
1977 if (fs_info
->fs_devices
->latest_dev
->bdev
== device
->bdev
)
1978 fs_info
->fs_devices
->latest_dev
= next_device
;
1982 * Return btrfs_fs_devices::num_devices excluding the device that's being
1983 * currently replaced.
1985 static u64
btrfs_num_devices(struct btrfs_fs_info
*fs_info
)
1987 u64 num_devices
= fs_info
->fs_devices
->num_devices
;
1989 down_read(&fs_info
->dev_replace
.rwsem
);
1990 if (btrfs_dev_replace_is_ongoing(&fs_info
->dev_replace
)) {
1991 ASSERT(num_devices
> 1);
1994 up_read(&fs_info
->dev_replace
.rwsem
);
1999 static void btrfs_scratch_superblock(struct btrfs_fs_info
*fs_info
,
2000 struct block_device
*bdev
, int copy_num
)
2002 struct btrfs_super_block
*disk_super
;
2003 const size_t len
= sizeof(disk_super
->magic
);
2004 const u64 bytenr
= btrfs_sb_offset(copy_num
);
2007 disk_super
= btrfs_read_disk_super(bdev
, bytenr
, bytenr
);
2008 if (IS_ERR(disk_super
))
2011 memset(&disk_super
->magic
, 0, len
);
2012 folio_mark_dirty(virt_to_folio(disk_super
));
2013 btrfs_release_disk_super(disk_super
);
2015 ret
= sync_blockdev_range(bdev
, bytenr
, bytenr
+ len
- 1);
2017 btrfs_warn(fs_info
, "error clearing superblock number %d (%d)",
2021 void btrfs_scratch_superblocks(struct btrfs_fs_info
*fs_info
,
2022 struct block_device
*bdev
,
2023 const char *device_path
)
2030 for (copy_num
= 0; copy_num
< BTRFS_SUPER_MIRROR_MAX
; copy_num
++) {
2031 if (bdev_is_zoned(bdev
))
2032 btrfs_reset_sb_log_zones(bdev
, copy_num
);
2034 btrfs_scratch_superblock(fs_info
, bdev
, copy_num
);
2037 /* Notify udev that device has changed */
2038 btrfs_kobject_uevent(bdev
, KOBJ_CHANGE
);
2040 /* Update ctime/mtime for device path for libblkid */
2041 update_dev_time(device_path
);
2044 int btrfs_rm_device(struct btrfs_fs_info
*fs_info
,
2045 struct btrfs_dev_lookup_args
*args
,
2046 struct block_device
**bdev
, void **holder
)
2048 struct btrfs_trans_handle
*trans
;
2049 struct btrfs_device
*device
;
2050 struct btrfs_fs_devices
*cur_devices
;
2051 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
2055 if (btrfs_fs_incompat(fs_info
, EXTENT_TREE_V2
)) {
2056 btrfs_err(fs_info
, "device remove not supported on extent tree v2 yet");
2061 * The device list in fs_devices is accessed without locks (neither
2062 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2063 * filesystem and another device rm cannot run.
2065 num_devices
= btrfs_num_devices(fs_info
);
2067 ret
= btrfs_check_raid_min_devices(fs_info
, num_devices
- 1);
2071 device
= btrfs_find_device(fs_info
->fs_devices
, args
);
2074 ret
= BTRFS_ERROR_DEV_MISSING_NOT_FOUND
;
2080 if (btrfs_pinned_by_swapfile(fs_info
, device
)) {
2081 btrfs_warn_in_rcu(fs_info
,
2082 "cannot remove device %s (devid %llu) due to active swapfile",
2083 btrfs_dev_name(device
), device
->devid
);
2087 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
))
2088 return BTRFS_ERROR_DEV_TGT_REPLACE
;
2090 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
) &&
2091 fs_info
->fs_devices
->rw_devices
== 1)
2092 return BTRFS_ERROR_DEV_ONLY_WRITABLE
;
2094 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
2095 mutex_lock(&fs_info
->chunk_mutex
);
2096 list_del_init(&device
->dev_alloc_list
);
2097 device
->fs_devices
->rw_devices
--;
2098 mutex_unlock(&fs_info
->chunk_mutex
);
2101 ret
= btrfs_shrink_device(device
, 0);
2105 trans
= btrfs_start_transaction(fs_info
->chunk_root
, 0);
2106 if (IS_ERR(trans
)) {
2107 ret
= PTR_ERR(trans
);
2111 ret
= btrfs_rm_dev_item(trans
, device
);
2113 /* Any error in dev item removal is critical */
2115 "failed to remove device item for devid %llu: %d",
2116 device
->devid
, ret
);
2117 btrfs_abort_transaction(trans
, ret
);
2118 btrfs_end_transaction(trans
);
2122 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
);
2123 btrfs_scrub_cancel_dev(device
);
2126 * the device list mutex makes sure that we don't change
2127 * the device list while someone else is writing out all
2128 * the device supers. Whoever is writing all supers, should
2129 * lock the device list mutex before getting the number of
2130 * devices in the super block (super_copy). Conversely,
2131 * whoever updates the number of devices in the super block
2132 * (super_copy) should hold the device list mutex.
2136 * In normal cases the cur_devices == fs_devices. But in case
2137 * of deleting a seed device, the cur_devices should point to
2138 * its own fs_devices listed under the fs_devices->seed_list.
2140 cur_devices
= device
->fs_devices
;
2141 mutex_lock(&fs_devices
->device_list_mutex
);
2142 list_del_rcu(&device
->dev_list
);
2144 cur_devices
->num_devices
--;
2145 cur_devices
->total_devices
--;
2146 /* Update total_devices of the parent fs_devices if it's seed */
2147 if (cur_devices
!= fs_devices
)
2148 fs_devices
->total_devices
--;
2150 if (test_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
))
2151 cur_devices
->missing_devices
--;
2153 btrfs_assign_next_active_device(device
, NULL
);
2156 cur_devices
->open_devices
--;
2157 /* remove sysfs entry */
2158 btrfs_sysfs_remove_device(device
);
2161 num_devices
= btrfs_super_num_devices(fs_info
->super_copy
) - 1;
2162 btrfs_set_super_num_devices(fs_info
->super_copy
, num_devices
);
2163 mutex_unlock(&fs_devices
->device_list_mutex
);
2166 * At this point, the device is zero sized and detached from the
2167 * devices list. All that's left is to zero out the old supers and
2170 * We cannot call btrfs_close_bdev() here because we're holding the sb
2171 * write lock, and blkdev_put() will pull in the ->open_mutex on the
2172 * block device and it's dependencies. Instead just flush the device
2173 * and let the caller do the final blkdev_put.
2175 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
2176 btrfs_scratch_superblocks(fs_info
, device
->bdev
,
2179 sync_blockdev(device
->bdev
);
2180 invalidate_bdev(device
->bdev
);
2184 *bdev
= device
->bdev
;
2185 *holder
= device
->holder
;
2187 btrfs_free_device(device
);
2190 * This can happen if cur_devices is the private seed devices list. We
2191 * cannot call close_fs_devices() here because it expects the uuid_mutex
2192 * to be held, but in fact we don't need that for the private
2193 * seed_devices, we can simply decrement cur_devices->opened and then
2194 * remove it from our list and free the fs_devices.
2196 if (cur_devices
->num_devices
== 0) {
2197 list_del_init(&cur_devices
->seed_list
);
2198 ASSERT(cur_devices
->opened
== 1);
2199 cur_devices
->opened
--;
2200 free_fs_devices(cur_devices
);
2203 ret
= btrfs_commit_transaction(trans
);
2208 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
2209 mutex_lock(&fs_info
->chunk_mutex
);
2210 list_add(&device
->dev_alloc_list
,
2211 &fs_devices
->alloc_list
);
2212 device
->fs_devices
->rw_devices
++;
2213 mutex_unlock(&fs_info
->chunk_mutex
);
2218 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device
*srcdev
)
2220 struct btrfs_fs_devices
*fs_devices
;
2222 lockdep_assert_held(&srcdev
->fs_info
->fs_devices
->device_list_mutex
);
2225 * in case of fs with no seed, srcdev->fs_devices will point
2226 * to fs_devices of fs_info. However when the dev being replaced is
2227 * a seed dev it will point to the seed's local fs_devices. In short
2228 * srcdev will have its correct fs_devices in both the cases.
2230 fs_devices
= srcdev
->fs_devices
;
2232 list_del_rcu(&srcdev
->dev_list
);
2233 list_del(&srcdev
->dev_alloc_list
);
2234 fs_devices
->num_devices
--;
2235 if (test_bit(BTRFS_DEV_STATE_MISSING
, &srcdev
->dev_state
))
2236 fs_devices
->missing_devices
--;
2238 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &srcdev
->dev_state
))
2239 fs_devices
->rw_devices
--;
2242 fs_devices
->open_devices
--;
2245 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device
*srcdev
)
2247 struct btrfs_fs_devices
*fs_devices
= srcdev
->fs_devices
;
2249 mutex_lock(&uuid_mutex
);
2251 btrfs_close_bdev(srcdev
);
2253 btrfs_free_device(srcdev
);
2255 /* if this is no devs we rather delete the fs_devices */
2256 if (!fs_devices
->num_devices
) {
2258 * On a mounted FS, num_devices can't be zero unless it's a
2259 * seed. In case of a seed device being replaced, the replace
2260 * target added to the sprout FS, so there will be no more
2261 * device left under the seed FS.
2263 ASSERT(fs_devices
->seeding
);
2265 list_del_init(&fs_devices
->seed_list
);
2266 close_fs_devices(fs_devices
);
2267 free_fs_devices(fs_devices
);
2269 mutex_unlock(&uuid_mutex
);
2272 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device
*tgtdev
)
2274 struct btrfs_fs_devices
*fs_devices
= tgtdev
->fs_info
->fs_devices
;
2276 mutex_lock(&fs_devices
->device_list_mutex
);
2278 btrfs_sysfs_remove_device(tgtdev
);
2281 fs_devices
->open_devices
--;
2283 fs_devices
->num_devices
--;
2285 btrfs_assign_next_active_device(tgtdev
, NULL
);
2287 list_del_rcu(&tgtdev
->dev_list
);
2289 mutex_unlock(&fs_devices
->device_list_mutex
);
2291 btrfs_scratch_superblocks(tgtdev
->fs_info
, tgtdev
->bdev
,
2294 btrfs_close_bdev(tgtdev
);
2296 btrfs_free_device(tgtdev
);
2300 * Populate args from device at path.
2302 * @fs_info: the filesystem
2303 * @args: the args to populate
2304 * @path: the path to the device
2306 * This will read the super block of the device at @path and populate @args with
2307 * the devid, fsid, and uuid. This is meant to be used for ioctls that need to
2308 * lookup a device to operate on, but need to do it before we take any locks.
2309 * This properly handles the special case of "missing" that a user may pass in,
2310 * and does some basic sanity checks. The caller must make sure that @path is
2311 * properly NUL terminated before calling in, and must call
2312 * btrfs_put_dev_args_from_path() in order to free up the temporary fsid and
2315 * Return: 0 for success, -errno for failure
2317 int btrfs_get_dev_args_from_path(struct btrfs_fs_info
*fs_info
,
2318 struct btrfs_dev_lookup_args
*args
,
2321 struct btrfs_super_block
*disk_super
;
2322 struct block_device
*bdev
;
2325 if (!path
|| !path
[0])
2327 if (!strcmp(path
, "missing")) {
2328 args
->missing
= true;
2332 args
->uuid
= kzalloc(BTRFS_UUID_SIZE
, GFP_KERNEL
);
2333 args
->fsid
= kzalloc(BTRFS_FSID_SIZE
, GFP_KERNEL
);
2334 if (!args
->uuid
|| !args
->fsid
) {
2335 btrfs_put_dev_args_from_path(args
);
2339 ret
= btrfs_get_bdev_and_sb(path
, BLK_OPEN_READ
, NULL
, 0,
2340 &bdev
, &disk_super
);
2342 btrfs_put_dev_args_from_path(args
);
2346 args
->devid
= btrfs_stack_device_id(&disk_super
->dev_item
);
2347 memcpy(args
->uuid
, disk_super
->dev_item
.uuid
, BTRFS_UUID_SIZE
);
2348 if (btrfs_fs_incompat(fs_info
, METADATA_UUID
))
2349 memcpy(args
->fsid
, disk_super
->metadata_uuid
, BTRFS_FSID_SIZE
);
2351 memcpy(args
->fsid
, disk_super
->fsid
, BTRFS_FSID_SIZE
);
2352 btrfs_release_disk_super(disk_super
);
2353 blkdev_put(bdev
, NULL
);
2358 * Only use this jointly with btrfs_get_dev_args_from_path() because we will
2359 * allocate our ->uuid and ->fsid pointers, everybody else uses local variables
2360 * that don't need to be freed.
2362 void btrfs_put_dev_args_from_path(struct btrfs_dev_lookup_args
*args
)
2370 struct btrfs_device
*btrfs_find_device_by_devspec(
2371 struct btrfs_fs_info
*fs_info
, u64 devid
,
2372 const char *device_path
)
2374 BTRFS_DEV_LOOKUP_ARGS(args
);
2375 struct btrfs_device
*device
;
2380 device
= btrfs_find_device(fs_info
->fs_devices
, &args
);
2382 return ERR_PTR(-ENOENT
);
2386 ret
= btrfs_get_dev_args_from_path(fs_info
, &args
, device_path
);
2388 return ERR_PTR(ret
);
2389 device
= btrfs_find_device(fs_info
->fs_devices
, &args
);
2390 btrfs_put_dev_args_from_path(&args
);
2392 return ERR_PTR(-ENOENT
);
2396 static struct btrfs_fs_devices
*btrfs_init_sprout(struct btrfs_fs_info
*fs_info
)
2398 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
2399 struct btrfs_fs_devices
*old_devices
;
2400 struct btrfs_fs_devices
*seed_devices
;
2402 lockdep_assert_held(&uuid_mutex
);
2403 if (!fs_devices
->seeding
)
2404 return ERR_PTR(-EINVAL
);
2407 * Private copy of the seed devices, anchored at
2408 * fs_info->fs_devices->seed_list
2410 seed_devices
= alloc_fs_devices(NULL
);
2411 if (IS_ERR(seed_devices
))
2412 return seed_devices
;
2415 * It's necessary to retain a copy of the original seed fs_devices in
2416 * fs_uuids so that filesystems which have been seeded can successfully
2417 * reference the seed device from open_seed_devices. This also supports
2420 old_devices
= clone_fs_devices(fs_devices
);
2421 if (IS_ERR(old_devices
)) {
2422 kfree(seed_devices
);
2426 list_add(&old_devices
->fs_list
, &fs_uuids
);
2428 memcpy(seed_devices
, fs_devices
, sizeof(*seed_devices
));
2429 seed_devices
->opened
= 1;
2430 INIT_LIST_HEAD(&seed_devices
->devices
);
2431 INIT_LIST_HEAD(&seed_devices
->alloc_list
);
2432 mutex_init(&seed_devices
->device_list_mutex
);
2434 return seed_devices
;
2438 * Splice seed devices into the sprout fs_devices.
2439 * Generate a new fsid for the sprouted read-write filesystem.
2441 static void btrfs_setup_sprout(struct btrfs_fs_info
*fs_info
,
2442 struct btrfs_fs_devices
*seed_devices
)
2444 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
2445 struct btrfs_super_block
*disk_super
= fs_info
->super_copy
;
2446 struct btrfs_device
*device
;
2450 * We are updating the fsid, the thread leading to device_list_add()
2451 * could race, so uuid_mutex is needed.
2453 lockdep_assert_held(&uuid_mutex
);
2456 * The threads listed below may traverse dev_list but can do that without
2457 * device_list_mutex:
2458 * - All device ops and balance - as we are in btrfs_exclop_start.
2459 * - Various dev_list readers - are using RCU.
2460 * - btrfs_ioctl_fitrim() - is using RCU.
2462 * For-read threads as below are using device_list_mutex:
2463 * - Readonly scrub btrfs_scrub_dev()
2464 * - Readonly scrub btrfs_scrub_progress()
2465 * - btrfs_get_dev_stats()
2467 lockdep_assert_held(&fs_devices
->device_list_mutex
);
2469 list_splice_init_rcu(&fs_devices
->devices
, &seed_devices
->devices
,
2471 list_for_each_entry(device
, &seed_devices
->devices
, dev_list
)
2472 device
->fs_devices
= seed_devices
;
2474 fs_devices
->seeding
= false;
2475 fs_devices
->num_devices
= 0;
2476 fs_devices
->open_devices
= 0;
2477 fs_devices
->missing_devices
= 0;
2478 fs_devices
->rotating
= false;
2479 list_add(&seed_devices
->seed_list
, &fs_devices
->seed_list
);
2481 generate_random_uuid(fs_devices
->fsid
);
2482 memcpy(fs_devices
->metadata_uuid
, fs_devices
->fsid
, BTRFS_FSID_SIZE
);
2483 memcpy(disk_super
->fsid
, fs_devices
->fsid
, BTRFS_FSID_SIZE
);
2485 super_flags
= btrfs_super_flags(disk_super
) &
2486 ~BTRFS_SUPER_FLAG_SEEDING
;
2487 btrfs_set_super_flags(disk_super
, super_flags
);
2491 * Store the expected generation for seed devices in device items.
2493 static int btrfs_finish_sprout(struct btrfs_trans_handle
*trans
)
2495 BTRFS_DEV_LOOKUP_ARGS(args
);
2496 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2497 struct btrfs_root
*root
= fs_info
->chunk_root
;
2498 struct btrfs_path
*path
;
2499 struct extent_buffer
*leaf
;
2500 struct btrfs_dev_item
*dev_item
;
2501 struct btrfs_device
*device
;
2502 struct btrfs_key key
;
2503 u8 fs_uuid
[BTRFS_FSID_SIZE
];
2504 u8 dev_uuid
[BTRFS_UUID_SIZE
];
2507 path
= btrfs_alloc_path();
2511 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
2513 key
.type
= BTRFS_DEV_ITEM_KEY
;
2516 btrfs_reserve_chunk_metadata(trans
, false);
2517 ret
= btrfs_search_slot(trans
, root
, &key
, path
, 0, 1);
2518 btrfs_trans_release_chunk_metadata(trans
);
2522 leaf
= path
->nodes
[0];
2524 if (path
->slots
[0] >= btrfs_header_nritems(leaf
)) {
2525 ret
= btrfs_next_leaf(root
, path
);
2530 leaf
= path
->nodes
[0];
2531 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
2532 btrfs_release_path(path
);
2536 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
2537 if (key
.objectid
!= BTRFS_DEV_ITEMS_OBJECTID
||
2538 key
.type
!= BTRFS_DEV_ITEM_KEY
)
2541 dev_item
= btrfs_item_ptr(leaf
, path
->slots
[0],
2542 struct btrfs_dev_item
);
2543 args
.devid
= btrfs_device_id(leaf
, dev_item
);
2544 read_extent_buffer(leaf
, dev_uuid
, btrfs_device_uuid(dev_item
),
2546 read_extent_buffer(leaf
, fs_uuid
, btrfs_device_fsid(dev_item
),
2548 args
.uuid
= dev_uuid
;
2549 args
.fsid
= fs_uuid
;
2550 device
= btrfs_find_device(fs_info
->fs_devices
, &args
);
2551 BUG_ON(!device
); /* Logic error */
2553 if (device
->fs_devices
->seeding
) {
2554 btrfs_set_device_generation(leaf
, dev_item
,
2555 device
->generation
);
2556 btrfs_mark_buffer_dirty(trans
, leaf
);
2564 btrfs_free_path(path
);
2568 int btrfs_init_new_device(struct btrfs_fs_info
*fs_info
, const char *device_path
)
2570 struct btrfs_root
*root
= fs_info
->dev_root
;
2571 struct btrfs_trans_handle
*trans
;
2572 struct btrfs_device
*device
;
2573 struct block_device
*bdev
;
2574 struct super_block
*sb
= fs_info
->sb
;
2575 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
2576 struct btrfs_fs_devices
*seed_devices
= NULL
;
2577 u64 orig_super_total_bytes
;
2578 u64 orig_super_num_devices
;
2580 bool seeding_dev
= false;
2581 bool locked
= false;
2583 if (sb_rdonly(sb
) && !fs_devices
->seeding
)
2586 bdev
= blkdev_get_by_path(device_path
, BLK_OPEN_WRITE
,
2587 fs_info
->bdev_holder
, NULL
);
2589 return PTR_ERR(bdev
);
2591 if (!btrfs_check_device_zone_type(fs_info
, bdev
)) {
2596 if (fs_devices
->seeding
) {
2598 down_write(&sb
->s_umount
);
2599 mutex_lock(&uuid_mutex
);
2603 sync_blockdev(bdev
);
2606 list_for_each_entry_rcu(device
, &fs_devices
->devices
, dev_list
) {
2607 if (device
->bdev
== bdev
) {
2615 device
= btrfs_alloc_device(fs_info
, NULL
, NULL
, device_path
);
2616 if (IS_ERR(device
)) {
2617 /* we can safely leave the fs_devices entry around */
2618 ret
= PTR_ERR(device
);
2622 device
->fs_info
= fs_info
;
2623 device
->bdev
= bdev
;
2624 ret
= lookup_bdev(device_path
, &device
->devt
);
2626 goto error_free_device
;
2628 ret
= btrfs_get_dev_zone_info(device
, false);
2630 goto error_free_device
;
2632 trans
= btrfs_start_transaction(root
, 0);
2633 if (IS_ERR(trans
)) {
2634 ret
= PTR_ERR(trans
);
2635 goto error_free_zone
;
2638 set_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
);
2639 device
->generation
= trans
->transid
;
2640 device
->io_width
= fs_info
->sectorsize
;
2641 device
->io_align
= fs_info
->sectorsize
;
2642 device
->sector_size
= fs_info
->sectorsize
;
2643 device
->total_bytes
=
2644 round_down(bdev_nr_bytes(bdev
), fs_info
->sectorsize
);
2645 device
->disk_total_bytes
= device
->total_bytes
;
2646 device
->commit_total_bytes
= device
->total_bytes
;
2647 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
);
2648 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
);
2649 device
->holder
= fs_info
->bdev_holder
;
2650 device
->dev_stats_valid
= 1;
2651 set_blocksize(device
->bdev
, BTRFS_BDEV_BLOCKSIZE
);
2654 btrfs_clear_sb_rdonly(sb
);
2656 /* GFP_KERNEL allocation must not be under device_list_mutex */
2657 seed_devices
= btrfs_init_sprout(fs_info
);
2658 if (IS_ERR(seed_devices
)) {
2659 ret
= PTR_ERR(seed_devices
);
2660 btrfs_abort_transaction(trans
, ret
);
2665 mutex_lock(&fs_devices
->device_list_mutex
);
2667 btrfs_setup_sprout(fs_info
, seed_devices
);
2668 btrfs_assign_next_active_device(fs_info
->fs_devices
->latest_dev
,
2672 device
->fs_devices
= fs_devices
;
2674 mutex_lock(&fs_info
->chunk_mutex
);
2675 list_add_rcu(&device
->dev_list
, &fs_devices
->devices
);
2676 list_add(&device
->dev_alloc_list
, &fs_devices
->alloc_list
);
2677 fs_devices
->num_devices
++;
2678 fs_devices
->open_devices
++;
2679 fs_devices
->rw_devices
++;
2680 fs_devices
->total_devices
++;
2681 fs_devices
->total_rw_bytes
+= device
->total_bytes
;
2683 atomic64_add(device
->total_bytes
, &fs_info
->free_chunk_space
);
2685 if (!bdev_nonrot(bdev
))
2686 fs_devices
->rotating
= true;
2688 orig_super_total_bytes
= btrfs_super_total_bytes(fs_info
->super_copy
);
2689 btrfs_set_super_total_bytes(fs_info
->super_copy
,
2690 round_down(orig_super_total_bytes
+ device
->total_bytes
,
2691 fs_info
->sectorsize
));
2693 orig_super_num_devices
= btrfs_super_num_devices(fs_info
->super_copy
);
2694 btrfs_set_super_num_devices(fs_info
->super_copy
,
2695 orig_super_num_devices
+ 1);
2698 * we've got more storage, clear any full flags on the space
2701 btrfs_clear_space_info_full(fs_info
);
2703 mutex_unlock(&fs_info
->chunk_mutex
);
2705 /* Add sysfs device entry */
2706 btrfs_sysfs_add_device(device
);
2708 mutex_unlock(&fs_devices
->device_list_mutex
);
2711 mutex_lock(&fs_info
->chunk_mutex
);
2712 ret
= init_first_rw_device(trans
);
2713 mutex_unlock(&fs_info
->chunk_mutex
);
2715 btrfs_abort_transaction(trans
, ret
);
2720 ret
= btrfs_add_dev_item(trans
, device
);
2722 btrfs_abort_transaction(trans
, ret
);
2727 ret
= btrfs_finish_sprout(trans
);
2729 btrfs_abort_transaction(trans
, ret
);
2734 * fs_devices now represents the newly sprouted filesystem and
2735 * its fsid has been changed by btrfs_sprout_splice().
2737 btrfs_sysfs_update_sprout_fsid(fs_devices
);
2740 ret
= btrfs_commit_transaction(trans
);
2743 mutex_unlock(&uuid_mutex
);
2744 up_write(&sb
->s_umount
);
2747 if (ret
) /* transaction commit */
2750 ret
= btrfs_relocate_sys_chunks(fs_info
);
2752 btrfs_handle_fs_error(fs_info
, ret
,
2753 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2754 trans
= btrfs_attach_transaction(root
);
2755 if (IS_ERR(trans
)) {
2756 if (PTR_ERR(trans
) == -ENOENT
)
2758 ret
= PTR_ERR(trans
);
2762 ret
= btrfs_commit_transaction(trans
);
2766 * Now that we have written a new super block to this device, check all
2767 * other fs_devices list if device_path alienates any other scanned
2769 * We can ignore the return value as it typically returns -EINVAL and
2770 * only succeeds if the device was an alien.
2772 btrfs_forget_devices(device
->devt
);
2774 /* Update ctime/mtime for blkid or udev */
2775 update_dev_time(device_path
);
2780 btrfs_sysfs_remove_device(device
);
2781 mutex_lock(&fs_info
->fs_devices
->device_list_mutex
);
2782 mutex_lock(&fs_info
->chunk_mutex
);
2783 list_del_rcu(&device
->dev_list
);
2784 list_del(&device
->dev_alloc_list
);
2785 fs_info
->fs_devices
->num_devices
--;
2786 fs_info
->fs_devices
->open_devices
--;
2787 fs_info
->fs_devices
->rw_devices
--;
2788 fs_info
->fs_devices
->total_devices
--;
2789 fs_info
->fs_devices
->total_rw_bytes
-= device
->total_bytes
;
2790 atomic64_sub(device
->total_bytes
, &fs_info
->free_chunk_space
);
2791 btrfs_set_super_total_bytes(fs_info
->super_copy
,
2792 orig_super_total_bytes
);
2793 btrfs_set_super_num_devices(fs_info
->super_copy
,
2794 orig_super_num_devices
);
2795 mutex_unlock(&fs_info
->chunk_mutex
);
2796 mutex_unlock(&fs_info
->fs_devices
->device_list_mutex
);
2799 btrfs_set_sb_rdonly(sb
);
2801 btrfs_end_transaction(trans
);
2803 btrfs_destroy_dev_zone_info(device
);
2805 btrfs_free_device(device
);
2807 blkdev_put(bdev
, fs_info
->bdev_holder
);
2809 mutex_unlock(&uuid_mutex
);
2810 up_write(&sb
->s_umount
);
2815 static noinline
int btrfs_update_device(struct btrfs_trans_handle
*trans
,
2816 struct btrfs_device
*device
)
2819 struct btrfs_path
*path
;
2820 struct btrfs_root
*root
= device
->fs_info
->chunk_root
;
2821 struct btrfs_dev_item
*dev_item
;
2822 struct extent_buffer
*leaf
;
2823 struct btrfs_key key
;
2825 path
= btrfs_alloc_path();
2829 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
2830 key
.type
= BTRFS_DEV_ITEM_KEY
;
2831 key
.offset
= device
->devid
;
2833 ret
= btrfs_search_slot(trans
, root
, &key
, path
, 0, 1);
2842 leaf
= path
->nodes
[0];
2843 dev_item
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_dev_item
);
2845 btrfs_set_device_id(leaf
, dev_item
, device
->devid
);
2846 btrfs_set_device_type(leaf
, dev_item
, device
->type
);
2847 btrfs_set_device_io_align(leaf
, dev_item
, device
->io_align
);
2848 btrfs_set_device_io_width(leaf
, dev_item
, device
->io_width
);
2849 btrfs_set_device_sector_size(leaf
, dev_item
, device
->sector_size
);
2850 btrfs_set_device_total_bytes(leaf
, dev_item
,
2851 btrfs_device_get_disk_total_bytes(device
));
2852 btrfs_set_device_bytes_used(leaf
, dev_item
,
2853 btrfs_device_get_bytes_used(device
));
2854 btrfs_mark_buffer_dirty(trans
, leaf
);
2857 btrfs_free_path(path
);
2861 int btrfs_grow_device(struct btrfs_trans_handle
*trans
,
2862 struct btrfs_device
*device
, u64 new_size
)
2864 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
2865 struct btrfs_super_block
*super_copy
= fs_info
->super_copy
;
2870 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
))
2873 new_size
= round_down(new_size
, fs_info
->sectorsize
);
2875 mutex_lock(&fs_info
->chunk_mutex
);
2876 old_total
= btrfs_super_total_bytes(super_copy
);
2877 diff
= round_down(new_size
- device
->total_bytes
, fs_info
->sectorsize
);
2879 if (new_size
<= device
->total_bytes
||
2880 test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
)) {
2881 mutex_unlock(&fs_info
->chunk_mutex
);
2885 btrfs_set_super_total_bytes(super_copy
,
2886 round_down(old_total
+ diff
, fs_info
->sectorsize
));
2887 device
->fs_devices
->total_rw_bytes
+= diff
;
2888 atomic64_add(diff
, &fs_info
->free_chunk_space
);
2890 btrfs_device_set_total_bytes(device
, new_size
);
2891 btrfs_device_set_disk_total_bytes(device
, new_size
);
2892 btrfs_clear_space_info_full(device
->fs_info
);
2893 if (list_empty(&device
->post_commit_list
))
2894 list_add_tail(&device
->post_commit_list
,
2895 &trans
->transaction
->dev_update_list
);
2896 mutex_unlock(&fs_info
->chunk_mutex
);
2898 btrfs_reserve_chunk_metadata(trans
, false);
2899 ret
= btrfs_update_device(trans
, device
);
2900 btrfs_trans_release_chunk_metadata(trans
);
2905 static int btrfs_free_chunk(struct btrfs_trans_handle
*trans
, u64 chunk_offset
)
2907 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2908 struct btrfs_root
*root
= fs_info
->chunk_root
;
2910 struct btrfs_path
*path
;
2911 struct btrfs_key key
;
2913 path
= btrfs_alloc_path();
2917 key
.objectid
= BTRFS_FIRST_CHUNK_TREE_OBJECTID
;
2918 key
.offset
= chunk_offset
;
2919 key
.type
= BTRFS_CHUNK_ITEM_KEY
;
2921 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
2924 else if (ret
> 0) { /* Logic error or corruption */
2925 btrfs_handle_fs_error(fs_info
, -ENOENT
,
2926 "Failed lookup while freeing chunk.");
2931 ret
= btrfs_del_item(trans
, root
, path
);
2933 btrfs_handle_fs_error(fs_info
, ret
,
2934 "Failed to delete chunk item.");
2936 btrfs_free_path(path
);
2940 static int btrfs_del_sys_chunk(struct btrfs_fs_info
*fs_info
, u64 chunk_offset
)
2942 struct btrfs_super_block
*super_copy
= fs_info
->super_copy
;
2943 struct btrfs_disk_key
*disk_key
;
2944 struct btrfs_chunk
*chunk
;
2951 struct btrfs_key key
;
2953 lockdep_assert_held(&fs_info
->chunk_mutex
);
2954 array_size
= btrfs_super_sys_array_size(super_copy
);
2956 ptr
= super_copy
->sys_chunk_array
;
2959 while (cur
< array_size
) {
2960 disk_key
= (struct btrfs_disk_key
*)ptr
;
2961 btrfs_disk_key_to_cpu(&key
, disk_key
);
2963 len
= sizeof(*disk_key
);
2965 if (key
.type
== BTRFS_CHUNK_ITEM_KEY
) {
2966 chunk
= (struct btrfs_chunk
*)(ptr
+ len
);
2967 num_stripes
= btrfs_stack_chunk_num_stripes(chunk
);
2968 len
+= btrfs_chunk_item_size(num_stripes
);
2973 if (key
.objectid
== BTRFS_FIRST_CHUNK_TREE_OBJECTID
&&
2974 key
.offset
== chunk_offset
) {
2975 memmove(ptr
, ptr
+ len
, array_size
- (cur
+ len
));
2977 btrfs_set_super_sys_array_size(super_copy
, array_size
);
2987 * Find the mapping containing the given logical extent.
2989 * @logical: Logical block offset in bytes.
2990 * @length: Length of extent in bytes.
2992 * Return: Chunk mapping or ERR_PTR.
2994 struct extent_map
*btrfs_get_chunk_map(struct btrfs_fs_info
*fs_info
,
2995 u64 logical
, u64 length
)
2997 struct extent_map_tree
*em_tree
;
2998 struct extent_map
*em
;
3000 em_tree
= &fs_info
->mapping_tree
;
3001 read_lock(&em_tree
->lock
);
3002 em
= lookup_extent_mapping(em_tree
, logical
, length
);
3003 read_unlock(&em_tree
->lock
);
3007 "unable to find chunk map for logical %llu length %llu",
3009 return ERR_PTR(-EINVAL
);
3012 if (em
->start
> logical
|| em
->start
+ em
->len
<= logical
) {
3014 "found a bad chunk map, wanted %llu-%llu, found %llu-%llu",
3015 logical
, logical
+ length
, em
->start
, em
->start
+ em
->len
);
3016 free_extent_map(em
);
3017 return ERR_PTR(-EINVAL
);
3020 /* callers are responsible for dropping em's ref. */
3024 static int remove_chunk_item(struct btrfs_trans_handle
*trans
,
3025 struct map_lookup
*map
, u64 chunk_offset
)
3030 * Removing chunk items and updating the device items in the chunks btree
3031 * requires holding the chunk_mutex.
3032 * See the comment at btrfs_chunk_alloc() for the details.
3034 lockdep_assert_held(&trans
->fs_info
->chunk_mutex
);
3036 for (i
= 0; i
< map
->num_stripes
; i
++) {
3039 ret
= btrfs_update_device(trans
, map
->stripes
[i
].dev
);
3044 return btrfs_free_chunk(trans
, chunk_offset
);
3047 int btrfs_remove_chunk(struct btrfs_trans_handle
*trans
, u64 chunk_offset
)
3049 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
3050 struct extent_map
*em
;
3051 struct map_lookup
*map
;
3052 u64 dev_extent_len
= 0;
3054 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
3056 em
= btrfs_get_chunk_map(fs_info
, chunk_offset
, 1);
3059 * This is a logic error, but we don't want to just rely on the
3060 * user having built with ASSERT enabled, so if ASSERT doesn't
3061 * do anything we still error out.
3066 map
= em
->map_lookup
;
3069 * First delete the device extent items from the devices btree.
3070 * We take the device_list_mutex to avoid racing with the finishing phase
3071 * of a device replace operation. See the comment below before acquiring
3072 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3073 * because that can result in a deadlock when deleting the device extent
3074 * items from the devices btree - COWing an extent buffer from the btree
3075 * may result in allocating a new metadata chunk, which would attempt to
3076 * lock again fs_info->chunk_mutex.
3078 mutex_lock(&fs_devices
->device_list_mutex
);
3079 for (i
= 0; i
< map
->num_stripes
; i
++) {
3080 struct btrfs_device
*device
= map
->stripes
[i
].dev
;
3081 ret
= btrfs_free_dev_extent(trans
, device
,
3082 map
->stripes
[i
].physical
,
3085 mutex_unlock(&fs_devices
->device_list_mutex
);
3086 btrfs_abort_transaction(trans
, ret
);
3090 if (device
->bytes_used
> 0) {
3091 mutex_lock(&fs_info
->chunk_mutex
);
3092 btrfs_device_set_bytes_used(device
,
3093 device
->bytes_used
- dev_extent_len
);
3094 atomic64_add(dev_extent_len
, &fs_info
->free_chunk_space
);
3095 btrfs_clear_space_info_full(fs_info
);
3096 mutex_unlock(&fs_info
->chunk_mutex
);
3099 mutex_unlock(&fs_devices
->device_list_mutex
);
3102 * We acquire fs_info->chunk_mutex for 2 reasons:
3104 * 1) Just like with the first phase of the chunk allocation, we must
3105 * reserve system space, do all chunk btree updates and deletions, and
3106 * update the system chunk array in the superblock while holding this
3107 * mutex. This is for similar reasons as explained on the comment at
3108 * the top of btrfs_chunk_alloc();
3110 * 2) Prevent races with the final phase of a device replace operation
3111 * that replaces the device object associated with the map's stripes,
3112 * because the device object's id can change at any time during that
3113 * final phase of the device replace operation
3114 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3115 * replaced device and then see it with an ID of
3116 * BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3117 * the device item, which does not exists on the chunk btree.
3118 * The finishing phase of device replace acquires both the
3119 * device_list_mutex and the chunk_mutex, in that order, so we are
3120 * safe by just acquiring the chunk_mutex.
3122 trans
->removing_chunk
= true;
3123 mutex_lock(&fs_info
->chunk_mutex
);
3125 check_system_chunk(trans
, map
->type
);
3127 ret
= remove_chunk_item(trans
, map
, chunk_offset
);
3129 * Normally we should not get -ENOSPC since we reserved space before
3130 * through the call to check_system_chunk().
3132 * Despite our system space_info having enough free space, we may not
3133 * be able to allocate extents from its block groups, because all have
3134 * an incompatible profile, which will force us to allocate a new system
3135 * block group with the right profile, or right after we called
3136 * check_system_space() above, a scrub turned the only system block group
3137 * with enough free space into RO mode.
3138 * This is explained with more detail at do_chunk_alloc().
3140 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3142 if (ret
== -ENOSPC
) {
3143 const u64 sys_flags
= btrfs_system_alloc_profile(fs_info
);
3144 struct btrfs_block_group
*sys_bg
;
3146 sys_bg
= btrfs_create_chunk(trans
, sys_flags
);
3147 if (IS_ERR(sys_bg
)) {
3148 ret
= PTR_ERR(sys_bg
);
3149 btrfs_abort_transaction(trans
, ret
);
3153 ret
= btrfs_chunk_alloc_add_chunk_item(trans
, sys_bg
);
3155 btrfs_abort_transaction(trans
, ret
);
3159 ret
= remove_chunk_item(trans
, map
, chunk_offset
);
3161 btrfs_abort_transaction(trans
, ret
);
3165 btrfs_abort_transaction(trans
, ret
);
3169 trace_btrfs_chunk_free(fs_info
, map
, chunk_offset
, em
->len
);
3171 if (map
->type
& BTRFS_BLOCK_GROUP_SYSTEM
) {
3172 ret
= btrfs_del_sys_chunk(fs_info
, chunk_offset
);
3174 btrfs_abort_transaction(trans
, ret
);
3179 mutex_unlock(&fs_info
->chunk_mutex
);
3180 trans
->removing_chunk
= false;
3183 * We are done with chunk btree updates and deletions, so release the
3184 * system space we previously reserved (with check_system_chunk()).
3186 btrfs_trans_release_chunk_metadata(trans
);
3188 ret
= btrfs_remove_block_group(trans
, chunk_offset
, em
);
3190 btrfs_abort_transaction(trans
, ret
);
3195 if (trans
->removing_chunk
) {
3196 mutex_unlock(&fs_info
->chunk_mutex
);
3197 trans
->removing_chunk
= false;
3200 free_extent_map(em
);
3204 int btrfs_relocate_chunk(struct btrfs_fs_info
*fs_info
, u64 chunk_offset
)
3206 struct btrfs_root
*root
= fs_info
->chunk_root
;
3207 struct btrfs_trans_handle
*trans
;
3208 struct btrfs_block_group
*block_group
;
3212 if (btrfs_fs_incompat(fs_info
, EXTENT_TREE_V2
)) {
3214 "relocate: not supported on extent tree v2 yet");
3219 * Prevent races with automatic removal of unused block groups.
3220 * After we relocate and before we remove the chunk with offset
3221 * chunk_offset, automatic removal of the block group can kick in,
3222 * resulting in a failure when calling btrfs_remove_chunk() below.
3224 * Make sure to acquire this mutex before doing a tree search (dev
3225 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3226 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3227 * we release the path used to search the chunk/dev tree and before
3228 * the current task acquires this mutex and calls us.
3230 lockdep_assert_held(&fs_info
->reclaim_bgs_lock
);
3232 /* step one, relocate all the extents inside this chunk */
3233 btrfs_scrub_pause(fs_info
);
3234 ret
= btrfs_relocate_block_group(fs_info
, chunk_offset
);
3235 btrfs_scrub_continue(fs_info
);
3238 * If we had a transaction abort, stop all running scrubs.
3239 * See transaction.c:cleanup_transaction() why we do it here.
3241 if (BTRFS_FS_ERROR(fs_info
))
3242 btrfs_scrub_cancel(fs_info
);
3246 block_group
= btrfs_lookup_block_group(fs_info
, chunk_offset
);
3249 btrfs_discard_cancel_work(&fs_info
->discard_ctl
, block_group
);
3250 length
= block_group
->length
;
3251 btrfs_put_block_group(block_group
);
3254 * On a zoned file system, discard the whole block group, this will
3255 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3256 * resetting the zone fails, don't treat it as a fatal problem from the
3257 * filesystem's point of view.
3259 if (btrfs_is_zoned(fs_info
)) {
3260 ret
= btrfs_discard_extent(fs_info
, chunk_offset
, length
, NULL
);
3263 "failed to reset zone %llu after relocation",
3267 trans
= btrfs_start_trans_remove_block_group(root
->fs_info
,
3269 if (IS_ERR(trans
)) {
3270 ret
= PTR_ERR(trans
);
3271 btrfs_handle_fs_error(root
->fs_info
, ret
, NULL
);
3276 * step two, delete the device extents and the
3277 * chunk tree entries
3279 ret
= btrfs_remove_chunk(trans
, chunk_offset
);
3280 btrfs_end_transaction(trans
);
3284 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info
*fs_info
)
3286 struct btrfs_root
*chunk_root
= fs_info
->chunk_root
;
3287 struct btrfs_path
*path
;
3288 struct extent_buffer
*leaf
;
3289 struct btrfs_chunk
*chunk
;
3290 struct btrfs_key key
;
3291 struct btrfs_key found_key
;
3293 bool retried
= false;
3297 path
= btrfs_alloc_path();
3302 key
.objectid
= BTRFS_FIRST_CHUNK_TREE_OBJECTID
;
3303 key
.offset
= (u64
)-1;
3304 key
.type
= BTRFS_CHUNK_ITEM_KEY
;
3307 mutex_lock(&fs_info
->reclaim_bgs_lock
);
3308 ret
= btrfs_search_slot(NULL
, chunk_root
, &key
, path
, 0, 0);
3310 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3313 BUG_ON(ret
== 0); /* Corruption */
3315 ret
= btrfs_previous_item(chunk_root
, path
, key
.objectid
,
3318 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3324 leaf
= path
->nodes
[0];
3325 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
3327 chunk
= btrfs_item_ptr(leaf
, path
->slots
[0],
3328 struct btrfs_chunk
);
3329 chunk_type
= btrfs_chunk_type(leaf
, chunk
);
3330 btrfs_release_path(path
);
3332 if (chunk_type
& BTRFS_BLOCK_GROUP_SYSTEM
) {
3333 ret
= btrfs_relocate_chunk(fs_info
, found_key
.offset
);
3339 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3341 if (found_key
.offset
== 0)
3343 key
.offset
= found_key
.offset
- 1;
3346 if (failed
&& !retried
) {
3350 } else if (WARN_ON(failed
&& retried
)) {
3354 btrfs_free_path(path
);
3359 * return 1 : allocate a data chunk successfully,
3360 * return <0: errors during allocating a data chunk,
3361 * return 0 : no need to allocate a data chunk.
3363 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info
*fs_info
,
3366 struct btrfs_block_group
*cache
;
3370 cache
= btrfs_lookup_block_group(fs_info
, chunk_offset
);
3372 chunk_type
= cache
->flags
;
3373 btrfs_put_block_group(cache
);
3375 if (!(chunk_type
& BTRFS_BLOCK_GROUP_DATA
))
3378 spin_lock(&fs_info
->data_sinfo
->lock
);
3379 bytes_used
= fs_info
->data_sinfo
->bytes_used
;
3380 spin_unlock(&fs_info
->data_sinfo
->lock
);
3383 struct btrfs_trans_handle
*trans
;
3386 trans
= btrfs_join_transaction(fs_info
->tree_root
);
3388 return PTR_ERR(trans
);
3390 ret
= btrfs_force_chunk_alloc(trans
, BTRFS_BLOCK_GROUP_DATA
);
3391 btrfs_end_transaction(trans
);
3400 static int insert_balance_item(struct btrfs_fs_info
*fs_info
,
3401 struct btrfs_balance_control
*bctl
)
3403 struct btrfs_root
*root
= fs_info
->tree_root
;
3404 struct btrfs_trans_handle
*trans
;
3405 struct btrfs_balance_item
*item
;
3406 struct btrfs_disk_balance_args disk_bargs
;
3407 struct btrfs_path
*path
;
3408 struct extent_buffer
*leaf
;
3409 struct btrfs_key key
;
3412 path
= btrfs_alloc_path();
3416 trans
= btrfs_start_transaction(root
, 0);
3417 if (IS_ERR(trans
)) {
3418 btrfs_free_path(path
);
3419 return PTR_ERR(trans
);
3422 key
.objectid
= BTRFS_BALANCE_OBJECTID
;
3423 key
.type
= BTRFS_TEMPORARY_ITEM_KEY
;
3426 ret
= btrfs_insert_empty_item(trans
, root
, path
, &key
,
3431 leaf
= path
->nodes
[0];
3432 item
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_balance_item
);
3434 memzero_extent_buffer(leaf
, (unsigned long)item
, sizeof(*item
));
3436 btrfs_cpu_balance_args_to_disk(&disk_bargs
, &bctl
->data
);
3437 btrfs_set_balance_data(leaf
, item
, &disk_bargs
);
3438 btrfs_cpu_balance_args_to_disk(&disk_bargs
, &bctl
->meta
);
3439 btrfs_set_balance_meta(leaf
, item
, &disk_bargs
);
3440 btrfs_cpu_balance_args_to_disk(&disk_bargs
, &bctl
->sys
);
3441 btrfs_set_balance_sys(leaf
, item
, &disk_bargs
);
3443 btrfs_set_balance_flags(leaf
, item
, bctl
->flags
);
3445 btrfs_mark_buffer_dirty(trans
, leaf
);
3447 btrfs_free_path(path
);
3448 err
= btrfs_commit_transaction(trans
);
3454 static int del_balance_item(struct btrfs_fs_info
*fs_info
)
3456 struct btrfs_root
*root
= fs_info
->tree_root
;
3457 struct btrfs_trans_handle
*trans
;
3458 struct btrfs_path
*path
;
3459 struct btrfs_key key
;
3462 path
= btrfs_alloc_path();
3466 trans
= btrfs_start_transaction_fallback_global_rsv(root
, 0);
3467 if (IS_ERR(trans
)) {
3468 btrfs_free_path(path
);
3469 return PTR_ERR(trans
);
3472 key
.objectid
= BTRFS_BALANCE_OBJECTID
;
3473 key
.type
= BTRFS_TEMPORARY_ITEM_KEY
;
3476 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
3484 ret
= btrfs_del_item(trans
, root
, path
);
3486 btrfs_free_path(path
);
3487 err
= btrfs_commit_transaction(trans
);
3494 * This is a heuristic used to reduce the number of chunks balanced on
3495 * resume after balance was interrupted.
3497 static void update_balance_args(struct btrfs_balance_control
*bctl
)
3500 * Turn on soft mode for chunk types that were being converted.
3502 if (bctl
->data
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)
3503 bctl
->data
.flags
|= BTRFS_BALANCE_ARGS_SOFT
;
3504 if (bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)
3505 bctl
->sys
.flags
|= BTRFS_BALANCE_ARGS_SOFT
;
3506 if (bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)
3507 bctl
->meta
.flags
|= BTRFS_BALANCE_ARGS_SOFT
;
3510 * Turn on usage filter if is not already used. The idea is
3511 * that chunks that we have already balanced should be
3512 * reasonably full. Don't do it for chunks that are being
3513 * converted - that will keep us from relocating unconverted
3514 * (albeit full) chunks.
3516 if (!(bctl
->data
.flags
& BTRFS_BALANCE_ARGS_USAGE
) &&
3517 !(bctl
->data
.flags
& BTRFS_BALANCE_ARGS_USAGE_RANGE
) &&
3518 !(bctl
->data
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)) {
3519 bctl
->data
.flags
|= BTRFS_BALANCE_ARGS_USAGE
;
3520 bctl
->data
.usage
= 90;
3522 if (!(bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_USAGE
) &&
3523 !(bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_USAGE_RANGE
) &&
3524 !(bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)) {
3525 bctl
->sys
.flags
|= BTRFS_BALANCE_ARGS_USAGE
;
3526 bctl
->sys
.usage
= 90;
3528 if (!(bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_USAGE
) &&
3529 !(bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_USAGE_RANGE
) &&
3530 !(bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_CONVERT
)) {
3531 bctl
->meta
.flags
|= BTRFS_BALANCE_ARGS_USAGE
;
3532 bctl
->meta
.usage
= 90;
3537 * Clear the balance status in fs_info and delete the balance item from disk.
3539 static void reset_balance_state(struct btrfs_fs_info
*fs_info
)
3541 struct btrfs_balance_control
*bctl
= fs_info
->balance_ctl
;
3544 BUG_ON(!fs_info
->balance_ctl
);
3546 spin_lock(&fs_info
->balance_lock
);
3547 fs_info
->balance_ctl
= NULL
;
3548 spin_unlock(&fs_info
->balance_lock
);
3551 ret
= del_balance_item(fs_info
);
3553 btrfs_handle_fs_error(fs_info
, ret
, NULL
);
3557 * Balance filters. Return 1 if chunk should be filtered out
3558 * (should not be balanced).
3560 static int chunk_profiles_filter(u64 chunk_type
,
3561 struct btrfs_balance_args
*bargs
)
3563 chunk_type
= chunk_to_extended(chunk_type
) &
3564 BTRFS_EXTENDED_PROFILE_MASK
;
3566 if (bargs
->profiles
& chunk_type
)
3572 static int chunk_usage_range_filter(struct btrfs_fs_info
*fs_info
, u64 chunk_offset
,
3573 struct btrfs_balance_args
*bargs
)
3575 struct btrfs_block_group
*cache
;
3577 u64 user_thresh_min
;
3578 u64 user_thresh_max
;
3581 cache
= btrfs_lookup_block_group(fs_info
, chunk_offset
);
3582 chunk_used
= cache
->used
;
3584 if (bargs
->usage_min
== 0)
3585 user_thresh_min
= 0;
3587 user_thresh_min
= mult_perc(cache
->length
, bargs
->usage_min
);
3589 if (bargs
->usage_max
== 0)
3590 user_thresh_max
= 1;
3591 else if (bargs
->usage_max
> 100)
3592 user_thresh_max
= cache
->length
;
3594 user_thresh_max
= mult_perc(cache
->length
, bargs
->usage_max
);
3596 if (user_thresh_min
<= chunk_used
&& chunk_used
< user_thresh_max
)
3599 btrfs_put_block_group(cache
);
3603 static int chunk_usage_filter(struct btrfs_fs_info
*fs_info
,
3604 u64 chunk_offset
, struct btrfs_balance_args
*bargs
)
3606 struct btrfs_block_group
*cache
;
3607 u64 chunk_used
, user_thresh
;
3610 cache
= btrfs_lookup_block_group(fs_info
, chunk_offset
);
3611 chunk_used
= cache
->used
;
3613 if (bargs
->usage_min
== 0)
3615 else if (bargs
->usage
> 100)
3616 user_thresh
= cache
->length
;
3618 user_thresh
= mult_perc(cache
->length
, bargs
->usage
);
3620 if (chunk_used
< user_thresh
)
3623 btrfs_put_block_group(cache
);
3627 static int chunk_devid_filter(struct extent_buffer
*leaf
,
3628 struct btrfs_chunk
*chunk
,
3629 struct btrfs_balance_args
*bargs
)
3631 struct btrfs_stripe
*stripe
;
3632 int num_stripes
= btrfs_chunk_num_stripes(leaf
, chunk
);
3635 for (i
= 0; i
< num_stripes
; i
++) {
3636 stripe
= btrfs_stripe_nr(chunk
, i
);
3637 if (btrfs_stripe_devid(leaf
, stripe
) == bargs
->devid
)
3644 static u64
calc_data_stripes(u64 type
, int num_stripes
)
3646 const int index
= btrfs_bg_flags_to_raid_index(type
);
3647 const int ncopies
= btrfs_raid_array
[index
].ncopies
;
3648 const int nparity
= btrfs_raid_array
[index
].nparity
;
3650 return (num_stripes
- nparity
) / ncopies
;
3653 /* [pstart, pend) */
3654 static int chunk_drange_filter(struct extent_buffer
*leaf
,
3655 struct btrfs_chunk
*chunk
,
3656 struct btrfs_balance_args
*bargs
)
3658 struct btrfs_stripe
*stripe
;
3659 int num_stripes
= btrfs_chunk_num_stripes(leaf
, chunk
);
3666 if (!(bargs
->flags
& BTRFS_BALANCE_ARGS_DEVID
))
3669 type
= btrfs_chunk_type(leaf
, chunk
);
3670 factor
= calc_data_stripes(type
, num_stripes
);
3672 for (i
= 0; i
< num_stripes
; i
++) {
3673 stripe
= btrfs_stripe_nr(chunk
, i
);
3674 if (btrfs_stripe_devid(leaf
, stripe
) != bargs
->devid
)
3677 stripe_offset
= btrfs_stripe_offset(leaf
, stripe
);
3678 stripe_length
= btrfs_chunk_length(leaf
, chunk
);
3679 stripe_length
= div_u64(stripe_length
, factor
);
3681 if (stripe_offset
< bargs
->pend
&&
3682 stripe_offset
+ stripe_length
> bargs
->pstart
)
3689 /* [vstart, vend) */
3690 static int chunk_vrange_filter(struct extent_buffer
*leaf
,
3691 struct btrfs_chunk
*chunk
,
3693 struct btrfs_balance_args
*bargs
)
3695 if (chunk_offset
< bargs
->vend
&&
3696 chunk_offset
+ btrfs_chunk_length(leaf
, chunk
) > bargs
->vstart
)
3697 /* at least part of the chunk is inside this vrange */
3703 static int chunk_stripes_range_filter(struct extent_buffer
*leaf
,
3704 struct btrfs_chunk
*chunk
,
3705 struct btrfs_balance_args
*bargs
)
3707 int num_stripes
= btrfs_chunk_num_stripes(leaf
, chunk
);
3709 if (bargs
->stripes_min
<= num_stripes
3710 && num_stripes
<= bargs
->stripes_max
)
3716 static int chunk_soft_convert_filter(u64 chunk_type
,
3717 struct btrfs_balance_args
*bargs
)
3719 if (!(bargs
->flags
& BTRFS_BALANCE_ARGS_CONVERT
))
3722 chunk_type
= chunk_to_extended(chunk_type
) &
3723 BTRFS_EXTENDED_PROFILE_MASK
;
3725 if (bargs
->target
== chunk_type
)
3731 static int should_balance_chunk(struct extent_buffer
*leaf
,
3732 struct btrfs_chunk
*chunk
, u64 chunk_offset
)
3734 struct btrfs_fs_info
*fs_info
= leaf
->fs_info
;
3735 struct btrfs_balance_control
*bctl
= fs_info
->balance_ctl
;
3736 struct btrfs_balance_args
*bargs
= NULL
;
3737 u64 chunk_type
= btrfs_chunk_type(leaf
, chunk
);
3740 if (!((chunk_type
& BTRFS_BLOCK_GROUP_TYPE_MASK
) &
3741 (bctl
->flags
& BTRFS_BALANCE_TYPE_MASK
))) {
3745 if (chunk_type
& BTRFS_BLOCK_GROUP_DATA
)
3746 bargs
= &bctl
->data
;
3747 else if (chunk_type
& BTRFS_BLOCK_GROUP_SYSTEM
)
3749 else if (chunk_type
& BTRFS_BLOCK_GROUP_METADATA
)
3750 bargs
= &bctl
->meta
;
3752 /* profiles filter */
3753 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_PROFILES
) &&
3754 chunk_profiles_filter(chunk_type
, bargs
)) {
3759 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_USAGE
) &&
3760 chunk_usage_filter(fs_info
, chunk_offset
, bargs
)) {
3762 } else if ((bargs
->flags
& BTRFS_BALANCE_ARGS_USAGE_RANGE
) &&
3763 chunk_usage_range_filter(fs_info
, chunk_offset
, bargs
)) {
3768 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_DEVID
) &&
3769 chunk_devid_filter(leaf
, chunk
, bargs
)) {
3773 /* drange filter, makes sense only with devid filter */
3774 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_DRANGE
) &&
3775 chunk_drange_filter(leaf
, chunk
, bargs
)) {
3780 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_VRANGE
) &&
3781 chunk_vrange_filter(leaf
, chunk
, chunk_offset
, bargs
)) {
3785 /* stripes filter */
3786 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_STRIPES_RANGE
) &&
3787 chunk_stripes_range_filter(leaf
, chunk
, bargs
)) {
3791 /* soft profile changing mode */
3792 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_SOFT
) &&
3793 chunk_soft_convert_filter(chunk_type
, bargs
)) {
3798 * limited by count, must be the last filter
3800 if ((bargs
->flags
& BTRFS_BALANCE_ARGS_LIMIT
)) {
3801 if (bargs
->limit
== 0)
3805 } else if ((bargs
->flags
& BTRFS_BALANCE_ARGS_LIMIT_RANGE
)) {
3807 * Same logic as the 'limit' filter; the minimum cannot be
3808 * determined here because we do not have the global information
3809 * about the count of all chunks that satisfy the filters.
3811 if (bargs
->limit_max
== 0)
3820 static int __btrfs_balance(struct btrfs_fs_info
*fs_info
)
3822 struct btrfs_balance_control
*bctl
= fs_info
->balance_ctl
;
3823 struct btrfs_root
*chunk_root
= fs_info
->chunk_root
;
3825 struct btrfs_chunk
*chunk
;
3826 struct btrfs_path
*path
= NULL
;
3827 struct btrfs_key key
;
3828 struct btrfs_key found_key
;
3829 struct extent_buffer
*leaf
;
3832 int enospc_errors
= 0;
3833 bool counting
= true;
3834 /* The single value limit and min/max limits use the same bytes in the */
3835 u64 limit_data
= bctl
->data
.limit
;
3836 u64 limit_meta
= bctl
->meta
.limit
;
3837 u64 limit_sys
= bctl
->sys
.limit
;
3841 int chunk_reserved
= 0;
3843 path
= btrfs_alloc_path();
3849 /* zero out stat counters */
3850 spin_lock(&fs_info
->balance_lock
);
3851 memset(&bctl
->stat
, 0, sizeof(bctl
->stat
));
3852 spin_unlock(&fs_info
->balance_lock
);
3856 * The single value limit and min/max limits use the same bytes
3859 bctl
->data
.limit
= limit_data
;
3860 bctl
->meta
.limit
= limit_meta
;
3861 bctl
->sys
.limit
= limit_sys
;
3863 key
.objectid
= BTRFS_FIRST_CHUNK_TREE_OBJECTID
;
3864 key
.offset
= (u64
)-1;
3865 key
.type
= BTRFS_CHUNK_ITEM_KEY
;
3868 if ((!counting
&& atomic_read(&fs_info
->balance_pause_req
)) ||
3869 atomic_read(&fs_info
->balance_cancel_req
)) {
3874 mutex_lock(&fs_info
->reclaim_bgs_lock
);
3875 ret
= btrfs_search_slot(NULL
, chunk_root
, &key
, path
, 0, 0);
3877 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3882 * this shouldn't happen, it means the last relocate
3886 BUG(); /* FIXME break ? */
3888 ret
= btrfs_previous_item(chunk_root
, path
, 0,
3889 BTRFS_CHUNK_ITEM_KEY
);
3891 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3896 leaf
= path
->nodes
[0];
3897 slot
= path
->slots
[0];
3898 btrfs_item_key_to_cpu(leaf
, &found_key
, slot
);
3900 if (found_key
.objectid
!= key
.objectid
) {
3901 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3905 chunk
= btrfs_item_ptr(leaf
, slot
, struct btrfs_chunk
);
3906 chunk_type
= btrfs_chunk_type(leaf
, chunk
);
3909 spin_lock(&fs_info
->balance_lock
);
3910 bctl
->stat
.considered
++;
3911 spin_unlock(&fs_info
->balance_lock
);
3914 ret
= should_balance_chunk(leaf
, chunk
, found_key
.offset
);
3916 btrfs_release_path(path
);
3918 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3923 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3924 spin_lock(&fs_info
->balance_lock
);
3925 bctl
->stat
.expected
++;
3926 spin_unlock(&fs_info
->balance_lock
);
3928 if (chunk_type
& BTRFS_BLOCK_GROUP_DATA
)
3930 else if (chunk_type
& BTRFS_BLOCK_GROUP_SYSTEM
)
3932 else if (chunk_type
& BTRFS_BLOCK_GROUP_METADATA
)
3939 * Apply limit_min filter, no need to check if the LIMITS
3940 * filter is used, limit_min is 0 by default
3942 if (((chunk_type
& BTRFS_BLOCK_GROUP_DATA
) &&
3943 count_data
< bctl
->data
.limit_min
)
3944 || ((chunk_type
& BTRFS_BLOCK_GROUP_METADATA
) &&
3945 count_meta
< bctl
->meta
.limit_min
)
3946 || ((chunk_type
& BTRFS_BLOCK_GROUP_SYSTEM
) &&
3947 count_sys
< bctl
->sys
.limit_min
)) {
3948 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3952 if (!chunk_reserved
) {
3954 * We may be relocating the only data chunk we have,
3955 * which could potentially end up with losing data's
3956 * raid profile, so lets allocate an empty one in
3959 ret
= btrfs_may_alloc_data_chunk(fs_info
,
3962 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3964 } else if (ret
== 1) {
3969 ret
= btrfs_relocate_chunk(fs_info
, found_key
.offset
);
3970 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
3971 if (ret
== -ENOSPC
) {
3973 } else if (ret
== -ETXTBSY
) {
3975 "skipping relocation of block group %llu due to active swapfile",
3981 spin_lock(&fs_info
->balance_lock
);
3982 bctl
->stat
.completed
++;
3983 spin_unlock(&fs_info
->balance_lock
);
3986 if (found_key
.offset
== 0)
3988 key
.offset
= found_key
.offset
- 1;
3992 btrfs_release_path(path
);
3997 btrfs_free_path(path
);
3998 if (enospc_errors
) {
3999 btrfs_info(fs_info
, "%d enospc errors during balance",
4009 * See if a given profile is valid and reduced.
4011 * @flags: profile to validate
4012 * @extended: if true @flags is treated as an extended profile
4014 static int alloc_profile_is_valid(u64 flags
, int extended
)
4016 u64 mask
= (extended
? BTRFS_EXTENDED_PROFILE_MASK
:
4017 BTRFS_BLOCK_GROUP_PROFILE_MASK
);
4019 flags
&= ~BTRFS_BLOCK_GROUP_TYPE_MASK
;
4021 /* 1) check that all other bits are zeroed */
4025 /* 2) see if profile is reduced */
4027 return !extended
; /* "0" is valid for usual profiles */
4029 return has_single_bit_set(flags
);
4033 * Validate target profile against allowed profiles and return true if it's OK.
4034 * Otherwise print the error message and return false.
4036 static inline int validate_convert_profile(struct btrfs_fs_info
*fs_info
,
4037 const struct btrfs_balance_args
*bargs
,
4038 u64 allowed
, const char *type
)
4040 if (!(bargs
->flags
& BTRFS_BALANCE_ARGS_CONVERT
))
4043 /* Profile is valid and does not have bits outside of the allowed set */
4044 if (alloc_profile_is_valid(bargs
->target
, 1) &&
4045 (bargs
->target
& ~allowed
) == 0)
4048 btrfs_err(fs_info
, "balance: invalid convert %s profile %s",
4049 type
, btrfs_bg_type_to_raid_name(bargs
->target
));
4054 * Fill @buf with textual description of balance filter flags @bargs, up to
4055 * @size_buf including the terminating null. The output may be trimmed if it
4056 * does not fit into the provided buffer.
4058 static void describe_balance_args(struct btrfs_balance_args
*bargs
, char *buf
,
4062 u32 size_bp
= size_buf
;
4064 u64 flags
= bargs
->flags
;
4065 char tmp_buf
[128] = {'\0'};
4070 #define CHECK_APPEND_NOARG(a) \
4072 ret = snprintf(bp, size_bp, (a)); \
4073 if (ret < 0 || ret >= size_bp) \
4074 goto out_overflow; \
4079 #define CHECK_APPEND_1ARG(a, v1) \
4081 ret = snprintf(bp, size_bp, (a), (v1)); \
4082 if (ret < 0 || ret >= size_bp) \
4083 goto out_overflow; \
4088 #define CHECK_APPEND_2ARG(a, v1, v2) \
4090 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
4091 if (ret < 0 || ret >= size_bp) \
4092 goto out_overflow; \
4097 if (flags
& BTRFS_BALANCE_ARGS_CONVERT
)
4098 CHECK_APPEND_1ARG("convert=%s,",
4099 btrfs_bg_type_to_raid_name(bargs
->target
));
4101 if (flags
& BTRFS_BALANCE_ARGS_SOFT
)
4102 CHECK_APPEND_NOARG("soft,");
4104 if (flags
& BTRFS_BALANCE_ARGS_PROFILES
) {
4105 btrfs_describe_block_groups(bargs
->profiles
, tmp_buf
,
4107 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf
);
4110 if (flags
& BTRFS_BALANCE_ARGS_USAGE
)
4111 CHECK_APPEND_1ARG("usage=%llu,", bargs
->usage
);
4113 if (flags
& BTRFS_BALANCE_ARGS_USAGE_RANGE
)
4114 CHECK_APPEND_2ARG("usage=%u..%u,",
4115 bargs
->usage_min
, bargs
->usage_max
);
4117 if (flags
& BTRFS_BALANCE_ARGS_DEVID
)
4118 CHECK_APPEND_1ARG("devid=%llu,", bargs
->devid
);
4120 if (flags
& BTRFS_BALANCE_ARGS_DRANGE
)
4121 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4122 bargs
->pstart
, bargs
->pend
);
4124 if (flags
& BTRFS_BALANCE_ARGS_VRANGE
)
4125 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4126 bargs
->vstart
, bargs
->vend
);
4128 if (flags
& BTRFS_BALANCE_ARGS_LIMIT
)
4129 CHECK_APPEND_1ARG("limit=%llu,", bargs
->limit
);
4131 if (flags
& BTRFS_BALANCE_ARGS_LIMIT_RANGE
)
4132 CHECK_APPEND_2ARG("limit=%u..%u,",
4133 bargs
->limit_min
, bargs
->limit_max
);
4135 if (flags
& BTRFS_BALANCE_ARGS_STRIPES_RANGE
)
4136 CHECK_APPEND_2ARG("stripes=%u..%u,",
4137 bargs
->stripes_min
, bargs
->stripes_max
);
4139 #undef CHECK_APPEND_2ARG
4140 #undef CHECK_APPEND_1ARG
4141 #undef CHECK_APPEND_NOARG
4145 if (size_bp
< size_buf
)
4146 buf
[size_buf
- size_bp
- 1] = '\0'; /* remove last , */
4151 static void describe_balance_start_or_resume(struct btrfs_fs_info
*fs_info
)
4153 u32 size_buf
= 1024;
4154 char tmp_buf
[192] = {'\0'};
4157 u32 size_bp
= size_buf
;
4159 struct btrfs_balance_control
*bctl
= fs_info
->balance_ctl
;
4161 buf
= kzalloc(size_buf
, GFP_KERNEL
);
4167 #define CHECK_APPEND_1ARG(a, v1) \
4169 ret = snprintf(bp, size_bp, (a), (v1)); \
4170 if (ret < 0 || ret >= size_bp) \
4171 goto out_overflow; \
4176 if (bctl
->flags
& BTRFS_BALANCE_FORCE
)
4177 CHECK_APPEND_1ARG("%s", "-f ");
4179 if (bctl
->flags
& BTRFS_BALANCE_DATA
) {
4180 describe_balance_args(&bctl
->data
, tmp_buf
, sizeof(tmp_buf
));
4181 CHECK_APPEND_1ARG("-d%s ", tmp_buf
);
4184 if (bctl
->flags
& BTRFS_BALANCE_METADATA
) {
4185 describe_balance_args(&bctl
->meta
, tmp_buf
, sizeof(tmp_buf
));
4186 CHECK_APPEND_1ARG("-m%s ", tmp_buf
);
4189 if (bctl
->flags
& BTRFS_BALANCE_SYSTEM
) {
4190 describe_balance_args(&bctl
->sys
, tmp_buf
, sizeof(tmp_buf
));
4191 CHECK_APPEND_1ARG("-s%s ", tmp_buf
);
4194 #undef CHECK_APPEND_1ARG
4198 if (size_bp
< size_buf
)
4199 buf
[size_buf
- size_bp
- 1] = '\0'; /* remove last " " */
4200 btrfs_info(fs_info
, "balance: %s %s",
4201 (bctl
->flags
& BTRFS_BALANCE_RESUME
) ?
4202 "resume" : "start", buf
);
4208 * Should be called with balance mutexe held
4210 int btrfs_balance(struct btrfs_fs_info
*fs_info
,
4211 struct btrfs_balance_control
*bctl
,
4212 struct btrfs_ioctl_balance_args
*bargs
)
4214 u64 meta_target
, data_target
;
4220 bool reducing_redundancy
;
4221 bool paused
= false;
4224 if (btrfs_fs_closing(fs_info
) ||
4225 atomic_read(&fs_info
->balance_pause_req
) ||
4226 btrfs_should_cancel_balance(fs_info
)) {
4231 allowed
= btrfs_super_incompat_flags(fs_info
->super_copy
);
4232 if (allowed
& BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS
)
4236 * In case of mixed groups both data and meta should be picked,
4237 * and identical options should be given for both of them.
4239 allowed
= BTRFS_BALANCE_DATA
| BTRFS_BALANCE_METADATA
;
4240 if (mixed
&& (bctl
->flags
& allowed
)) {
4241 if (!(bctl
->flags
& BTRFS_BALANCE_DATA
) ||
4242 !(bctl
->flags
& BTRFS_BALANCE_METADATA
) ||
4243 memcmp(&bctl
->data
, &bctl
->meta
, sizeof(bctl
->data
))) {
4245 "balance: mixed groups data and metadata options must be the same");
4252 * rw_devices will not change at the moment, device add/delete/replace
4255 num_devices
= fs_info
->fs_devices
->rw_devices
;
4258 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4259 * special bit for it, to make it easier to distinguish. Thus we need
4260 * to set it manually, or balance would refuse the profile.
4262 allowed
= BTRFS_AVAIL_ALLOC_BIT_SINGLE
;
4263 for (i
= 0; i
< ARRAY_SIZE(btrfs_raid_array
); i
++)
4264 if (num_devices
>= btrfs_raid_array
[i
].devs_min
)
4265 allowed
|= btrfs_raid_array
[i
].bg_flag
;
4267 if (!validate_convert_profile(fs_info
, &bctl
->data
, allowed
, "data") ||
4268 !validate_convert_profile(fs_info
, &bctl
->meta
, allowed
, "metadata") ||
4269 !validate_convert_profile(fs_info
, &bctl
->sys
, allowed
, "system")) {
4275 * Allow to reduce metadata or system integrity only if force set for
4276 * profiles with redundancy (copies, parity)
4279 for (i
= 0; i
< ARRAY_SIZE(btrfs_raid_array
); i
++) {
4280 if (btrfs_raid_array
[i
].ncopies
>= 2 ||
4281 btrfs_raid_array
[i
].tolerated_failures
>= 1)
4282 allowed
|= btrfs_raid_array
[i
].bg_flag
;
4285 seq
= read_seqbegin(&fs_info
->profiles_lock
);
4287 if (((bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) &&
4288 (fs_info
->avail_system_alloc_bits
& allowed
) &&
4289 !(bctl
->sys
.target
& allowed
)) ||
4290 ((bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) &&
4291 (fs_info
->avail_metadata_alloc_bits
& allowed
) &&
4292 !(bctl
->meta
.target
& allowed
)))
4293 reducing_redundancy
= true;
4295 reducing_redundancy
= false;
4297 /* if we're not converting, the target field is uninitialized */
4298 meta_target
= (bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) ?
4299 bctl
->meta
.target
: fs_info
->avail_metadata_alloc_bits
;
4300 data_target
= (bctl
->data
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) ?
4301 bctl
->data
.target
: fs_info
->avail_data_alloc_bits
;
4302 } while (read_seqretry(&fs_info
->profiles_lock
, seq
));
4304 if (reducing_redundancy
) {
4305 if (bctl
->flags
& BTRFS_BALANCE_FORCE
) {
4307 "balance: force reducing metadata redundancy");
4310 "balance: reduces metadata redundancy, use --force if you want this");
4316 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target
) <
4317 btrfs_get_num_tolerated_disk_barrier_failures(data_target
)) {
4319 "balance: metadata profile %s has lower redundancy than data profile %s",
4320 btrfs_bg_type_to_raid_name(meta_target
),
4321 btrfs_bg_type_to_raid_name(data_target
));
4324 ret
= insert_balance_item(fs_info
, bctl
);
4325 if (ret
&& ret
!= -EEXIST
)
4328 if (!(bctl
->flags
& BTRFS_BALANCE_RESUME
)) {
4329 BUG_ON(ret
== -EEXIST
);
4330 BUG_ON(fs_info
->balance_ctl
);
4331 spin_lock(&fs_info
->balance_lock
);
4332 fs_info
->balance_ctl
= bctl
;
4333 spin_unlock(&fs_info
->balance_lock
);
4335 BUG_ON(ret
!= -EEXIST
);
4336 spin_lock(&fs_info
->balance_lock
);
4337 update_balance_args(bctl
);
4338 spin_unlock(&fs_info
->balance_lock
);
4341 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
));
4342 set_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
);
4343 describe_balance_start_or_resume(fs_info
);
4344 mutex_unlock(&fs_info
->balance_mutex
);
4346 ret
= __btrfs_balance(fs_info
);
4348 mutex_lock(&fs_info
->balance_mutex
);
4349 if (ret
== -ECANCELED
&& atomic_read(&fs_info
->balance_pause_req
)) {
4350 btrfs_info(fs_info
, "balance: paused");
4351 btrfs_exclop_balance(fs_info
, BTRFS_EXCLOP_BALANCE_PAUSED
);
4355 * Balance can be canceled by:
4357 * - Regular cancel request
4358 * Then ret == -ECANCELED and balance_cancel_req > 0
4360 * - Fatal signal to "btrfs" process
4361 * Either the signal caught by wait_reserve_ticket() and callers
4362 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4364 * Either way, in this case balance_cancel_req = 0, and
4365 * ret == -EINTR or ret == -ECANCELED.
4367 * So here we only check the return value to catch canceled balance.
4369 else if (ret
== -ECANCELED
|| ret
== -EINTR
)
4370 btrfs_info(fs_info
, "balance: canceled");
4372 btrfs_info(fs_info
, "balance: ended with status: %d", ret
);
4374 clear_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
);
4377 memset(bargs
, 0, sizeof(*bargs
));
4378 btrfs_update_ioctl_balance_args(fs_info
, bargs
);
4381 /* We didn't pause, we can clean everything up. */
4383 reset_balance_state(fs_info
);
4384 btrfs_exclop_finish(fs_info
);
4387 wake_up(&fs_info
->balance_wait_q
);
4391 if (bctl
->flags
& BTRFS_BALANCE_RESUME
)
4392 reset_balance_state(fs_info
);
4395 btrfs_exclop_finish(fs_info
);
4400 static int balance_kthread(void *data
)
4402 struct btrfs_fs_info
*fs_info
= data
;
4405 sb_start_write(fs_info
->sb
);
4406 mutex_lock(&fs_info
->balance_mutex
);
4407 if (fs_info
->balance_ctl
)
4408 ret
= btrfs_balance(fs_info
, fs_info
->balance_ctl
, NULL
);
4409 mutex_unlock(&fs_info
->balance_mutex
);
4410 sb_end_write(fs_info
->sb
);
4415 int btrfs_resume_balance_async(struct btrfs_fs_info
*fs_info
)
4417 struct task_struct
*tsk
;
4419 mutex_lock(&fs_info
->balance_mutex
);
4420 if (!fs_info
->balance_ctl
) {
4421 mutex_unlock(&fs_info
->balance_mutex
);
4424 mutex_unlock(&fs_info
->balance_mutex
);
4426 if (btrfs_test_opt(fs_info
, SKIP_BALANCE
)) {
4427 btrfs_info(fs_info
, "balance: resume skipped");
4431 spin_lock(&fs_info
->super_lock
);
4432 ASSERT(fs_info
->exclusive_operation
== BTRFS_EXCLOP_BALANCE_PAUSED
);
4433 fs_info
->exclusive_operation
= BTRFS_EXCLOP_BALANCE
;
4434 spin_unlock(&fs_info
->super_lock
);
4436 * A ro->rw remount sequence should continue with the paused balance
4437 * regardless of who pauses it, system or the user as of now, so set
4440 spin_lock(&fs_info
->balance_lock
);
4441 fs_info
->balance_ctl
->flags
|= BTRFS_BALANCE_RESUME
;
4442 spin_unlock(&fs_info
->balance_lock
);
4444 tsk
= kthread_run(balance_kthread
, fs_info
, "btrfs-balance");
4445 return PTR_ERR_OR_ZERO(tsk
);
4448 int btrfs_recover_balance(struct btrfs_fs_info
*fs_info
)
4450 struct btrfs_balance_control
*bctl
;
4451 struct btrfs_balance_item
*item
;
4452 struct btrfs_disk_balance_args disk_bargs
;
4453 struct btrfs_path
*path
;
4454 struct extent_buffer
*leaf
;
4455 struct btrfs_key key
;
4458 path
= btrfs_alloc_path();
4462 key
.objectid
= BTRFS_BALANCE_OBJECTID
;
4463 key
.type
= BTRFS_TEMPORARY_ITEM_KEY
;
4466 ret
= btrfs_search_slot(NULL
, fs_info
->tree_root
, &key
, path
, 0, 0);
4469 if (ret
> 0) { /* ret = -ENOENT; */
4474 bctl
= kzalloc(sizeof(*bctl
), GFP_NOFS
);
4480 leaf
= path
->nodes
[0];
4481 item
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_balance_item
);
4483 bctl
->flags
= btrfs_balance_flags(leaf
, item
);
4484 bctl
->flags
|= BTRFS_BALANCE_RESUME
;
4486 btrfs_balance_data(leaf
, item
, &disk_bargs
);
4487 btrfs_disk_balance_args_to_cpu(&bctl
->data
, &disk_bargs
);
4488 btrfs_balance_meta(leaf
, item
, &disk_bargs
);
4489 btrfs_disk_balance_args_to_cpu(&bctl
->meta
, &disk_bargs
);
4490 btrfs_balance_sys(leaf
, item
, &disk_bargs
);
4491 btrfs_disk_balance_args_to_cpu(&bctl
->sys
, &disk_bargs
);
4494 * This should never happen, as the paused balance state is recovered
4495 * during mount without any chance of other exclusive ops to collide.
4497 * This gives the exclusive op status to balance and keeps in paused
4498 * state until user intervention (cancel or umount). If the ownership
4499 * cannot be assigned, show a message but do not fail. The balance
4500 * is in a paused state and must have fs_info::balance_ctl properly
4503 if (!btrfs_exclop_start(fs_info
, BTRFS_EXCLOP_BALANCE_PAUSED
))
4505 "balance: cannot set exclusive op status, resume manually");
4507 btrfs_release_path(path
);
4509 mutex_lock(&fs_info
->balance_mutex
);
4510 BUG_ON(fs_info
->balance_ctl
);
4511 spin_lock(&fs_info
->balance_lock
);
4512 fs_info
->balance_ctl
= bctl
;
4513 spin_unlock(&fs_info
->balance_lock
);
4514 mutex_unlock(&fs_info
->balance_mutex
);
4516 btrfs_free_path(path
);
4520 int btrfs_pause_balance(struct btrfs_fs_info
*fs_info
)
4524 mutex_lock(&fs_info
->balance_mutex
);
4525 if (!fs_info
->balance_ctl
) {
4526 mutex_unlock(&fs_info
->balance_mutex
);
4530 if (test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
)) {
4531 atomic_inc(&fs_info
->balance_pause_req
);
4532 mutex_unlock(&fs_info
->balance_mutex
);
4534 wait_event(fs_info
->balance_wait_q
,
4535 !test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
));
4537 mutex_lock(&fs_info
->balance_mutex
);
4538 /* we are good with balance_ctl ripped off from under us */
4539 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
));
4540 atomic_dec(&fs_info
->balance_pause_req
);
4545 mutex_unlock(&fs_info
->balance_mutex
);
4549 int btrfs_cancel_balance(struct btrfs_fs_info
*fs_info
)
4551 mutex_lock(&fs_info
->balance_mutex
);
4552 if (!fs_info
->balance_ctl
) {
4553 mutex_unlock(&fs_info
->balance_mutex
);
4558 * A paused balance with the item stored on disk can be resumed at
4559 * mount time if the mount is read-write. Otherwise it's still paused
4560 * and we must not allow cancelling as it deletes the item.
4562 if (sb_rdonly(fs_info
->sb
)) {
4563 mutex_unlock(&fs_info
->balance_mutex
);
4567 atomic_inc(&fs_info
->balance_cancel_req
);
4569 * if we are running just wait and return, balance item is
4570 * deleted in btrfs_balance in this case
4572 if (test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
)) {
4573 mutex_unlock(&fs_info
->balance_mutex
);
4574 wait_event(fs_info
->balance_wait_q
,
4575 !test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
));
4576 mutex_lock(&fs_info
->balance_mutex
);
4578 mutex_unlock(&fs_info
->balance_mutex
);
4580 * Lock released to allow other waiters to continue, we'll
4581 * reexamine the status again.
4583 mutex_lock(&fs_info
->balance_mutex
);
4585 if (fs_info
->balance_ctl
) {
4586 reset_balance_state(fs_info
);
4587 btrfs_exclop_finish(fs_info
);
4588 btrfs_info(fs_info
, "balance: canceled");
4592 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING
, &fs_info
->flags
));
4593 atomic_dec(&fs_info
->balance_cancel_req
);
4594 mutex_unlock(&fs_info
->balance_mutex
);
4598 int btrfs_uuid_scan_kthread(void *data
)
4600 struct btrfs_fs_info
*fs_info
= data
;
4601 struct btrfs_root
*root
= fs_info
->tree_root
;
4602 struct btrfs_key key
;
4603 struct btrfs_path
*path
= NULL
;
4605 struct extent_buffer
*eb
;
4607 struct btrfs_root_item root_item
;
4609 struct btrfs_trans_handle
*trans
= NULL
;
4610 bool closing
= false;
4612 path
= btrfs_alloc_path();
4619 key
.type
= BTRFS_ROOT_ITEM_KEY
;
4623 if (btrfs_fs_closing(fs_info
)) {
4627 ret
= btrfs_search_forward(root
, &key
, path
,
4628 BTRFS_OLDEST_GENERATION
);
4635 if (key
.type
!= BTRFS_ROOT_ITEM_KEY
||
4636 (key
.objectid
< BTRFS_FIRST_FREE_OBJECTID
&&
4637 key
.objectid
!= BTRFS_FS_TREE_OBJECTID
) ||
4638 key
.objectid
> BTRFS_LAST_FREE_OBJECTID
)
4641 eb
= path
->nodes
[0];
4642 slot
= path
->slots
[0];
4643 item_size
= btrfs_item_size(eb
, slot
);
4644 if (item_size
< sizeof(root_item
))
4647 read_extent_buffer(eb
, &root_item
,
4648 btrfs_item_ptr_offset(eb
, slot
),
4649 (int)sizeof(root_item
));
4650 if (btrfs_root_refs(&root_item
) == 0)
4653 if (!btrfs_is_empty_uuid(root_item
.uuid
) ||
4654 !btrfs_is_empty_uuid(root_item
.received_uuid
)) {
4658 btrfs_release_path(path
);
4660 * 1 - subvol uuid item
4661 * 1 - received_subvol uuid item
4663 trans
= btrfs_start_transaction(fs_info
->uuid_root
, 2);
4664 if (IS_ERR(trans
)) {
4665 ret
= PTR_ERR(trans
);
4673 btrfs_release_path(path
);
4674 if (!btrfs_is_empty_uuid(root_item
.uuid
)) {
4675 ret
= btrfs_uuid_tree_add(trans
, root_item
.uuid
,
4676 BTRFS_UUID_KEY_SUBVOL
,
4679 btrfs_warn(fs_info
, "uuid_tree_add failed %d",
4685 if (!btrfs_is_empty_uuid(root_item
.received_uuid
)) {
4686 ret
= btrfs_uuid_tree_add(trans
,
4687 root_item
.received_uuid
,
4688 BTRFS_UUID_KEY_RECEIVED_SUBVOL
,
4691 btrfs_warn(fs_info
, "uuid_tree_add failed %d",
4698 btrfs_release_path(path
);
4700 ret
= btrfs_end_transaction(trans
);
4706 if (key
.offset
< (u64
)-1) {
4708 } else if (key
.type
< BTRFS_ROOT_ITEM_KEY
) {
4710 key
.type
= BTRFS_ROOT_ITEM_KEY
;
4711 } else if (key
.objectid
< (u64
)-1) {
4713 key
.type
= BTRFS_ROOT_ITEM_KEY
;
4722 btrfs_free_path(path
);
4723 if (trans
&& !IS_ERR(trans
))
4724 btrfs_end_transaction(trans
);
4726 btrfs_warn(fs_info
, "btrfs_uuid_scan_kthread failed %d", ret
);
4728 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN
, &fs_info
->flags
);
4729 up(&fs_info
->uuid_tree_rescan_sem
);
4733 int btrfs_create_uuid_tree(struct btrfs_fs_info
*fs_info
)
4735 struct btrfs_trans_handle
*trans
;
4736 struct btrfs_root
*tree_root
= fs_info
->tree_root
;
4737 struct btrfs_root
*uuid_root
;
4738 struct task_struct
*task
;
4745 trans
= btrfs_start_transaction(tree_root
, 2);
4747 return PTR_ERR(trans
);
4749 uuid_root
= btrfs_create_tree(trans
, BTRFS_UUID_TREE_OBJECTID
);
4750 if (IS_ERR(uuid_root
)) {
4751 ret
= PTR_ERR(uuid_root
);
4752 btrfs_abort_transaction(trans
, ret
);
4753 btrfs_end_transaction(trans
);
4757 fs_info
->uuid_root
= uuid_root
;
4759 ret
= btrfs_commit_transaction(trans
);
4763 down(&fs_info
->uuid_tree_rescan_sem
);
4764 task
= kthread_run(btrfs_uuid_scan_kthread
, fs_info
, "btrfs-uuid");
4766 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4767 btrfs_warn(fs_info
, "failed to start uuid_scan task");
4768 up(&fs_info
->uuid_tree_rescan_sem
);
4769 return PTR_ERR(task
);
4776 * shrinking a device means finding all of the device extents past
4777 * the new size, and then following the back refs to the chunks.
4778 * The chunk relocation code actually frees the device extent
4780 int btrfs_shrink_device(struct btrfs_device
*device
, u64 new_size
)
4782 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
4783 struct btrfs_root
*root
= fs_info
->dev_root
;
4784 struct btrfs_trans_handle
*trans
;
4785 struct btrfs_dev_extent
*dev_extent
= NULL
;
4786 struct btrfs_path
*path
;
4792 bool retried
= false;
4793 struct extent_buffer
*l
;
4794 struct btrfs_key key
;
4795 struct btrfs_super_block
*super_copy
= fs_info
->super_copy
;
4796 u64 old_total
= btrfs_super_total_bytes(super_copy
);
4797 u64 old_size
= btrfs_device_get_total_bytes(device
);
4802 new_size
= round_down(new_size
, fs_info
->sectorsize
);
4804 diff
= round_down(old_size
- new_size
, fs_info
->sectorsize
);
4806 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
))
4809 path
= btrfs_alloc_path();
4813 path
->reada
= READA_BACK
;
4815 trans
= btrfs_start_transaction(root
, 0);
4816 if (IS_ERR(trans
)) {
4817 btrfs_free_path(path
);
4818 return PTR_ERR(trans
);
4821 mutex_lock(&fs_info
->chunk_mutex
);
4823 btrfs_device_set_total_bytes(device
, new_size
);
4824 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
4825 device
->fs_devices
->total_rw_bytes
-= diff
;
4828 * The new free_chunk_space is new_size - used, so we have to
4829 * subtract the delta of the old free_chunk_space which included
4830 * old_size - used. If used > new_size then just subtract this
4831 * entire device's free space.
4833 if (device
->bytes_used
< new_size
)
4834 free_diff
= (old_size
- device
->bytes_used
) -
4835 (new_size
- device
->bytes_used
);
4837 free_diff
= old_size
- device
->bytes_used
;
4838 atomic64_sub(free_diff
, &fs_info
->free_chunk_space
);
4842 * Once the device's size has been set to the new size, ensure all
4843 * in-memory chunks are synced to disk so that the loop below sees them
4844 * and relocates them accordingly.
4846 if (contains_pending_extent(device
, &start
, diff
)) {
4847 mutex_unlock(&fs_info
->chunk_mutex
);
4848 ret
= btrfs_commit_transaction(trans
);
4852 mutex_unlock(&fs_info
->chunk_mutex
);
4853 btrfs_end_transaction(trans
);
4857 key
.objectid
= device
->devid
;
4858 key
.offset
= (u64
)-1;
4859 key
.type
= BTRFS_DEV_EXTENT_KEY
;
4862 mutex_lock(&fs_info
->reclaim_bgs_lock
);
4863 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
4865 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4869 ret
= btrfs_previous_item(root
, path
, 0, key
.type
);
4871 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4875 btrfs_release_path(path
);
4880 slot
= path
->slots
[0];
4881 btrfs_item_key_to_cpu(l
, &key
, path
->slots
[0]);
4883 if (key
.objectid
!= device
->devid
) {
4884 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4885 btrfs_release_path(path
);
4889 dev_extent
= btrfs_item_ptr(l
, slot
, struct btrfs_dev_extent
);
4890 length
= btrfs_dev_extent_length(l
, dev_extent
);
4892 if (key
.offset
+ length
<= new_size
) {
4893 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4894 btrfs_release_path(path
);
4898 chunk_offset
= btrfs_dev_extent_chunk_offset(l
, dev_extent
);
4899 btrfs_release_path(path
);
4902 * We may be relocating the only data chunk we have,
4903 * which could potentially end up with losing data's
4904 * raid profile, so lets allocate an empty one in
4907 ret
= btrfs_may_alloc_data_chunk(fs_info
, chunk_offset
);
4909 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4913 ret
= btrfs_relocate_chunk(fs_info
, chunk_offset
);
4914 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
4915 if (ret
== -ENOSPC
) {
4918 if (ret
== -ETXTBSY
) {
4920 "could not shrink block group %llu due to active swapfile",
4925 } while (key
.offset
-- > 0);
4927 if (failed
&& !retried
) {
4931 } else if (failed
&& retried
) {
4936 /* Shrinking succeeded, else we would be at "done". */
4937 trans
= btrfs_start_transaction(root
, 0);
4938 if (IS_ERR(trans
)) {
4939 ret
= PTR_ERR(trans
);
4943 mutex_lock(&fs_info
->chunk_mutex
);
4944 /* Clear all state bits beyond the shrunk device size */
4945 clear_extent_bits(&device
->alloc_state
, new_size
, (u64
)-1,
4948 btrfs_device_set_disk_total_bytes(device
, new_size
);
4949 if (list_empty(&device
->post_commit_list
))
4950 list_add_tail(&device
->post_commit_list
,
4951 &trans
->transaction
->dev_update_list
);
4953 WARN_ON(diff
> old_total
);
4954 btrfs_set_super_total_bytes(super_copy
,
4955 round_down(old_total
- diff
, fs_info
->sectorsize
));
4956 mutex_unlock(&fs_info
->chunk_mutex
);
4958 btrfs_reserve_chunk_metadata(trans
, false);
4959 /* Now btrfs_update_device() will change the on-disk size. */
4960 ret
= btrfs_update_device(trans
, device
);
4961 btrfs_trans_release_chunk_metadata(trans
);
4963 btrfs_abort_transaction(trans
, ret
);
4964 btrfs_end_transaction(trans
);
4966 ret
= btrfs_commit_transaction(trans
);
4969 btrfs_free_path(path
);
4971 mutex_lock(&fs_info
->chunk_mutex
);
4972 btrfs_device_set_total_bytes(device
, old_size
);
4973 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
4974 device
->fs_devices
->total_rw_bytes
+= diff
;
4975 atomic64_add(free_diff
, &fs_info
->free_chunk_space
);
4977 mutex_unlock(&fs_info
->chunk_mutex
);
4982 static int btrfs_add_system_chunk(struct btrfs_fs_info
*fs_info
,
4983 struct btrfs_key
*key
,
4984 struct btrfs_chunk
*chunk
, int item_size
)
4986 struct btrfs_super_block
*super_copy
= fs_info
->super_copy
;
4987 struct btrfs_disk_key disk_key
;
4991 lockdep_assert_held(&fs_info
->chunk_mutex
);
4993 array_size
= btrfs_super_sys_array_size(super_copy
);
4994 if (array_size
+ item_size
+ sizeof(disk_key
)
4995 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE
)
4998 ptr
= super_copy
->sys_chunk_array
+ array_size
;
4999 btrfs_cpu_key_to_disk(&disk_key
, key
);
5000 memcpy(ptr
, &disk_key
, sizeof(disk_key
));
5001 ptr
+= sizeof(disk_key
);
5002 memcpy(ptr
, chunk
, item_size
);
5003 item_size
+= sizeof(disk_key
);
5004 btrfs_set_super_sys_array_size(super_copy
, array_size
+ item_size
);
5010 * sort the devices in descending order by max_avail, total_avail
5012 static int btrfs_cmp_device_info(const void *a
, const void *b
)
5014 const struct btrfs_device_info
*di_a
= a
;
5015 const struct btrfs_device_info
*di_b
= b
;
5017 if (di_a
->max_avail
> di_b
->max_avail
)
5019 if (di_a
->max_avail
< di_b
->max_avail
)
5021 if (di_a
->total_avail
> di_b
->total_avail
)
5023 if (di_a
->total_avail
< di_b
->total_avail
)
5028 static void check_raid56_incompat_flag(struct btrfs_fs_info
*info
, u64 type
)
5030 if (!(type
& BTRFS_BLOCK_GROUP_RAID56_MASK
))
5033 btrfs_set_fs_incompat(info
, RAID56
);
5036 static void check_raid1c34_incompat_flag(struct btrfs_fs_info
*info
, u64 type
)
5038 if (!(type
& (BTRFS_BLOCK_GROUP_RAID1C3
| BTRFS_BLOCK_GROUP_RAID1C4
)))
5041 btrfs_set_fs_incompat(info
, RAID1C34
);
5045 * Structure used internally for btrfs_create_chunk() function.
5046 * Wraps needed parameters.
5048 struct alloc_chunk_ctl
{
5051 /* Total number of stripes to allocate */
5053 /* sub_stripes info for map */
5055 /* Stripes per device */
5057 /* Maximum number of devices to use */
5059 /* Minimum number of devices to use */
5061 /* ndevs has to be a multiple of this */
5063 /* Number of copies */
5065 /* Number of stripes worth of bytes to store parity information */
5067 u64 max_stripe_size
;
5075 static void init_alloc_chunk_ctl_policy_regular(
5076 struct btrfs_fs_devices
*fs_devices
,
5077 struct alloc_chunk_ctl
*ctl
)
5079 struct btrfs_space_info
*space_info
;
5081 space_info
= btrfs_find_space_info(fs_devices
->fs_info
, ctl
->type
);
5084 ctl
->max_chunk_size
= READ_ONCE(space_info
->chunk_size
);
5085 ctl
->max_stripe_size
= ctl
->max_chunk_size
;
5087 if (ctl
->type
& BTRFS_BLOCK_GROUP_SYSTEM
)
5088 ctl
->devs_max
= min_t(int, ctl
->devs_max
, BTRFS_MAX_DEVS_SYS_CHUNK
);
5090 /* We don't want a chunk larger than 10% of writable space */
5091 ctl
->max_chunk_size
= min(mult_perc(fs_devices
->total_rw_bytes
, 10),
5092 ctl
->max_chunk_size
);
5093 ctl
->dev_extent_min
= btrfs_stripe_nr_to_offset(ctl
->dev_stripes
);
5096 static void init_alloc_chunk_ctl_policy_zoned(
5097 struct btrfs_fs_devices
*fs_devices
,
5098 struct alloc_chunk_ctl
*ctl
)
5100 u64 zone_size
= fs_devices
->fs_info
->zone_size
;
5102 int min_num_stripes
= ctl
->devs_min
* ctl
->dev_stripes
;
5103 int min_data_stripes
= (min_num_stripes
- ctl
->nparity
) / ctl
->ncopies
;
5104 u64 min_chunk_size
= min_data_stripes
* zone_size
;
5105 u64 type
= ctl
->type
;
5107 ctl
->max_stripe_size
= zone_size
;
5108 if (type
& BTRFS_BLOCK_GROUP_DATA
) {
5109 ctl
->max_chunk_size
= round_down(BTRFS_MAX_DATA_CHUNK_SIZE
,
5111 } else if (type
& BTRFS_BLOCK_GROUP_METADATA
) {
5112 ctl
->max_chunk_size
= ctl
->max_stripe_size
;
5113 } else if (type
& BTRFS_BLOCK_GROUP_SYSTEM
) {
5114 ctl
->max_chunk_size
= 2 * ctl
->max_stripe_size
;
5115 ctl
->devs_max
= min_t(int, ctl
->devs_max
,
5116 BTRFS_MAX_DEVS_SYS_CHUNK
);
5121 /* We don't want a chunk larger than 10% of writable space */
5122 limit
= max(round_down(mult_perc(fs_devices
->total_rw_bytes
, 10),
5125 ctl
->max_chunk_size
= min(limit
, ctl
->max_chunk_size
);
5126 ctl
->dev_extent_min
= zone_size
* ctl
->dev_stripes
;
5129 static void init_alloc_chunk_ctl(struct btrfs_fs_devices
*fs_devices
,
5130 struct alloc_chunk_ctl
*ctl
)
5132 int index
= btrfs_bg_flags_to_raid_index(ctl
->type
);
5134 ctl
->sub_stripes
= btrfs_raid_array
[index
].sub_stripes
;
5135 ctl
->dev_stripes
= btrfs_raid_array
[index
].dev_stripes
;
5136 ctl
->devs_max
= btrfs_raid_array
[index
].devs_max
;
5138 ctl
->devs_max
= BTRFS_MAX_DEVS(fs_devices
->fs_info
);
5139 ctl
->devs_min
= btrfs_raid_array
[index
].devs_min
;
5140 ctl
->devs_increment
= btrfs_raid_array
[index
].devs_increment
;
5141 ctl
->ncopies
= btrfs_raid_array
[index
].ncopies
;
5142 ctl
->nparity
= btrfs_raid_array
[index
].nparity
;
5145 switch (fs_devices
->chunk_alloc_policy
) {
5146 case BTRFS_CHUNK_ALLOC_REGULAR
:
5147 init_alloc_chunk_ctl_policy_regular(fs_devices
, ctl
);
5149 case BTRFS_CHUNK_ALLOC_ZONED
:
5150 init_alloc_chunk_ctl_policy_zoned(fs_devices
, ctl
);
5157 static int gather_device_info(struct btrfs_fs_devices
*fs_devices
,
5158 struct alloc_chunk_ctl
*ctl
,
5159 struct btrfs_device_info
*devices_info
)
5161 struct btrfs_fs_info
*info
= fs_devices
->fs_info
;
5162 struct btrfs_device
*device
;
5164 u64 dev_extent_want
= ctl
->max_stripe_size
* ctl
->dev_stripes
;
5171 * in the first pass through the devices list, we gather information
5172 * about the available holes on each device.
5174 list_for_each_entry(device
, &fs_devices
->alloc_list
, dev_alloc_list
) {
5175 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
)) {
5177 "BTRFS: read-only device in alloc_list\n");
5181 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA
,
5182 &device
->dev_state
) ||
5183 test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
))
5186 if (device
->total_bytes
> device
->bytes_used
)
5187 total_avail
= device
->total_bytes
- device
->bytes_used
;
5191 /* If there is no space on this device, skip it. */
5192 if (total_avail
< ctl
->dev_extent_min
)
5195 ret
= find_free_dev_extent(device
, dev_extent_want
, &dev_offset
,
5197 if (ret
&& ret
!= -ENOSPC
)
5201 max_avail
= dev_extent_want
;
5203 if (max_avail
< ctl
->dev_extent_min
) {
5204 if (btrfs_test_opt(info
, ENOSPC_DEBUG
))
5206 "%s: devid %llu has no free space, have=%llu want=%llu",
5207 __func__
, device
->devid
, max_avail
,
5208 ctl
->dev_extent_min
);
5212 if (ndevs
== fs_devices
->rw_devices
) {
5213 WARN(1, "%s: found more than %llu devices\n",
5214 __func__
, fs_devices
->rw_devices
);
5217 devices_info
[ndevs
].dev_offset
= dev_offset
;
5218 devices_info
[ndevs
].max_avail
= max_avail
;
5219 devices_info
[ndevs
].total_avail
= total_avail
;
5220 devices_info
[ndevs
].dev
= device
;
5226 * now sort the devices by hole size / available space
5228 sort(devices_info
, ndevs
, sizeof(struct btrfs_device_info
),
5229 btrfs_cmp_device_info
, NULL
);
5234 static int decide_stripe_size_regular(struct alloc_chunk_ctl
*ctl
,
5235 struct btrfs_device_info
*devices_info
)
5237 /* Number of stripes that count for block group size */
5241 * The primary goal is to maximize the number of stripes, so use as
5242 * many devices as possible, even if the stripes are not maximum sized.
5244 * The DUP profile stores more than one stripe per device, the
5245 * max_avail is the total size so we have to adjust.
5247 ctl
->stripe_size
= div_u64(devices_info
[ctl
->ndevs
- 1].max_avail
,
5249 ctl
->num_stripes
= ctl
->ndevs
* ctl
->dev_stripes
;
5251 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5252 data_stripes
= (ctl
->num_stripes
- ctl
->nparity
) / ctl
->ncopies
;
5255 * Use the number of data stripes to figure out how big this chunk is
5256 * really going to be in terms of logical address space, and compare
5257 * that answer with the max chunk size. If it's higher, we try to
5258 * reduce stripe_size.
5260 if (ctl
->stripe_size
* data_stripes
> ctl
->max_chunk_size
) {
5262 * Reduce stripe_size, round it up to a 16MB boundary again and
5263 * then use it, unless it ends up being even bigger than the
5264 * previous value we had already.
5266 ctl
->stripe_size
= min(round_up(div_u64(ctl
->max_chunk_size
,
5267 data_stripes
), SZ_16M
),
5271 /* Stripe size should not go beyond 1G. */
5272 ctl
->stripe_size
= min_t(u64
, ctl
->stripe_size
, SZ_1G
);
5274 /* Align to BTRFS_STRIPE_LEN */
5275 ctl
->stripe_size
= round_down(ctl
->stripe_size
, BTRFS_STRIPE_LEN
);
5276 ctl
->chunk_size
= ctl
->stripe_size
* data_stripes
;
5281 static int decide_stripe_size_zoned(struct alloc_chunk_ctl
*ctl
,
5282 struct btrfs_device_info
*devices_info
)
5284 u64 zone_size
= devices_info
[0].dev
->zone_info
->zone_size
;
5285 /* Number of stripes that count for block group size */
5289 * It should hold because:
5290 * dev_extent_min == dev_extent_want == zone_size * dev_stripes
5292 ASSERT(devices_info
[ctl
->ndevs
- 1].max_avail
== ctl
->dev_extent_min
);
5294 ctl
->stripe_size
= zone_size
;
5295 ctl
->num_stripes
= ctl
->ndevs
* ctl
->dev_stripes
;
5296 data_stripes
= (ctl
->num_stripes
- ctl
->nparity
) / ctl
->ncopies
;
5298 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */
5299 if (ctl
->stripe_size
* data_stripes
> ctl
->max_chunk_size
) {
5300 ctl
->ndevs
= div_u64(div_u64(ctl
->max_chunk_size
* ctl
->ncopies
,
5301 ctl
->stripe_size
) + ctl
->nparity
,
5303 ctl
->num_stripes
= ctl
->ndevs
* ctl
->dev_stripes
;
5304 data_stripes
= (ctl
->num_stripes
- ctl
->nparity
) / ctl
->ncopies
;
5305 ASSERT(ctl
->stripe_size
* data_stripes
<= ctl
->max_chunk_size
);
5308 ctl
->chunk_size
= ctl
->stripe_size
* data_stripes
;
5313 static int decide_stripe_size(struct btrfs_fs_devices
*fs_devices
,
5314 struct alloc_chunk_ctl
*ctl
,
5315 struct btrfs_device_info
*devices_info
)
5317 struct btrfs_fs_info
*info
= fs_devices
->fs_info
;
5320 * Round down to number of usable stripes, devs_increment can be any
5321 * number so we can't use round_down() that requires power of 2, while
5322 * rounddown is safe.
5324 ctl
->ndevs
= rounddown(ctl
->ndevs
, ctl
->devs_increment
);
5326 if (ctl
->ndevs
< ctl
->devs_min
) {
5327 if (btrfs_test_opt(info
, ENOSPC_DEBUG
)) {
5329 "%s: not enough devices with free space: have=%d minimum required=%d",
5330 __func__
, ctl
->ndevs
, ctl
->devs_min
);
5335 ctl
->ndevs
= min(ctl
->ndevs
, ctl
->devs_max
);
5337 switch (fs_devices
->chunk_alloc_policy
) {
5338 case BTRFS_CHUNK_ALLOC_REGULAR
:
5339 return decide_stripe_size_regular(ctl
, devices_info
);
5340 case BTRFS_CHUNK_ALLOC_ZONED
:
5341 return decide_stripe_size_zoned(ctl
, devices_info
);
5347 static struct btrfs_block_group
*create_chunk(struct btrfs_trans_handle
*trans
,
5348 struct alloc_chunk_ctl
*ctl
,
5349 struct btrfs_device_info
*devices_info
)
5351 struct btrfs_fs_info
*info
= trans
->fs_info
;
5352 struct map_lookup
*map
= NULL
;
5353 struct extent_map_tree
*em_tree
;
5354 struct btrfs_block_group
*block_group
;
5355 struct extent_map
*em
;
5356 u64 start
= ctl
->start
;
5357 u64 type
= ctl
->type
;
5362 map
= kmalloc(map_lookup_size(ctl
->num_stripes
), GFP_NOFS
);
5364 return ERR_PTR(-ENOMEM
);
5365 map
->num_stripes
= ctl
->num_stripes
;
5367 for (i
= 0; i
< ctl
->ndevs
; ++i
) {
5368 for (j
= 0; j
< ctl
->dev_stripes
; ++j
) {
5369 int s
= i
* ctl
->dev_stripes
+ j
;
5370 map
->stripes
[s
].dev
= devices_info
[i
].dev
;
5371 map
->stripes
[s
].physical
= devices_info
[i
].dev_offset
+
5372 j
* ctl
->stripe_size
;
5375 map
->io_align
= BTRFS_STRIPE_LEN
;
5376 map
->io_width
= BTRFS_STRIPE_LEN
;
5378 map
->sub_stripes
= ctl
->sub_stripes
;
5380 trace_btrfs_chunk_alloc(info
, map
, start
, ctl
->chunk_size
);
5382 em
= alloc_extent_map();
5385 return ERR_PTR(-ENOMEM
);
5387 set_bit(EXTENT_FLAG_FS_MAPPING
, &em
->flags
);
5388 em
->map_lookup
= map
;
5390 em
->len
= ctl
->chunk_size
;
5391 em
->block_start
= 0;
5392 em
->block_len
= em
->len
;
5393 em
->orig_block_len
= ctl
->stripe_size
;
5395 em_tree
= &info
->mapping_tree
;
5396 write_lock(&em_tree
->lock
);
5397 ret
= add_extent_mapping(em_tree
, em
, 0);
5399 write_unlock(&em_tree
->lock
);
5400 free_extent_map(em
);
5401 return ERR_PTR(ret
);
5403 write_unlock(&em_tree
->lock
);
5405 block_group
= btrfs_make_block_group(trans
, type
, start
, ctl
->chunk_size
);
5406 if (IS_ERR(block_group
))
5407 goto error_del_extent
;
5409 for (i
= 0; i
< map
->num_stripes
; i
++) {
5410 struct btrfs_device
*dev
= map
->stripes
[i
].dev
;
5412 btrfs_device_set_bytes_used(dev
,
5413 dev
->bytes_used
+ ctl
->stripe_size
);
5414 if (list_empty(&dev
->post_commit_list
))
5415 list_add_tail(&dev
->post_commit_list
,
5416 &trans
->transaction
->dev_update_list
);
5419 atomic64_sub(ctl
->stripe_size
* map
->num_stripes
,
5420 &info
->free_chunk_space
);
5422 free_extent_map(em
);
5423 check_raid56_incompat_flag(info
, type
);
5424 check_raid1c34_incompat_flag(info
, type
);
5429 write_lock(&em_tree
->lock
);
5430 remove_extent_mapping(em_tree
, em
);
5431 write_unlock(&em_tree
->lock
);
5433 /* One for our allocation */
5434 free_extent_map(em
);
5435 /* One for the tree reference */
5436 free_extent_map(em
);
5441 struct btrfs_block_group
*btrfs_create_chunk(struct btrfs_trans_handle
*trans
,
5444 struct btrfs_fs_info
*info
= trans
->fs_info
;
5445 struct btrfs_fs_devices
*fs_devices
= info
->fs_devices
;
5446 struct btrfs_device_info
*devices_info
= NULL
;
5447 struct alloc_chunk_ctl ctl
;
5448 struct btrfs_block_group
*block_group
;
5451 lockdep_assert_held(&info
->chunk_mutex
);
5453 if (!alloc_profile_is_valid(type
, 0)) {
5455 return ERR_PTR(-EINVAL
);
5458 if (list_empty(&fs_devices
->alloc_list
)) {
5459 if (btrfs_test_opt(info
, ENOSPC_DEBUG
))
5460 btrfs_debug(info
, "%s: no writable device", __func__
);
5461 return ERR_PTR(-ENOSPC
);
5464 if (!(type
& BTRFS_BLOCK_GROUP_TYPE_MASK
)) {
5465 btrfs_err(info
, "invalid chunk type 0x%llx requested", type
);
5467 return ERR_PTR(-EINVAL
);
5470 ctl
.start
= find_next_chunk(info
);
5472 init_alloc_chunk_ctl(fs_devices
, &ctl
);
5474 devices_info
= kcalloc(fs_devices
->rw_devices
, sizeof(*devices_info
),
5477 return ERR_PTR(-ENOMEM
);
5479 ret
= gather_device_info(fs_devices
, &ctl
, devices_info
);
5481 block_group
= ERR_PTR(ret
);
5485 ret
= decide_stripe_size(fs_devices
, &ctl
, devices_info
);
5487 block_group
= ERR_PTR(ret
);
5491 block_group
= create_chunk(trans
, &ctl
, devices_info
);
5494 kfree(devices_info
);
5499 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5500 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5503 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5506 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle
*trans
,
5507 struct btrfs_block_group
*bg
)
5509 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
5510 struct btrfs_root
*chunk_root
= fs_info
->chunk_root
;
5511 struct btrfs_key key
;
5512 struct btrfs_chunk
*chunk
;
5513 struct btrfs_stripe
*stripe
;
5514 struct extent_map
*em
;
5515 struct map_lookup
*map
;
5521 * We take the chunk_mutex for 2 reasons:
5523 * 1) Updates and insertions in the chunk btree must be done while holding
5524 * the chunk_mutex, as well as updating the system chunk array in the
5525 * superblock. See the comment on top of btrfs_chunk_alloc() for the
5528 * 2) To prevent races with the final phase of a device replace operation
5529 * that replaces the device object associated with the map's stripes,
5530 * because the device object's id can change at any time during that
5531 * final phase of the device replace operation
5532 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5533 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5534 * which would cause a failure when updating the device item, which does
5535 * not exists, or persisting a stripe of the chunk item with such ID.
5536 * Here we can't use the device_list_mutex because our caller already
5537 * has locked the chunk_mutex, and the final phase of device replace
5538 * acquires both mutexes - first the device_list_mutex and then the
5539 * chunk_mutex. Using any of those two mutexes protects us from a
5540 * concurrent device replace.
5542 lockdep_assert_held(&fs_info
->chunk_mutex
);
5544 em
= btrfs_get_chunk_map(fs_info
, bg
->start
, bg
->length
);
5547 btrfs_abort_transaction(trans
, ret
);
5551 map
= em
->map_lookup
;
5552 item_size
= btrfs_chunk_item_size(map
->num_stripes
);
5554 chunk
= kzalloc(item_size
, GFP_NOFS
);
5557 btrfs_abort_transaction(trans
, ret
);
5561 for (i
= 0; i
< map
->num_stripes
; i
++) {
5562 struct btrfs_device
*device
= map
->stripes
[i
].dev
;
5564 ret
= btrfs_update_device(trans
, device
);
5569 stripe
= &chunk
->stripe
;
5570 for (i
= 0; i
< map
->num_stripes
; i
++) {
5571 struct btrfs_device
*device
= map
->stripes
[i
].dev
;
5572 const u64 dev_offset
= map
->stripes
[i
].physical
;
5574 btrfs_set_stack_stripe_devid(stripe
, device
->devid
);
5575 btrfs_set_stack_stripe_offset(stripe
, dev_offset
);
5576 memcpy(stripe
->dev_uuid
, device
->uuid
, BTRFS_UUID_SIZE
);
5580 btrfs_set_stack_chunk_length(chunk
, bg
->length
);
5581 btrfs_set_stack_chunk_owner(chunk
, BTRFS_EXTENT_TREE_OBJECTID
);
5582 btrfs_set_stack_chunk_stripe_len(chunk
, BTRFS_STRIPE_LEN
);
5583 btrfs_set_stack_chunk_type(chunk
, map
->type
);
5584 btrfs_set_stack_chunk_num_stripes(chunk
, map
->num_stripes
);
5585 btrfs_set_stack_chunk_io_align(chunk
, BTRFS_STRIPE_LEN
);
5586 btrfs_set_stack_chunk_io_width(chunk
, BTRFS_STRIPE_LEN
);
5587 btrfs_set_stack_chunk_sector_size(chunk
, fs_info
->sectorsize
);
5588 btrfs_set_stack_chunk_sub_stripes(chunk
, map
->sub_stripes
);
5590 key
.objectid
= BTRFS_FIRST_CHUNK_TREE_OBJECTID
;
5591 key
.type
= BTRFS_CHUNK_ITEM_KEY
;
5592 key
.offset
= bg
->start
;
5594 ret
= btrfs_insert_item(trans
, chunk_root
, &key
, chunk
, item_size
);
5598 set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED
, &bg
->runtime_flags
);
5600 if (map
->type
& BTRFS_BLOCK_GROUP_SYSTEM
) {
5601 ret
= btrfs_add_system_chunk(fs_info
, &key
, chunk
, item_size
);
5608 free_extent_map(em
);
5612 static noinline
int init_first_rw_device(struct btrfs_trans_handle
*trans
)
5614 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
5616 struct btrfs_block_group
*meta_bg
;
5617 struct btrfs_block_group
*sys_bg
;
5620 * When adding a new device for sprouting, the seed device is read-only
5621 * so we must first allocate a metadata and a system chunk. But before
5622 * adding the block group items to the extent, device and chunk btrees,
5625 * 1) Create both chunks without doing any changes to the btrees, as
5626 * otherwise we would get -ENOSPC since the block groups from the
5627 * seed device are read-only;
5629 * 2) Add the device item for the new sprout device - finishing the setup
5630 * of a new block group requires updating the device item in the chunk
5631 * btree, so it must exist when we attempt to do it. The previous step
5632 * ensures this does not fail with -ENOSPC.
5634 * After that we can add the block group items to their btrees:
5635 * update existing device item in the chunk btree, add a new block group
5636 * item to the extent btree, add a new chunk item to the chunk btree and
5637 * finally add the new device extent items to the devices btree.
5640 alloc_profile
= btrfs_metadata_alloc_profile(fs_info
);
5641 meta_bg
= btrfs_create_chunk(trans
, alloc_profile
);
5642 if (IS_ERR(meta_bg
))
5643 return PTR_ERR(meta_bg
);
5645 alloc_profile
= btrfs_system_alloc_profile(fs_info
);
5646 sys_bg
= btrfs_create_chunk(trans
, alloc_profile
);
5648 return PTR_ERR(sys_bg
);
5653 static inline int btrfs_chunk_max_errors(struct map_lookup
*map
)
5655 const int index
= btrfs_bg_flags_to_raid_index(map
->type
);
5657 return btrfs_raid_array
[index
].tolerated_failures
;
5660 bool btrfs_chunk_writeable(struct btrfs_fs_info
*fs_info
, u64 chunk_offset
)
5662 struct extent_map
*em
;
5663 struct map_lookup
*map
;
5668 em
= btrfs_get_chunk_map(fs_info
, chunk_offset
, 1);
5672 map
= em
->map_lookup
;
5673 for (i
= 0; i
< map
->num_stripes
; i
++) {
5674 if (test_bit(BTRFS_DEV_STATE_MISSING
,
5675 &map
->stripes
[i
].dev
->dev_state
)) {
5679 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE
,
5680 &map
->stripes
[i
].dev
->dev_state
)) {
5687 * If the number of missing devices is larger than max errors, we can
5688 * not write the data into that chunk successfully.
5690 if (miss_ndevs
> btrfs_chunk_max_errors(map
))
5693 free_extent_map(em
);
5697 void btrfs_mapping_tree_free(struct extent_map_tree
*tree
)
5699 struct extent_map
*em
;
5702 write_lock(&tree
->lock
);
5703 em
= lookup_extent_mapping(tree
, 0, (u64
)-1);
5705 remove_extent_mapping(tree
, em
);
5706 write_unlock(&tree
->lock
);
5710 free_extent_map(em
);
5711 /* once for the tree */
5712 free_extent_map(em
);
5716 int btrfs_num_copies(struct btrfs_fs_info
*fs_info
, u64 logical
, u64 len
)
5718 struct extent_map
*em
;
5719 struct map_lookup
*map
;
5720 enum btrfs_raid_types index
;
5723 em
= btrfs_get_chunk_map(fs_info
, logical
, len
);
5726 * We could return errors for these cases, but that could get
5727 * ugly and we'd probably do the same thing which is just not do
5728 * anything else and exit, so return 1 so the callers don't try
5729 * to use other copies.
5733 map
= em
->map_lookup
;
5734 index
= btrfs_bg_flags_to_raid_index(map
->type
);
5736 /* Non-RAID56, use their ncopies from btrfs_raid_array. */
5737 if (!(map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
))
5738 ret
= btrfs_raid_array
[index
].ncopies
;
5739 else if (map
->type
& BTRFS_BLOCK_GROUP_RAID5
)
5741 else if (map
->type
& BTRFS_BLOCK_GROUP_RAID6
)
5743 * There could be two corrupted data stripes, we need
5744 * to loop retry in order to rebuild the correct data.
5746 * Fail a stripe at a time on every retry except the
5747 * stripe under reconstruction.
5749 ret
= map
->num_stripes
;
5750 free_extent_map(em
);
5754 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info
*fs_info
,
5757 struct extent_map
*em
;
5758 struct map_lookup
*map
;
5759 unsigned long len
= fs_info
->sectorsize
;
5761 if (!btrfs_fs_incompat(fs_info
, RAID56
))
5764 em
= btrfs_get_chunk_map(fs_info
, logical
, len
);
5766 if (!WARN_ON(IS_ERR(em
))) {
5767 map
= em
->map_lookup
;
5768 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
)
5769 len
= btrfs_stripe_nr_to_offset(nr_data_stripes(map
));
5770 free_extent_map(em
);
5775 int btrfs_is_parity_mirror(struct btrfs_fs_info
*fs_info
, u64 logical
, u64 len
)
5777 struct extent_map
*em
;
5778 struct map_lookup
*map
;
5781 if (!btrfs_fs_incompat(fs_info
, RAID56
))
5784 em
= btrfs_get_chunk_map(fs_info
, logical
, len
);
5786 if(!WARN_ON(IS_ERR(em
))) {
5787 map
= em
->map_lookup
;
5788 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
)
5790 free_extent_map(em
);
5795 static int find_live_mirror(struct btrfs_fs_info
*fs_info
,
5796 struct map_lookup
*map
, int first
,
5797 int dev_replace_is_ongoing
)
5801 int preferred_mirror
;
5803 struct btrfs_device
*srcdev
;
5806 (BTRFS_BLOCK_GROUP_RAID1_MASK
| BTRFS_BLOCK_GROUP_RAID10
)));
5808 if (map
->type
& BTRFS_BLOCK_GROUP_RAID10
)
5809 num_stripes
= map
->sub_stripes
;
5811 num_stripes
= map
->num_stripes
;
5813 switch (fs_info
->fs_devices
->read_policy
) {
5815 /* Shouldn't happen, just warn and use pid instead of failing */
5816 btrfs_warn_rl(fs_info
,
5817 "unknown read_policy type %u, reset to pid",
5818 fs_info
->fs_devices
->read_policy
);
5819 fs_info
->fs_devices
->read_policy
= BTRFS_READ_POLICY_PID
;
5821 case BTRFS_READ_POLICY_PID
:
5822 preferred_mirror
= first
+ (current
->pid
% num_stripes
);
5826 if (dev_replace_is_ongoing
&&
5827 fs_info
->dev_replace
.cont_reading_from_srcdev_mode
==
5828 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID
)
5829 srcdev
= fs_info
->dev_replace
.srcdev
;
5834 * try to avoid the drive that is the source drive for a
5835 * dev-replace procedure, only choose it if no other non-missing
5836 * mirror is available
5838 for (tolerance
= 0; tolerance
< 2; tolerance
++) {
5839 if (map
->stripes
[preferred_mirror
].dev
->bdev
&&
5840 (tolerance
|| map
->stripes
[preferred_mirror
].dev
!= srcdev
))
5841 return preferred_mirror
;
5842 for (i
= first
; i
< first
+ num_stripes
; i
++) {
5843 if (map
->stripes
[i
].dev
->bdev
&&
5844 (tolerance
|| map
->stripes
[i
].dev
!= srcdev
))
5849 /* we couldn't find one that doesn't fail. Just return something
5850 * and the io error handling code will clean up eventually
5852 return preferred_mirror
;
5855 static struct btrfs_io_context
*alloc_btrfs_io_context(struct btrfs_fs_info
*fs_info
,
5859 struct btrfs_io_context
*bioc
;
5862 /* The size of btrfs_io_context */
5863 sizeof(struct btrfs_io_context
) +
5864 /* Plus the variable array for the stripes */
5865 sizeof(struct btrfs_io_stripe
) * (total_stripes
),
5871 refcount_set(&bioc
->refs
, 1);
5873 bioc
->fs_info
= fs_info
;
5874 bioc
->replace_stripe_src
= -1;
5875 bioc
->full_stripe_logical
= (u64
)-1;
5876 bioc
->logical
= logical
;
5881 void btrfs_get_bioc(struct btrfs_io_context
*bioc
)
5883 WARN_ON(!refcount_read(&bioc
->refs
));
5884 refcount_inc(&bioc
->refs
);
5887 void btrfs_put_bioc(struct btrfs_io_context
*bioc
)
5891 if (refcount_dec_and_test(&bioc
->refs
))
5896 * Please note that, discard won't be sent to target device of device
5899 struct btrfs_discard_stripe
*btrfs_map_discard(struct btrfs_fs_info
*fs_info
,
5900 u64 logical
, u64
*length_ret
,
5903 struct extent_map
*em
;
5904 struct map_lookup
*map
;
5905 struct btrfs_discard_stripe
*stripes
;
5906 u64 length
= *length_ret
;
5911 u64 stripe_end_offset
;
5915 u32 sub_stripes
= 0;
5916 u32 stripes_per_dev
= 0;
5917 u32 remaining_stripes
= 0;
5918 u32 last_stripe
= 0;
5922 em
= btrfs_get_chunk_map(fs_info
, logical
, length
);
5924 return ERR_CAST(em
);
5926 map
= em
->map_lookup
;
5928 /* we don't discard raid56 yet */
5929 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
) {
5934 offset
= logical
- em
->start
;
5935 length
= min_t(u64
, em
->start
+ em
->len
- logical
, length
);
5936 *length_ret
= length
;
5939 * stripe_nr counts the total number of stripes we have to stride
5940 * to get to this block
5942 stripe_nr
= offset
>> BTRFS_STRIPE_LEN_SHIFT
;
5944 /* stripe_offset is the offset of this block in its stripe */
5945 stripe_offset
= offset
- btrfs_stripe_nr_to_offset(stripe_nr
);
5947 stripe_nr_end
= round_up(offset
+ length
, BTRFS_STRIPE_LEN
) >>
5948 BTRFS_STRIPE_LEN_SHIFT
;
5949 stripe_cnt
= stripe_nr_end
- stripe_nr
;
5950 stripe_end_offset
= btrfs_stripe_nr_to_offset(stripe_nr_end
) -
5953 * after this, stripe_nr is the number of stripes on this
5954 * device we have to walk to find the data, and stripe_index is
5955 * the number of our device in the stripe array
5959 if (map
->type
& (BTRFS_BLOCK_GROUP_RAID0
|
5960 BTRFS_BLOCK_GROUP_RAID10
)) {
5961 if (map
->type
& BTRFS_BLOCK_GROUP_RAID0
)
5964 sub_stripes
= map
->sub_stripes
;
5966 factor
= map
->num_stripes
/ sub_stripes
;
5967 *num_stripes
= min_t(u64
, map
->num_stripes
,
5968 sub_stripes
* stripe_cnt
);
5969 stripe_index
= stripe_nr
% factor
;
5970 stripe_nr
/= factor
;
5971 stripe_index
*= sub_stripes
;
5973 remaining_stripes
= stripe_cnt
% factor
;
5974 stripes_per_dev
= stripe_cnt
/ factor
;
5975 last_stripe
= ((stripe_nr_end
- 1) % factor
) * sub_stripes
;
5976 } else if (map
->type
& (BTRFS_BLOCK_GROUP_RAID1_MASK
|
5977 BTRFS_BLOCK_GROUP_DUP
)) {
5978 *num_stripes
= map
->num_stripes
;
5980 stripe_index
= stripe_nr
% map
->num_stripes
;
5981 stripe_nr
/= map
->num_stripes
;
5984 stripes
= kcalloc(*num_stripes
, sizeof(*stripes
), GFP_NOFS
);
5990 for (i
= 0; i
< *num_stripes
; i
++) {
5991 stripes
[i
].physical
=
5992 map
->stripes
[stripe_index
].physical
+
5993 stripe_offset
+ btrfs_stripe_nr_to_offset(stripe_nr
);
5994 stripes
[i
].dev
= map
->stripes
[stripe_index
].dev
;
5996 if (map
->type
& (BTRFS_BLOCK_GROUP_RAID0
|
5997 BTRFS_BLOCK_GROUP_RAID10
)) {
5998 stripes
[i
].length
= btrfs_stripe_nr_to_offset(stripes_per_dev
);
6000 if (i
/ sub_stripes
< remaining_stripes
)
6001 stripes
[i
].length
+= BTRFS_STRIPE_LEN
;
6004 * Special for the first stripe and
6007 * |-------|...|-------|
6011 if (i
< sub_stripes
)
6012 stripes
[i
].length
-= stripe_offset
;
6014 if (stripe_index
>= last_stripe
&&
6015 stripe_index
<= (last_stripe
+
6017 stripes
[i
].length
-= stripe_end_offset
;
6019 if (i
== sub_stripes
- 1)
6022 stripes
[i
].length
= length
;
6026 if (stripe_index
== map
->num_stripes
) {
6032 free_extent_map(em
);
6035 free_extent_map(em
);
6036 return ERR_PTR(ret
);
6039 static bool is_block_group_to_copy(struct btrfs_fs_info
*fs_info
, u64 logical
)
6041 struct btrfs_block_group
*cache
;
6044 /* Non zoned filesystem does not use "to_copy" flag */
6045 if (!btrfs_is_zoned(fs_info
))
6048 cache
= btrfs_lookup_block_group(fs_info
, logical
);
6050 ret
= test_bit(BLOCK_GROUP_FLAG_TO_COPY
, &cache
->runtime_flags
);
6052 btrfs_put_block_group(cache
);
6056 static void handle_ops_on_dev_replace(enum btrfs_map_op op
,
6057 struct btrfs_io_context
*bioc
,
6058 struct btrfs_dev_replace
*dev_replace
,
6060 int *num_stripes_ret
, int *max_errors_ret
)
6062 u64 srcdev_devid
= dev_replace
->srcdev
->devid
;
6064 * At this stage, num_stripes is still the real number of stripes,
6065 * excluding the duplicated stripes.
6067 int num_stripes
= *num_stripes_ret
;
6068 int nr_extra_stripes
= 0;
6069 int max_errors
= *max_errors_ret
;
6073 * A block group which has "to_copy" set will eventually be copied by
6074 * the dev-replace process. We can avoid cloning IO here.
6076 if (is_block_group_to_copy(dev_replace
->srcdev
->fs_info
, logical
))
6080 * Duplicate the write operations while the dev-replace procedure is
6081 * running. Since the copying of the old disk to the new disk takes
6082 * place at run time while the filesystem is mounted writable, the
6083 * regular write operations to the old disk have to be duplicated to go
6084 * to the new disk as well.
6086 * Note that device->missing is handled by the caller, and that the
6087 * write to the old disk is already set up in the stripes array.
6089 for (i
= 0; i
< num_stripes
; i
++) {
6090 struct btrfs_io_stripe
*old
= &bioc
->stripes
[i
];
6091 struct btrfs_io_stripe
*new = &bioc
->stripes
[num_stripes
+ nr_extra_stripes
];
6093 if (old
->dev
->devid
!= srcdev_devid
)
6096 new->physical
= old
->physical
;
6097 new->dev
= dev_replace
->tgtdev
;
6098 if (bioc
->map_type
& BTRFS_BLOCK_GROUP_RAID56_MASK
)
6099 bioc
->replace_stripe_src
= i
;
6103 /* We can only have at most 2 extra nr_stripes (for DUP). */
6104 ASSERT(nr_extra_stripes
<= 2);
6106 * For GET_READ_MIRRORS, we can only return at most 1 extra stripe for
6108 * If we have 2 extra stripes, only choose the one with smaller physical.
6110 if (op
== BTRFS_MAP_GET_READ_MIRRORS
&& nr_extra_stripes
== 2) {
6111 struct btrfs_io_stripe
*first
= &bioc
->stripes
[num_stripes
];
6112 struct btrfs_io_stripe
*second
= &bioc
->stripes
[num_stripes
+ 1];
6114 /* Only DUP can have two extra stripes. */
6115 ASSERT(bioc
->map_type
& BTRFS_BLOCK_GROUP_DUP
);
6118 * Swap the last stripe stripes and reduce @nr_extra_stripes.
6119 * The extra stripe would still be there, but won't be accessed.
6121 if (first
->physical
> second
->physical
) {
6122 swap(second
->physical
, first
->physical
);
6123 swap(second
->dev
, first
->dev
);
6128 *num_stripes_ret
= num_stripes
+ nr_extra_stripes
;
6129 *max_errors_ret
= max_errors
+ nr_extra_stripes
;
6130 bioc
->replace_nr_stripes
= nr_extra_stripes
;
6133 static u64
btrfs_max_io_len(struct map_lookup
*map
, enum btrfs_map_op op
,
6134 u64 offset
, u32
*stripe_nr
, u64
*stripe_offset
,
6135 u64
*full_stripe_start
)
6138 * Stripe_nr is the stripe where this block falls. stripe_offset is
6139 * the offset of this block in its stripe.
6141 *stripe_offset
= offset
& BTRFS_STRIPE_LEN_MASK
;
6142 *stripe_nr
= offset
>> BTRFS_STRIPE_LEN_SHIFT
;
6143 ASSERT(*stripe_offset
< U32_MAX
);
6145 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
) {
6146 unsigned long full_stripe_len
=
6147 btrfs_stripe_nr_to_offset(nr_data_stripes(map
));
6150 * For full stripe start, we use previously calculated
6151 * @stripe_nr. Align it to nr_data_stripes, then multiply with
6154 * By this we can avoid u64 division completely. And we have
6155 * to go rounddown(), not round_down(), as nr_data_stripes is
6156 * not ensured to be power of 2.
6158 *full_stripe_start
=
6159 btrfs_stripe_nr_to_offset(
6160 rounddown(*stripe_nr
, nr_data_stripes(map
)));
6162 ASSERT(*full_stripe_start
+ full_stripe_len
> offset
);
6163 ASSERT(*full_stripe_start
<= offset
);
6165 * For writes to RAID56, allow to write a full stripe set, but
6166 * no straddling of stripe sets.
6168 if (op
== BTRFS_MAP_WRITE
)
6169 return full_stripe_len
- (offset
- *full_stripe_start
);
6173 * For other RAID types and for RAID56 reads, allow a single stripe (on
6176 if (map
->type
& BTRFS_BLOCK_GROUP_STRIPE_MASK
)
6177 return BTRFS_STRIPE_LEN
- *stripe_offset
;
6181 static int set_io_stripe(struct btrfs_fs_info
*fs_info
, enum btrfs_map_op op
,
6182 u64 logical
, u64
*length
, struct btrfs_io_stripe
*dst
,
6183 struct map_lookup
*map
, u32 stripe_index
,
6184 u64 stripe_offset
, u64 stripe_nr
)
6186 dst
->dev
= map
->stripes
[stripe_index
].dev
;
6188 if (op
== BTRFS_MAP_READ
&& btrfs_need_stripe_tree_update(fs_info
, map
->type
))
6189 return btrfs_get_raid_extent_offset(fs_info
, logical
, length
,
6190 map
->type
, stripe_index
, dst
);
6192 dst
->physical
= map
->stripes
[stripe_index
].physical
+
6193 stripe_offset
+ btrfs_stripe_nr_to_offset(stripe_nr
);
6198 * Map one logical range to one or more physical ranges.
6200 * @length: (Mandatory) mapped length of this run.
6201 * One logical range can be split into different segments
6202 * due to factors like zones and RAID0/5/6/10 stripe
6205 * @bioc_ret: (Mandatory) returned btrfs_io_context structure.
6206 * which has one or more physical ranges (btrfs_io_stripe)
6208 * Caller should call btrfs_put_bioc() to free it after use.
6210 * @smap: (Optional) single physical range optimization.
6211 * If the map request can be fulfilled by one single
6212 * physical range, and this is parameter is not NULL,
6213 * then @bioc_ret would be NULL, and @smap would be
6216 * @mirror_num_ret: (Mandatory) returned mirror number if the original
6219 * Mirror number 0 means to choose any live mirrors.
6221 * For non-RAID56 profiles, non-zero mirror_num means
6222 * the Nth mirror. (e.g. mirror_num 1 means the first
6225 * For RAID56 profile, mirror 1 means rebuild from P and
6226 * the remaining data stripes.
6228 * For RAID6 profile, mirror > 2 means mark another
6229 * data/P stripe error and rebuild from the remaining
6232 int btrfs_map_block(struct btrfs_fs_info
*fs_info
, enum btrfs_map_op op
,
6233 u64 logical
, u64
*length
,
6234 struct btrfs_io_context
**bioc_ret
,
6235 struct btrfs_io_stripe
*smap
, int *mirror_num_ret
)
6237 struct extent_map
*em
;
6238 struct map_lookup
*map
;
6246 int mirror_num
= (mirror_num_ret
? *mirror_num_ret
: 0);
6250 struct btrfs_io_context
*bioc
= NULL
;
6251 struct btrfs_dev_replace
*dev_replace
= &fs_info
->dev_replace
;
6252 int dev_replace_is_ongoing
= 0;
6253 u16 num_alloc_stripes
;
6254 u64 raid56_full_stripe_start
= (u64
)-1;
6259 num_copies
= btrfs_num_copies(fs_info
, logical
, fs_info
->sectorsize
);
6260 if (mirror_num
> num_copies
)
6263 em
= btrfs_get_chunk_map(fs_info
, logical
, *length
);
6267 map
= em
->map_lookup
;
6268 data_stripes
= nr_data_stripes(map
);
6270 map_offset
= logical
- em
->start
;
6271 max_len
= btrfs_max_io_len(map
, op
, map_offset
, &stripe_nr
,
6272 &stripe_offset
, &raid56_full_stripe_start
);
6273 *length
= min_t(u64
, em
->len
- map_offset
, max_len
);
6275 down_read(&dev_replace
->rwsem
);
6276 dev_replace_is_ongoing
= btrfs_dev_replace_is_ongoing(dev_replace
);
6278 * Hold the semaphore for read during the whole operation, write is
6279 * requested at commit time but must wait.
6281 if (!dev_replace_is_ongoing
)
6282 up_read(&dev_replace
->rwsem
);
6286 if (map
->type
& BTRFS_BLOCK_GROUP_RAID0
) {
6287 stripe_index
= stripe_nr
% map
->num_stripes
;
6288 stripe_nr
/= map
->num_stripes
;
6289 if (op
== BTRFS_MAP_READ
)
6291 } else if (map
->type
& BTRFS_BLOCK_GROUP_RAID1_MASK
) {
6292 if (op
!= BTRFS_MAP_READ
) {
6293 num_stripes
= map
->num_stripes
;
6294 } else if (mirror_num
) {
6295 stripe_index
= mirror_num
- 1;
6297 stripe_index
= find_live_mirror(fs_info
, map
, 0,
6298 dev_replace_is_ongoing
);
6299 mirror_num
= stripe_index
+ 1;
6302 } else if (map
->type
& BTRFS_BLOCK_GROUP_DUP
) {
6303 if (op
!= BTRFS_MAP_READ
) {
6304 num_stripes
= map
->num_stripes
;
6305 } else if (mirror_num
) {
6306 stripe_index
= mirror_num
- 1;
6311 } else if (map
->type
& BTRFS_BLOCK_GROUP_RAID10
) {
6312 u32 factor
= map
->num_stripes
/ map
->sub_stripes
;
6314 stripe_index
= (stripe_nr
% factor
) * map
->sub_stripes
;
6315 stripe_nr
/= factor
;
6317 if (op
!= BTRFS_MAP_READ
)
6318 num_stripes
= map
->sub_stripes
;
6319 else if (mirror_num
)
6320 stripe_index
+= mirror_num
- 1;
6322 int old_stripe_index
= stripe_index
;
6323 stripe_index
= find_live_mirror(fs_info
, map
,
6325 dev_replace_is_ongoing
);
6326 mirror_num
= stripe_index
- old_stripe_index
+ 1;
6329 } else if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
) {
6330 if (op
!= BTRFS_MAP_READ
|| mirror_num
> 1) {
6332 * Needs full stripe mapping.
6334 * Push stripe_nr back to the start of the full stripe
6335 * For those cases needing a full stripe, @stripe_nr
6336 * is the full stripe number.
6338 * Originally we go raid56_full_stripe_start / full_stripe_len,
6339 * but that can be expensive. Here we just divide
6340 * @stripe_nr with @data_stripes.
6342 stripe_nr
/= data_stripes
;
6344 /* RAID[56] write or recovery. Return all stripes */
6345 num_stripes
= map
->num_stripes
;
6346 max_errors
= btrfs_chunk_max_errors(map
);
6348 /* Return the length to the full stripe end */
6349 *length
= min(logical
+ *length
,
6350 raid56_full_stripe_start
+ em
->start
+
6351 btrfs_stripe_nr_to_offset(data_stripes
)) -
6356 ASSERT(mirror_num
<= 1);
6357 /* Just grab the data stripe directly. */
6358 stripe_index
= stripe_nr
% data_stripes
;
6359 stripe_nr
/= data_stripes
;
6361 /* We distribute the parity blocks across stripes */
6362 stripe_index
= (stripe_nr
+ stripe_index
) % map
->num_stripes
;
6363 if (op
== BTRFS_MAP_READ
&& mirror_num
< 1)
6368 * After this, stripe_nr is the number of stripes on this
6369 * device we have to walk to find the data, and stripe_index is
6370 * the number of our device in the stripe array
6372 stripe_index
= stripe_nr
% map
->num_stripes
;
6373 stripe_nr
/= map
->num_stripes
;
6374 mirror_num
= stripe_index
+ 1;
6376 if (stripe_index
>= map
->num_stripes
) {
6378 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6379 stripe_index
, map
->num_stripes
);
6384 num_alloc_stripes
= num_stripes
;
6385 if (dev_replace_is_ongoing
&& dev_replace
->tgtdev
!= NULL
&&
6386 op
!= BTRFS_MAP_READ
)
6388 * For replace case, we need to add extra stripes for extra
6389 * duplicated stripes.
6391 * For both WRITE and GET_READ_MIRRORS, we may have at most
6392 * 2 more stripes (DUP types, otherwise 1).
6394 num_alloc_stripes
+= 2;
6397 * If this I/O maps to a single device, try to return the device and
6398 * physical block information on the stack instead of allocating an
6399 * I/O context structure.
6401 if (smap
&& num_alloc_stripes
== 1 &&
6402 !(btrfs_need_stripe_tree_update(fs_info
, map
->type
) &&
6403 op
!= BTRFS_MAP_READ
) &&
6404 !((map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
) && mirror_num
> 1)) {
6405 ret
= set_io_stripe(fs_info
, op
, logical
, length
, smap
, map
,
6406 stripe_index
, stripe_offset
, stripe_nr
);
6408 *mirror_num_ret
= mirror_num
;
6413 bioc
= alloc_btrfs_io_context(fs_info
, logical
, num_alloc_stripes
);
6418 bioc
->map_type
= map
->type
;
6421 * For RAID56 full map, we need to make sure the stripes[] follows the
6422 * rule that data stripes are all ordered, then followed with P and Q
6425 * It's still mostly the same as other profiles, just with extra rotation.
6427 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
&&
6428 (op
!= BTRFS_MAP_READ
|| mirror_num
> 1)) {
6430 * For RAID56 @stripe_nr is already the number of full stripes
6431 * before us, which is also the rotation value (needs to modulo
6432 * with num_stripes).
6434 * In this case, we just add @stripe_nr with @i, then do the
6435 * modulo, to reduce one modulo call.
6437 bioc
->full_stripe_logical
= em
->start
+
6438 btrfs_stripe_nr_to_offset(stripe_nr
* data_stripes
);
6439 for (int i
= 0; i
< num_stripes
; i
++) {
6440 ret
= set_io_stripe(fs_info
, op
, logical
, length
,
6441 &bioc
->stripes
[i
], map
,
6442 (i
+ stripe_nr
) % num_stripes
,
6443 stripe_offset
, stripe_nr
);
6449 * For all other non-RAID56 profiles, just copy the target
6450 * stripe into the bioc.
6452 for (i
= 0; i
< num_stripes
; i
++) {
6453 ret
= set_io_stripe(fs_info
, op
, logical
, length
,
6454 &bioc
->stripes
[i
], map
, stripe_index
,
6455 stripe_offset
, stripe_nr
);
6464 btrfs_put_bioc(bioc
);
6468 if (op
!= BTRFS_MAP_READ
)
6469 max_errors
= btrfs_chunk_max_errors(map
);
6471 if (dev_replace_is_ongoing
&& dev_replace
->tgtdev
!= NULL
&&
6472 op
!= BTRFS_MAP_READ
) {
6473 handle_ops_on_dev_replace(op
, bioc
, dev_replace
, logical
,
6474 &num_stripes
, &max_errors
);
6478 bioc
->num_stripes
= num_stripes
;
6479 bioc
->max_errors
= max_errors
;
6480 bioc
->mirror_num
= mirror_num
;
6483 if (dev_replace_is_ongoing
) {
6484 lockdep_assert_held(&dev_replace
->rwsem
);
6485 /* Unlock and let waiting writers proceed */
6486 up_read(&dev_replace
->rwsem
);
6488 free_extent_map(em
);
6492 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args
*args
,
6493 const struct btrfs_fs_devices
*fs_devices
)
6495 if (args
->fsid
== NULL
)
6497 if (memcmp(fs_devices
->metadata_uuid
, args
->fsid
, BTRFS_FSID_SIZE
) == 0)
6502 static bool dev_args_match_device(const struct btrfs_dev_lookup_args
*args
,
6503 const struct btrfs_device
*device
)
6505 if (args
->missing
) {
6506 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
) &&
6512 if (device
->devid
!= args
->devid
)
6514 if (args
->uuid
&& memcmp(device
->uuid
, args
->uuid
, BTRFS_UUID_SIZE
) != 0)
6520 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6523 * If devid and uuid are both specified, the match must be exact, otherwise
6524 * only devid is used.
6526 struct btrfs_device
*btrfs_find_device(const struct btrfs_fs_devices
*fs_devices
,
6527 const struct btrfs_dev_lookup_args
*args
)
6529 struct btrfs_device
*device
;
6530 struct btrfs_fs_devices
*seed_devs
;
6532 if (dev_args_match_fs_devices(args
, fs_devices
)) {
6533 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
) {
6534 if (dev_args_match_device(args
, device
))
6539 list_for_each_entry(seed_devs
, &fs_devices
->seed_list
, seed_list
) {
6540 if (!dev_args_match_fs_devices(args
, seed_devs
))
6542 list_for_each_entry(device
, &seed_devs
->devices
, dev_list
) {
6543 if (dev_args_match_device(args
, device
))
6551 static struct btrfs_device
*add_missing_dev(struct btrfs_fs_devices
*fs_devices
,
6552 u64 devid
, u8
*dev_uuid
)
6554 struct btrfs_device
*device
;
6555 unsigned int nofs_flag
;
6558 * We call this under the chunk_mutex, so we want to use NOFS for this
6559 * allocation, however we don't want to change btrfs_alloc_device() to
6560 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6564 nofs_flag
= memalloc_nofs_save();
6565 device
= btrfs_alloc_device(NULL
, &devid
, dev_uuid
, NULL
);
6566 memalloc_nofs_restore(nofs_flag
);
6570 list_add(&device
->dev_list
, &fs_devices
->devices
);
6571 device
->fs_devices
= fs_devices
;
6572 fs_devices
->num_devices
++;
6574 set_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
);
6575 fs_devices
->missing_devices
++;
6581 * Allocate new device struct, set up devid and UUID.
6583 * @fs_info: used only for generating a new devid, can be NULL if
6584 * devid is provided (i.e. @devid != NULL).
6585 * @devid: a pointer to devid for this device. If NULL a new devid
6587 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6589 * @path: a pointer to device path if available, NULL otherwise.
6591 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6592 * on error. Returned struct is not linked onto any lists and must be
6593 * destroyed with btrfs_free_device.
6595 struct btrfs_device
*btrfs_alloc_device(struct btrfs_fs_info
*fs_info
,
6596 const u64
*devid
, const u8
*uuid
,
6599 struct btrfs_device
*dev
;
6602 if (WARN_ON(!devid
&& !fs_info
))
6603 return ERR_PTR(-EINVAL
);
6605 dev
= kzalloc(sizeof(*dev
), GFP_KERNEL
);
6607 return ERR_PTR(-ENOMEM
);
6609 INIT_LIST_HEAD(&dev
->dev_list
);
6610 INIT_LIST_HEAD(&dev
->dev_alloc_list
);
6611 INIT_LIST_HEAD(&dev
->post_commit_list
);
6613 atomic_set(&dev
->dev_stats_ccnt
, 0);
6614 btrfs_device_data_ordered_init(dev
);
6615 extent_io_tree_init(fs_info
, &dev
->alloc_state
, IO_TREE_DEVICE_ALLOC_STATE
);
6622 ret
= find_next_devid(fs_info
, &tmp
);
6624 btrfs_free_device(dev
);
6625 return ERR_PTR(ret
);
6631 memcpy(dev
->uuid
, uuid
, BTRFS_UUID_SIZE
);
6633 generate_random_uuid(dev
->uuid
);
6636 struct rcu_string
*name
;
6638 name
= rcu_string_strdup(path
, GFP_KERNEL
);
6640 btrfs_free_device(dev
);
6641 return ERR_PTR(-ENOMEM
);
6643 rcu_assign_pointer(dev
->name
, name
);
6649 static void btrfs_report_missing_device(struct btrfs_fs_info
*fs_info
,
6650 u64 devid
, u8
*uuid
, bool error
)
6653 btrfs_err_rl(fs_info
, "devid %llu uuid %pU is missing",
6656 btrfs_warn_rl(fs_info
, "devid %llu uuid %pU is missing",
6660 u64
btrfs_calc_stripe_length(const struct extent_map
*em
)
6662 const struct map_lookup
*map
= em
->map_lookup
;
6663 const int data_stripes
= calc_data_stripes(map
->type
, map
->num_stripes
);
6665 return div_u64(em
->len
, data_stripes
);
6668 #if BITS_PER_LONG == 32
6670 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
6671 * can't be accessed on 32bit systems.
6673 * This function do mount time check to reject the fs if it already has
6674 * metadata chunk beyond that limit.
6676 static int check_32bit_meta_chunk(struct btrfs_fs_info
*fs_info
,
6677 u64 logical
, u64 length
, u64 type
)
6679 if (!(type
& BTRFS_BLOCK_GROUP_METADATA
))
6682 if (logical
+ length
< MAX_LFS_FILESIZE
)
6685 btrfs_err_32bit_limit(fs_info
);
6690 * This is to give early warning for any metadata chunk reaching
6691 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
6692 * Although we can still access the metadata, it's not going to be possible
6693 * once the limit is reached.
6695 static void warn_32bit_meta_chunk(struct btrfs_fs_info
*fs_info
,
6696 u64 logical
, u64 length
, u64 type
)
6698 if (!(type
& BTRFS_BLOCK_GROUP_METADATA
))
6701 if (logical
+ length
< BTRFS_32BIT_EARLY_WARN_THRESHOLD
)
6704 btrfs_warn_32bit_limit(fs_info
);
6708 static struct btrfs_device
*handle_missing_device(struct btrfs_fs_info
*fs_info
,
6709 u64 devid
, u8
*uuid
)
6711 struct btrfs_device
*dev
;
6713 if (!btrfs_test_opt(fs_info
, DEGRADED
)) {
6714 btrfs_report_missing_device(fs_info
, devid
, uuid
, true);
6715 return ERR_PTR(-ENOENT
);
6718 dev
= add_missing_dev(fs_info
->fs_devices
, devid
, uuid
);
6720 btrfs_err(fs_info
, "failed to init missing device %llu: %ld",
6721 devid
, PTR_ERR(dev
));
6724 btrfs_report_missing_device(fs_info
, devid
, uuid
, false);
6729 static int read_one_chunk(struct btrfs_key
*key
, struct extent_buffer
*leaf
,
6730 struct btrfs_chunk
*chunk
)
6732 BTRFS_DEV_LOOKUP_ARGS(args
);
6733 struct btrfs_fs_info
*fs_info
= leaf
->fs_info
;
6734 struct extent_map_tree
*map_tree
= &fs_info
->mapping_tree
;
6735 struct map_lookup
*map
;
6736 struct extent_map
*em
;
6741 u8 uuid
[BTRFS_UUID_SIZE
];
6747 logical
= key
->offset
;
6748 length
= btrfs_chunk_length(leaf
, chunk
);
6749 type
= btrfs_chunk_type(leaf
, chunk
);
6750 index
= btrfs_bg_flags_to_raid_index(type
);
6751 num_stripes
= btrfs_chunk_num_stripes(leaf
, chunk
);
6753 #if BITS_PER_LONG == 32
6754 ret
= check_32bit_meta_chunk(fs_info
, logical
, length
, type
);
6757 warn_32bit_meta_chunk(fs_info
, logical
, length
, type
);
6761 * Only need to verify chunk item if we're reading from sys chunk array,
6762 * as chunk item in tree block is already verified by tree-checker.
6764 if (leaf
->start
== BTRFS_SUPER_INFO_OFFSET
) {
6765 ret
= btrfs_check_chunk_valid(leaf
, chunk
, logical
);
6770 read_lock(&map_tree
->lock
);
6771 em
= lookup_extent_mapping(map_tree
, logical
, 1);
6772 read_unlock(&map_tree
->lock
);
6774 /* already mapped? */
6775 if (em
&& em
->start
<= logical
&& em
->start
+ em
->len
> logical
) {
6776 free_extent_map(em
);
6779 free_extent_map(em
);
6782 em
= alloc_extent_map();
6785 map
= kmalloc(map_lookup_size(num_stripes
), GFP_NOFS
);
6787 free_extent_map(em
);
6791 set_bit(EXTENT_FLAG_FS_MAPPING
, &em
->flags
);
6792 em
->map_lookup
= map
;
6793 em
->start
= logical
;
6796 em
->block_start
= 0;
6797 em
->block_len
= em
->len
;
6799 map
->num_stripes
= num_stripes
;
6800 map
->io_width
= btrfs_chunk_io_width(leaf
, chunk
);
6801 map
->io_align
= btrfs_chunk_io_align(leaf
, chunk
);
6804 * We can't use the sub_stripes value, as for profiles other than
6805 * RAID10, they may have 0 as sub_stripes for filesystems created by
6806 * older mkfs (<v5.4).
6807 * In that case, it can cause divide-by-zero errors later.
6808 * Since currently sub_stripes is fixed for each profile, let's
6809 * use the trusted value instead.
6811 map
->sub_stripes
= btrfs_raid_array
[index
].sub_stripes
;
6812 map
->verified_stripes
= 0;
6813 em
->orig_block_len
= btrfs_calc_stripe_length(em
);
6814 for (i
= 0; i
< num_stripes
; i
++) {
6815 map
->stripes
[i
].physical
=
6816 btrfs_stripe_offset_nr(leaf
, chunk
, i
);
6817 devid
= btrfs_stripe_devid_nr(leaf
, chunk
, i
);
6819 read_extent_buffer(leaf
, uuid
, (unsigned long)
6820 btrfs_stripe_dev_uuid_nr(chunk
, i
),
6823 map
->stripes
[i
].dev
= btrfs_find_device(fs_info
->fs_devices
, &args
);
6824 if (!map
->stripes
[i
].dev
) {
6825 map
->stripes
[i
].dev
= handle_missing_device(fs_info
,
6827 if (IS_ERR(map
->stripes
[i
].dev
)) {
6828 ret
= PTR_ERR(map
->stripes
[i
].dev
);
6829 free_extent_map(em
);
6834 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA
,
6835 &(map
->stripes
[i
].dev
->dev_state
));
6838 write_lock(&map_tree
->lock
);
6839 ret
= add_extent_mapping(map_tree
, em
, 0);
6840 write_unlock(&map_tree
->lock
);
6843 "failed to add chunk map, start=%llu len=%llu: %d",
6844 em
->start
, em
->len
, ret
);
6846 free_extent_map(em
);
6851 static void fill_device_from_item(struct extent_buffer
*leaf
,
6852 struct btrfs_dev_item
*dev_item
,
6853 struct btrfs_device
*device
)
6857 device
->devid
= btrfs_device_id(leaf
, dev_item
);
6858 device
->disk_total_bytes
= btrfs_device_total_bytes(leaf
, dev_item
);
6859 device
->total_bytes
= device
->disk_total_bytes
;
6860 device
->commit_total_bytes
= device
->disk_total_bytes
;
6861 device
->bytes_used
= btrfs_device_bytes_used(leaf
, dev_item
);
6862 device
->commit_bytes_used
= device
->bytes_used
;
6863 device
->type
= btrfs_device_type(leaf
, dev_item
);
6864 device
->io_align
= btrfs_device_io_align(leaf
, dev_item
);
6865 device
->io_width
= btrfs_device_io_width(leaf
, dev_item
);
6866 device
->sector_size
= btrfs_device_sector_size(leaf
, dev_item
);
6867 WARN_ON(device
->devid
== BTRFS_DEV_REPLACE_DEVID
);
6868 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
);
6870 ptr
= btrfs_device_uuid(dev_item
);
6871 read_extent_buffer(leaf
, device
->uuid
, ptr
, BTRFS_UUID_SIZE
);
6874 static struct btrfs_fs_devices
*open_seed_devices(struct btrfs_fs_info
*fs_info
,
6877 struct btrfs_fs_devices
*fs_devices
;
6880 lockdep_assert_held(&uuid_mutex
);
6883 /* This will match only for multi-device seed fs */
6884 list_for_each_entry(fs_devices
, &fs_info
->fs_devices
->seed_list
, seed_list
)
6885 if (!memcmp(fs_devices
->fsid
, fsid
, BTRFS_FSID_SIZE
))
6889 fs_devices
= find_fsid(fsid
, NULL
);
6891 if (!btrfs_test_opt(fs_info
, DEGRADED
))
6892 return ERR_PTR(-ENOENT
);
6894 fs_devices
= alloc_fs_devices(fsid
);
6895 if (IS_ERR(fs_devices
))
6898 fs_devices
->seeding
= true;
6899 fs_devices
->opened
= 1;
6904 * Upon first call for a seed fs fsid, just create a private copy of the
6905 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
6907 fs_devices
= clone_fs_devices(fs_devices
);
6908 if (IS_ERR(fs_devices
))
6911 ret
= open_fs_devices(fs_devices
, BLK_OPEN_READ
, fs_info
->bdev_holder
);
6913 free_fs_devices(fs_devices
);
6914 return ERR_PTR(ret
);
6917 if (!fs_devices
->seeding
) {
6918 close_fs_devices(fs_devices
);
6919 free_fs_devices(fs_devices
);
6920 return ERR_PTR(-EINVAL
);
6923 list_add(&fs_devices
->seed_list
, &fs_info
->fs_devices
->seed_list
);
6928 static int read_one_dev(struct extent_buffer
*leaf
,
6929 struct btrfs_dev_item
*dev_item
)
6931 BTRFS_DEV_LOOKUP_ARGS(args
);
6932 struct btrfs_fs_info
*fs_info
= leaf
->fs_info
;
6933 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
6934 struct btrfs_device
*device
;
6937 u8 fs_uuid
[BTRFS_FSID_SIZE
];
6938 u8 dev_uuid
[BTRFS_UUID_SIZE
];
6940 devid
= btrfs_device_id(leaf
, dev_item
);
6942 read_extent_buffer(leaf
, dev_uuid
, btrfs_device_uuid(dev_item
),
6944 read_extent_buffer(leaf
, fs_uuid
, btrfs_device_fsid(dev_item
),
6946 args
.uuid
= dev_uuid
;
6947 args
.fsid
= fs_uuid
;
6949 if (memcmp(fs_uuid
, fs_devices
->metadata_uuid
, BTRFS_FSID_SIZE
)) {
6950 fs_devices
= open_seed_devices(fs_info
, fs_uuid
);
6951 if (IS_ERR(fs_devices
))
6952 return PTR_ERR(fs_devices
);
6955 device
= btrfs_find_device(fs_info
->fs_devices
, &args
);
6957 if (!btrfs_test_opt(fs_info
, DEGRADED
)) {
6958 btrfs_report_missing_device(fs_info
, devid
,
6963 device
= add_missing_dev(fs_devices
, devid
, dev_uuid
);
6964 if (IS_ERR(device
)) {
6966 "failed to add missing dev %llu: %ld",
6967 devid
, PTR_ERR(device
));
6968 return PTR_ERR(device
);
6970 btrfs_report_missing_device(fs_info
, devid
, dev_uuid
, false);
6972 if (!device
->bdev
) {
6973 if (!btrfs_test_opt(fs_info
, DEGRADED
)) {
6974 btrfs_report_missing_device(fs_info
,
6975 devid
, dev_uuid
, true);
6978 btrfs_report_missing_device(fs_info
, devid
,
6982 if (!device
->bdev
&&
6983 !test_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
)) {
6985 * this happens when a device that was properly setup
6986 * in the device info lists suddenly goes bad.
6987 * device->bdev is NULL, and so we have to set
6988 * device->missing to one here
6990 device
->fs_devices
->missing_devices
++;
6991 set_bit(BTRFS_DEV_STATE_MISSING
, &device
->dev_state
);
6994 /* Move the device to its own fs_devices */
6995 if (device
->fs_devices
!= fs_devices
) {
6996 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING
,
6997 &device
->dev_state
));
6999 list_move(&device
->dev_list
, &fs_devices
->devices
);
7000 device
->fs_devices
->num_devices
--;
7001 fs_devices
->num_devices
++;
7003 device
->fs_devices
->missing_devices
--;
7004 fs_devices
->missing_devices
++;
7006 device
->fs_devices
= fs_devices
;
7010 if (device
->fs_devices
!= fs_info
->fs_devices
) {
7011 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
));
7012 if (device
->generation
!=
7013 btrfs_device_generation(leaf
, dev_item
))
7017 fill_device_from_item(leaf
, dev_item
, device
);
7019 u64 max_total_bytes
= bdev_nr_bytes(device
->bdev
);
7021 if (device
->total_bytes
> max_total_bytes
) {
7023 "device total_bytes should be at most %llu but found %llu",
7024 max_total_bytes
, device
->total_bytes
);
7028 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
);
7029 if (test_bit(BTRFS_DEV_STATE_WRITEABLE
, &device
->dev_state
) &&
7030 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
)) {
7031 device
->fs_devices
->total_rw_bytes
+= device
->total_bytes
;
7032 atomic64_add(device
->total_bytes
- device
->bytes_used
,
7033 &fs_info
->free_chunk_space
);
7039 int btrfs_read_sys_array(struct btrfs_fs_info
*fs_info
)
7041 struct btrfs_super_block
*super_copy
= fs_info
->super_copy
;
7042 struct extent_buffer
*sb
;
7043 struct btrfs_disk_key
*disk_key
;
7044 struct btrfs_chunk
*chunk
;
7046 unsigned long sb_array_offset
;
7053 struct btrfs_key key
;
7055 ASSERT(BTRFS_SUPER_INFO_SIZE
<= fs_info
->nodesize
);
7058 * We allocated a dummy extent, just to use extent buffer accessors.
7059 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
7060 * that's fine, we will not go beyond system chunk array anyway.
7062 sb
= alloc_dummy_extent_buffer(fs_info
, BTRFS_SUPER_INFO_OFFSET
);
7065 set_extent_buffer_uptodate(sb
);
7067 write_extent_buffer(sb
, super_copy
, 0, BTRFS_SUPER_INFO_SIZE
);
7068 array_size
= btrfs_super_sys_array_size(super_copy
);
7070 array_ptr
= super_copy
->sys_chunk_array
;
7071 sb_array_offset
= offsetof(struct btrfs_super_block
, sys_chunk_array
);
7074 while (cur_offset
< array_size
) {
7075 disk_key
= (struct btrfs_disk_key
*)array_ptr
;
7076 len
= sizeof(*disk_key
);
7077 if (cur_offset
+ len
> array_size
)
7078 goto out_short_read
;
7080 btrfs_disk_key_to_cpu(&key
, disk_key
);
7083 sb_array_offset
+= len
;
7086 if (key
.type
!= BTRFS_CHUNK_ITEM_KEY
) {
7088 "unexpected item type %u in sys_array at offset %u",
7089 (u32
)key
.type
, cur_offset
);
7094 chunk
= (struct btrfs_chunk
*)sb_array_offset
;
7096 * At least one btrfs_chunk with one stripe must be present,
7097 * exact stripe count check comes afterwards
7099 len
= btrfs_chunk_item_size(1);
7100 if (cur_offset
+ len
> array_size
)
7101 goto out_short_read
;
7103 num_stripes
= btrfs_chunk_num_stripes(sb
, chunk
);
7106 "invalid number of stripes %u in sys_array at offset %u",
7107 num_stripes
, cur_offset
);
7112 type
= btrfs_chunk_type(sb
, chunk
);
7113 if ((type
& BTRFS_BLOCK_GROUP_SYSTEM
) == 0) {
7115 "invalid chunk type %llu in sys_array at offset %u",
7121 len
= btrfs_chunk_item_size(num_stripes
);
7122 if (cur_offset
+ len
> array_size
)
7123 goto out_short_read
;
7125 ret
= read_one_chunk(&key
, sb
, chunk
);
7130 sb_array_offset
+= len
;
7133 clear_extent_buffer_uptodate(sb
);
7134 free_extent_buffer_stale(sb
);
7138 btrfs_err(fs_info
, "sys_array too short to read %u bytes at offset %u",
7140 clear_extent_buffer_uptodate(sb
);
7141 free_extent_buffer_stale(sb
);
7146 * Check if all chunks in the fs are OK for read-write degraded mount
7148 * If the @failing_dev is specified, it's accounted as missing.
7150 * Return true if all chunks meet the minimal RW mount requirements.
7151 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7153 bool btrfs_check_rw_degradable(struct btrfs_fs_info
*fs_info
,
7154 struct btrfs_device
*failing_dev
)
7156 struct extent_map_tree
*map_tree
= &fs_info
->mapping_tree
;
7157 struct extent_map
*em
;
7161 read_lock(&map_tree
->lock
);
7162 em
= lookup_extent_mapping(map_tree
, 0, (u64
)-1);
7163 read_unlock(&map_tree
->lock
);
7164 /* No chunk at all? Return false anyway */
7170 struct map_lookup
*map
;
7175 map
= em
->map_lookup
;
7177 btrfs_get_num_tolerated_disk_barrier_failures(
7179 for (i
= 0; i
< map
->num_stripes
; i
++) {
7180 struct btrfs_device
*dev
= map
->stripes
[i
].dev
;
7182 if (!dev
|| !dev
->bdev
||
7183 test_bit(BTRFS_DEV_STATE_MISSING
, &dev
->dev_state
) ||
7184 dev
->last_flush_error
)
7186 else if (failing_dev
&& failing_dev
== dev
)
7189 if (missing
> max_tolerated
) {
7192 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7193 em
->start
, missing
, max_tolerated
);
7194 free_extent_map(em
);
7198 next_start
= extent_map_end(em
);
7199 free_extent_map(em
);
7201 read_lock(&map_tree
->lock
);
7202 em
= lookup_extent_mapping(map_tree
, next_start
,
7203 (u64
)(-1) - next_start
);
7204 read_unlock(&map_tree
->lock
);
7210 static void readahead_tree_node_children(struct extent_buffer
*node
)
7213 const int nr_items
= btrfs_header_nritems(node
);
7215 for (i
= 0; i
< nr_items
; i
++)
7216 btrfs_readahead_node_child(node
, i
);
7219 int btrfs_read_chunk_tree(struct btrfs_fs_info
*fs_info
)
7221 struct btrfs_root
*root
= fs_info
->chunk_root
;
7222 struct btrfs_path
*path
;
7223 struct extent_buffer
*leaf
;
7224 struct btrfs_key key
;
7225 struct btrfs_key found_key
;
7230 u64 last_ra_node
= 0;
7232 path
= btrfs_alloc_path();
7237 * uuid_mutex is needed only if we are mounting a sprout FS
7238 * otherwise we don't need it.
7240 mutex_lock(&uuid_mutex
);
7243 * It is possible for mount and umount to race in such a way that
7244 * we execute this code path, but open_fs_devices failed to clear
7245 * total_rw_bytes. We certainly want it cleared before reading the
7246 * device items, so clear it here.
7248 fs_info
->fs_devices
->total_rw_bytes
= 0;
7251 * Lockdep complains about possible circular locking dependency between
7252 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7253 * used for freeze procection of a fs (struct super_block.s_writers),
7254 * which we take when starting a transaction, and extent buffers of the
7255 * chunk tree if we call read_one_dev() while holding a lock on an
7256 * extent buffer of the chunk tree. Since we are mounting the filesystem
7257 * and at this point there can't be any concurrent task modifying the
7258 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7260 ASSERT(!test_bit(BTRFS_FS_OPEN
, &fs_info
->flags
));
7261 path
->skip_locking
= 1;
7264 * Read all device items, and then all the chunk items. All
7265 * device items are found before any chunk item (their object id
7266 * is smaller than the lowest possible object id for a chunk
7267 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7269 key
.objectid
= BTRFS_DEV_ITEMS_OBJECTID
;
7272 btrfs_for_each_slot(root
, &key
, &found_key
, path
, iter_ret
) {
7273 struct extent_buffer
*node
= path
->nodes
[1];
7275 leaf
= path
->nodes
[0];
7276 slot
= path
->slots
[0];
7279 if (last_ra_node
!= node
->start
) {
7280 readahead_tree_node_children(node
);
7281 last_ra_node
= node
->start
;
7284 if (found_key
.type
== BTRFS_DEV_ITEM_KEY
) {
7285 struct btrfs_dev_item
*dev_item
;
7286 dev_item
= btrfs_item_ptr(leaf
, slot
,
7287 struct btrfs_dev_item
);
7288 ret
= read_one_dev(leaf
, dev_item
);
7292 } else if (found_key
.type
== BTRFS_CHUNK_ITEM_KEY
) {
7293 struct btrfs_chunk
*chunk
;
7296 * We are only called at mount time, so no need to take
7297 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7298 * we always lock first fs_info->chunk_mutex before
7299 * acquiring any locks on the chunk tree. This is a
7300 * requirement for chunk allocation, see the comment on
7301 * top of btrfs_chunk_alloc() for details.
7303 chunk
= btrfs_item_ptr(leaf
, slot
, struct btrfs_chunk
);
7304 ret
= read_one_chunk(&found_key
, leaf
, chunk
);
7309 /* Catch error found during iteration */
7316 * After loading chunk tree, we've got all device information,
7317 * do another round of validation checks.
7319 if (total_dev
!= fs_info
->fs_devices
->total_devices
) {
7321 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7322 btrfs_super_num_devices(fs_info
->super_copy
),
7324 fs_info
->fs_devices
->total_devices
= total_dev
;
7325 btrfs_set_super_num_devices(fs_info
->super_copy
, total_dev
);
7327 if (btrfs_super_total_bytes(fs_info
->super_copy
) <
7328 fs_info
->fs_devices
->total_rw_bytes
) {
7330 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7331 btrfs_super_total_bytes(fs_info
->super_copy
),
7332 fs_info
->fs_devices
->total_rw_bytes
);
7338 mutex_unlock(&uuid_mutex
);
7340 btrfs_free_path(path
);
7344 int btrfs_init_devices_late(struct btrfs_fs_info
*fs_info
)
7346 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
, *seed_devs
;
7347 struct btrfs_device
*device
;
7350 fs_devices
->fs_info
= fs_info
;
7352 mutex_lock(&fs_devices
->device_list_mutex
);
7353 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
)
7354 device
->fs_info
= fs_info
;
7356 list_for_each_entry(seed_devs
, &fs_devices
->seed_list
, seed_list
) {
7357 list_for_each_entry(device
, &seed_devs
->devices
, dev_list
) {
7358 device
->fs_info
= fs_info
;
7359 ret
= btrfs_get_dev_zone_info(device
, false);
7364 seed_devs
->fs_info
= fs_info
;
7366 mutex_unlock(&fs_devices
->device_list_mutex
);
7371 static u64
btrfs_dev_stats_value(const struct extent_buffer
*eb
,
7372 const struct btrfs_dev_stats_item
*ptr
,
7377 read_extent_buffer(eb
, &val
,
7378 offsetof(struct btrfs_dev_stats_item
, values
) +
7379 ((unsigned long)ptr
) + (index
* sizeof(u64
)),
7384 static void btrfs_set_dev_stats_value(struct extent_buffer
*eb
,
7385 struct btrfs_dev_stats_item
*ptr
,
7388 write_extent_buffer(eb
, &val
,
7389 offsetof(struct btrfs_dev_stats_item
, values
) +
7390 ((unsigned long)ptr
) + (index
* sizeof(u64
)),
7394 static int btrfs_device_init_dev_stats(struct btrfs_device
*device
,
7395 struct btrfs_path
*path
)
7397 struct btrfs_dev_stats_item
*ptr
;
7398 struct extent_buffer
*eb
;
7399 struct btrfs_key key
;
7403 if (!device
->fs_info
->dev_root
)
7406 key
.objectid
= BTRFS_DEV_STATS_OBJECTID
;
7407 key
.type
= BTRFS_PERSISTENT_ITEM_KEY
;
7408 key
.offset
= device
->devid
;
7409 ret
= btrfs_search_slot(NULL
, device
->fs_info
->dev_root
, &key
, path
, 0, 0);
7411 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++)
7412 btrfs_dev_stat_set(device
, i
, 0);
7413 device
->dev_stats_valid
= 1;
7414 btrfs_release_path(path
);
7415 return ret
< 0 ? ret
: 0;
7417 slot
= path
->slots
[0];
7418 eb
= path
->nodes
[0];
7419 item_size
= btrfs_item_size(eb
, slot
);
7421 ptr
= btrfs_item_ptr(eb
, slot
, struct btrfs_dev_stats_item
);
7423 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++) {
7424 if (item_size
>= (1 + i
) * sizeof(__le64
))
7425 btrfs_dev_stat_set(device
, i
,
7426 btrfs_dev_stats_value(eb
, ptr
, i
));
7428 btrfs_dev_stat_set(device
, i
, 0);
7431 device
->dev_stats_valid
= 1;
7432 btrfs_dev_stat_print_on_load(device
);
7433 btrfs_release_path(path
);
7438 int btrfs_init_dev_stats(struct btrfs_fs_info
*fs_info
)
7440 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
, *seed_devs
;
7441 struct btrfs_device
*device
;
7442 struct btrfs_path
*path
= NULL
;
7445 path
= btrfs_alloc_path();
7449 mutex_lock(&fs_devices
->device_list_mutex
);
7450 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
) {
7451 ret
= btrfs_device_init_dev_stats(device
, path
);
7455 list_for_each_entry(seed_devs
, &fs_devices
->seed_list
, seed_list
) {
7456 list_for_each_entry(device
, &seed_devs
->devices
, dev_list
) {
7457 ret
= btrfs_device_init_dev_stats(device
, path
);
7463 mutex_unlock(&fs_devices
->device_list_mutex
);
7465 btrfs_free_path(path
);
7469 static int update_dev_stat_item(struct btrfs_trans_handle
*trans
,
7470 struct btrfs_device
*device
)
7472 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
7473 struct btrfs_root
*dev_root
= fs_info
->dev_root
;
7474 struct btrfs_path
*path
;
7475 struct btrfs_key key
;
7476 struct extent_buffer
*eb
;
7477 struct btrfs_dev_stats_item
*ptr
;
7481 key
.objectid
= BTRFS_DEV_STATS_OBJECTID
;
7482 key
.type
= BTRFS_PERSISTENT_ITEM_KEY
;
7483 key
.offset
= device
->devid
;
7485 path
= btrfs_alloc_path();
7488 ret
= btrfs_search_slot(trans
, dev_root
, &key
, path
, -1, 1);
7490 btrfs_warn_in_rcu(fs_info
,
7491 "error %d while searching for dev_stats item for device %s",
7492 ret
, btrfs_dev_name(device
));
7497 btrfs_item_size(path
->nodes
[0], path
->slots
[0]) < sizeof(*ptr
)) {
7498 /* need to delete old one and insert a new one */
7499 ret
= btrfs_del_item(trans
, dev_root
, path
);
7501 btrfs_warn_in_rcu(fs_info
,
7502 "delete too small dev_stats item for device %s failed %d",
7503 btrfs_dev_name(device
), ret
);
7510 /* need to insert a new item */
7511 btrfs_release_path(path
);
7512 ret
= btrfs_insert_empty_item(trans
, dev_root
, path
,
7513 &key
, sizeof(*ptr
));
7515 btrfs_warn_in_rcu(fs_info
,
7516 "insert dev_stats item for device %s failed %d",
7517 btrfs_dev_name(device
), ret
);
7522 eb
= path
->nodes
[0];
7523 ptr
= btrfs_item_ptr(eb
, path
->slots
[0], struct btrfs_dev_stats_item
);
7524 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++)
7525 btrfs_set_dev_stats_value(eb
, ptr
, i
,
7526 btrfs_dev_stat_read(device
, i
));
7527 btrfs_mark_buffer_dirty(trans
, eb
);
7530 btrfs_free_path(path
);
7535 * called from commit_transaction. Writes all changed device stats to disk.
7537 int btrfs_run_dev_stats(struct btrfs_trans_handle
*trans
)
7539 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
7540 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
7541 struct btrfs_device
*device
;
7545 mutex_lock(&fs_devices
->device_list_mutex
);
7546 list_for_each_entry(device
, &fs_devices
->devices
, dev_list
) {
7547 stats_cnt
= atomic_read(&device
->dev_stats_ccnt
);
7548 if (!device
->dev_stats_valid
|| stats_cnt
== 0)
7553 * There is a LOAD-LOAD control dependency between the value of
7554 * dev_stats_ccnt and updating the on-disk values which requires
7555 * reading the in-memory counters. Such control dependencies
7556 * require explicit read memory barriers.
7558 * This memory barriers pairs with smp_mb__before_atomic in
7559 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7560 * barrier implied by atomic_xchg in
7561 * btrfs_dev_stats_read_and_reset
7565 ret
= update_dev_stat_item(trans
, device
);
7567 atomic_sub(stats_cnt
, &device
->dev_stats_ccnt
);
7569 mutex_unlock(&fs_devices
->device_list_mutex
);
7574 void btrfs_dev_stat_inc_and_print(struct btrfs_device
*dev
, int index
)
7576 btrfs_dev_stat_inc(dev
, index
);
7578 if (!dev
->dev_stats_valid
)
7580 btrfs_err_rl_in_rcu(dev
->fs_info
,
7581 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7582 btrfs_dev_name(dev
),
7583 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_WRITE_ERRS
),
7584 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_READ_ERRS
),
7585 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_FLUSH_ERRS
),
7586 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_CORRUPTION_ERRS
),
7587 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_GENERATION_ERRS
));
7590 static void btrfs_dev_stat_print_on_load(struct btrfs_device
*dev
)
7594 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++)
7595 if (btrfs_dev_stat_read(dev
, i
) != 0)
7597 if (i
== BTRFS_DEV_STAT_VALUES_MAX
)
7598 return; /* all values == 0, suppress message */
7600 btrfs_info_in_rcu(dev
->fs_info
,
7601 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7602 btrfs_dev_name(dev
),
7603 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_WRITE_ERRS
),
7604 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_READ_ERRS
),
7605 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_FLUSH_ERRS
),
7606 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_CORRUPTION_ERRS
),
7607 btrfs_dev_stat_read(dev
, BTRFS_DEV_STAT_GENERATION_ERRS
));
7610 int btrfs_get_dev_stats(struct btrfs_fs_info
*fs_info
,
7611 struct btrfs_ioctl_get_dev_stats
*stats
)
7613 BTRFS_DEV_LOOKUP_ARGS(args
);
7614 struct btrfs_device
*dev
;
7615 struct btrfs_fs_devices
*fs_devices
= fs_info
->fs_devices
;
7618 mutex_lock(&fs_devices
->device_list_mutex
);
7619 args
.devid
= stats
->devid
;
7620 dev
= btrfs_find_device(fs_info
->fs_devices
, &args
);
7621 mutex_unlock(&fs_devices
->device_list_mutex
);
7624 btrfs_warn(fs_info
, "get dev_stats failed, device not found");
7626 } else if (!dev
->dev_stats_valid
) {
7627 btrfs_warn(fs_info
, "get dev_stats failed, not yet valid");
7629 } else if (stats
->flags
& BTRFS_DEV_STATS_RESET
) {
7630 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++) {
7631 if (stats
->nr_items
> i
)
7633 btrfs_dev_stat_read_and_reset(dev
, i
);
7635 btrfs_dev_stat_set(dev
, i
, 0);
7637 btrfs_info(fs_info
, "device stats zeroed by %s (%d)",
7638 current
->comm
, task_pid_nr(current
));
7640 for (i
= 0; i
< BTRFS_DEV_STAT_VALUES_MAX
; i
++)
7641 if (stats
->nr_items
> i
)
7642 stats
->values
[i
] = btrfs_dev_stat_read(dev
, i
);
7644 if (stats
->nr_items
> BTRFS_DEV_STAT_VALUES_MAX
)
7645 stats
->nr_items
= BTRFS_DEV_STAT_VALUES_MAX
;
7650 * Update the size and bytes used for each device where it changed. This is
7651 * delayed since we would otherwise get errors while writing out the
7654 * Must be invoked during transaction commit.
7656 void btrfs_commit_device_sizes(struct btrfs_transaction
*trans
)
7658 struct btrfs_device
*curr
, *next
;
7660 ASSERT(trans
->state
== TRANS_STATE_COMMIT_DOING
);
7662 if (list_empty(&trans
->dev_update_list
))
7666 * We don't need the device_list_mutex here. This list is owned by the
7667 * transaction and the transaction must complete before the device is
7670 mutex_lock(&trans
->fs_info
->chunk_mutex
);
7671 list_for_each_entry_safe(curr
, next
, &trans
->dev_update_list
,
7673 list_del_init(&curr
->post_commit_list
);
7674 curr
->commit_total_bytes
= curr
->disk_total_bytes
;
7675 curr
->commit_bytes_used
= curr
->bytes_used
;
7677 mutex_unlock(&trans
->fs_info
->chunk_mutex
);
7681 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7683 int btrfs_bg_type_to_factor(u64 flags
)
7685 const int index
= btrfs_bg_flags_to_raid_index(flags
);
7687 return btrfs_raid_array
[index
].ncopies
;
7692 static int verify_one_dev_extent(struct btrfs_fs_info
*fs_info
,
7693 u64 chunk_offset
, u64 devid
,
7694 u64 physical_offset
, u64 physical_len
)
7696 struct btrfs_dev_lookup_args args
= { .devid
= devid
};
7697 struct extent_map_tree
*em_tree
= &fs_info
->mapping_tree
;
7698 struct extent_map
*em
;
7699 struct map_lookup
*map
;
7700 struct btrfs_device
*dev
;
7706 read_lock(&em_tree
->lock
);
7707 em
= lookup_extent_mapping(em_tree
, chunk_offset
, 1);
7708 read_unlock(&em_tree
->lock
);
7712 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7713 physical_offset
, devid
);
7718 map
= em
->map_lookup
;
7719 stripe_len
= btrfs_calc_stripe_length(em
);
7720 if (physical_len
!= stripe_len
) {
7722 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7723 physical_offset
, devid
, em
->start
, physical_len
,
7730 * Very old mkfs.btrfs (before v4.1) will not respect the reserved
7731 * space. Although kernel can handle it without problem, better to warn
7734 if (physical_offset
< BTRFS_DEVICE_RANGE_RESERVED
)
7736 "devid %llu physical %llu len %llu inside the reserved space",
7737 devid
, physical_offset
, physical_len
);
7739 for (i
= 0; i
< map
->num_stripes
; i
++) {
7740 if (map
->stripes
[i
].dev
->devid
== devid
&&
7741 map
->stripes
[i
].physical
== physical_offset
) {
7743 if (map
->verified_stripes
>= map
->num_stripes
) {
7745 "too many dev extents for chunk %llu found",
7750 map
->verified_stripes
++;
7756 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7757 physical_offset
, devid
);
7761 /* Make sure no dev extent is beyond device boundary */
7762 dev
= btrfs_find_device(fs_info
->fs_devices
, &args
);
7764 btrfs_err(fs_info
, "failed to find devid %llu", devid
);
7769 if (physical_offset
+ physical_len
> dev
->disk_total_bytes
) {
7771 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7772 devid
, physical_offset
, physical_len
,
7773 dev
->disk_total_bytes
);
7778 if (dev
->zone_info
) {
7779 u64 zone_size
= dev
->zone_info
->zone_size
;
7781 if (!IS_ALIGNED(physical_offset
, zone_size
) ||
7782 !IS_ALIGNED(physical_len
, zone_size
)) {
7784 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
7785 devid
, physical_offset
, physical_len
);
7792 free_extent_map(em
);
7796 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info
*fs_info
)
7798 struct extent_map_tree
*em_tree
= &fs_info
->mapping_tree
;
7799 struct extent_map
*em
;
7800 struct rb_node
*node
;
7803 read_lock(&em_tree
->lock
);
7804 for (node
= rb_first_cached(&em_tree
->map
); node
; node
= rb_next(node
)) {
7805 em
= rb_entry(node
, struct extent_map
, rb_node
);
7806 if (em
->map_lookup
->num_stripes
!=
7807 em
->map_lookup
->verified_stripes
) {
7809 "chunk %llu has missing dev extent, have %d expect %d",
7810 em
->start
, em
->map_lookup
->verified_stripes
,
7811 em
->map_lookup
->num_stripes
);
7817 read_unlock(&em_tree
->lock
);
7822 * Ensure that all dev extents are mapped to correct chunk, otherwise
7823 * later chunk allocation/free would cause unexpected behavior.
7825 * NOTE: This will iterate through the whole device tree, which should be of
7826 * the same size level as the chunk tree. This slightly increases mount time.
7828 int btrfs_verify_dev_extents(struct btrfs_fs_info
*fs_info
)
7830 struct btrfs_path
*path
;
7831 struct btrfs_root
*root
= fs_info
->dev_root
;
7832 struct btrfs_key key
;
7834 u64 prev_dev_ext_end
= 0;
7838 * We don't have a dev_root because we mounted with ignorebadroots and
7839 * failed to load the root, so we want to skip the verification in this
7842 * However if the dev root is fine, but the tree itself is corrupted
7843 * we'd still fail to mount. This verification is only to make sure
7844 * writes can happen safely, so instead just bypass this check
7845 * completely in the case of IGNOREBADROOTS.
7847 if (btrfs_test_opt(fs_info
, IGNOREBADROOTS
))
7851 key
.type
= BTRFS_DEV_EXTENT_KEY
;
7854 path
= btrfs_alloc_path();
7858 path
->reada
= READA_FORWARD
;
7859 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
7863 if (path
->slots
[0] >= btrfs_header_nritems(path
->nodes
[0])) {
7864 ret
= btrfs_next_leaf(root
, path
);
7867 /* No dev extents at all? Not good */
7874 struct extent_buffer
*leaf
= path
->nodes
[0];
7875 struct btrfs_dev_extent
*dext
;
7876 int slot
= path
->slots
[0];
7878 u64 physical_offset
;
7882 btrfs_item_key_to_cpu(leaf
, &key
, slot
);
7883 if (key
.type
!= BTRFS_DEV_EXTENT_KEY
)
7885 devid
= key
.objectid
;
7886 physical_offset
= key
.offset
;
7888 dext
= btrfs_item_ptr(leaf
, slot
, struct btrfs_dev_extent
);
7889 chunk_offset
= btrfs_dev_extent_chunk_offset(leaf
, dext
);
7890 physical_len
= btrfs_dev_extent_length(leaf
, dext
);
7892 /* Check if this dev extent overlaps with the previous one */
7893 if (devid
== prev_devid
&& physical_offset
< prev_dev_ext_end
) {
7895 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7896 devid
, physical_offset
, prev_dev_ext_end
);
7901 ret
= verify_one_dev_extent(fs_info
, chunk_offset
, devid
,
7902 physical_offset
, physical_len
);
7906 prev_dev_ext_end
= physical_offset
+ physical_len
;
7908 ret
= btrfs_next_item(root
, path
);
7917 /* Ensure all chunks have corresponding dev extents */
7918 ret
= verify_chunk_dev_extent_mapping(fs_info
);
7920 btrfs_free_path(path
);
7925 * Check whether the given block group or device is pinned by any inode being
7926 * used as a swapfile.
7928 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info
*fs_info
, void *ptr
)
7930 struct btrfs_swapfile_pin
*sp
;
7931 struct rb_node
*node
;
7933 spin_lock(&fs_info
->swapfile_pins_lock
);
7934 node
= fs_info
->swapfile_pins
.rb_node
;
7936 sp
= rb_entry(node
, struct btrfs_swapfile_pin
, node
);
7938 node
= node
->rb_left
;
7939 else if (ptr
> sp
->ptr
)
7940 node
= node
->rb_right
;
7944 spin_unlock(&fs_info
->swapfile_pins_lock
);
7945 return node
!= NULL
;
7948 static int relocating_repair_kthread(void *data
)
7950 struct btrfs_block_group
*cache
= data
;
7951 struct btrfs_fs_info
*fs_info
= cache
->fs_info
;
7955 target
= cache
->start
;
7956 btrfs_put_block_group(cache
);
7958 sb_start_write(fs_info
->sb
);
7959 if (!btrfs_exclop_start(fs_info
, BTRFS_EXCLOP_BALANCE
)) {
7961 "zoned: skip relocating block group %llu to repair: EBUSY",
7963 sb_end_write(fs_info
->sb
);
7967 mutex_lock(&fs_info
->reclaim_bgs_lock
);
7969 /* Ensure block group still exists */
7970 cache
= btrfs_lookup_block_group(fs_info
, target
);
7974 if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR
, &cache
->runtime_flags
))
7977 ret
= btrfs_may_alloc_data_chunk(fs_info
, target
);
7982 "zoned: relocating block group %llu to repair IO failure",
7984 ret
= btrfs_relocate_chunk(fs_info
, target
);
7988 btrfs_put_block_group(cache
);
7989 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
7990 btrfs_exclop_finish(fs_info
);
7991 sb_end_write(fs_info
->sb
);
7996 bool btrfs_repair_one_zone(struct btrfs_fs_info
*fs_info
, u64 logical
)
7998 struct btrfs_block_group
*cache
;
8000 if (!btrfs_is_zoned(fs_info
))
8003 /* Do not attempt to repair in degraded state */
8004 if (btrfs_test_opt(fs_info
, DEGRADED
))
8007 cache
= btrfs_lookup_block_group(fs_info
, logical
);
8011 if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR
, &cache
->runtime_flags
)) {
8012 btrfs_put_block_group(cache
);
8016 kthread_run(relocating_repair_kthread
, cache
,
8017 "btrfs-relocating-repair");
8022 static void map_raid56_repair_block(struct btrfs_io_context
*bioc
,
8023 struct btrfs_io_stripe
*smap
,
8026 int data_stripes
= nr_bioc_data_stripes(bioc
);
8029 for (i
= 0; i
< data_stripes
; i
++) {
8030 u64 stripe_start
= bioc
->full_stripe_logical
+
8031 btrfs_stripe_nr_to_offset(i
);
8033 if (logical
>= stripe_start
&&
8034 logical
< stripe_start
+ BTRFS_STRIPE_LEN
)
8037 ASSERT(i
< data_stripes
);
8038 smap
->dev
= bioc
->stripes
[i
].dev
;
8039 smap
->physical
= bioc
->stripes
[i
].physical
+
8040 ((logical
- bioc
->full_stripe_logical
) &
8041 BTRFS_STRIPE_LEN_MASK
);
8045 * Map a repair write into a single device.
8047 * A repair write is triggered by read time repair or scrub, which would only
8048 * update the contents of a single device.
8049 * Not update any other mirrors nor go through RMW path.
8051 * Callers should ensure:
8053 * - Call btrfs_bio_counter_inc_blocked() first
8054 * - The range does not cross stripe boundary
8055 * - Has a valid @mirror_num passed in.
8057 int btrfs_map_repair_block(struct btrfs_fs_info
*fs_info
,
8058 struct btrfs_io_stripe
*smap
, u64 logical
,
8059 u32 length
, int mirror_num
)
8061 struct btrfs_io_context
*bioc
= NULL
;
8062 u64 map_length
= length
;
8063 int mirror_ret
= mirror_num
;
8066 ASSERT(mirror_num
> 0);
8068 ret
= btrfs_map_block(fs_info
, BTRFS_MAP_WRITE
, logical
, &map_length
,
8069 &bioc
, smap
, &mirror_ret
);
8073 /* The map range should not cross stripe boundary. */
8074 ASSERT(map_length
>= length
);
8076 /* Already mapped to single stripe. */
8080 /* Map the RAID56 multi-stripe writes to a single one. */
8081 if (bioc
->map_type
& BTRFS_BLOCK_GROUP_RAID56_MASK
) {
8082 map_raid56_repair_block(bioc
, smap
, logical
);
8086 ASSERT(mirror_num
<= bioc
->num_stripes
);
8087 smap
->dev
= bioc
->stripes
[mirror_num
- 1].dev
;
8088 smap
->physical
= bioc
->stripes
[mirror_num
- 1].physical
;
8090 btrfs_put_bioc(bioc
);