1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/mm.h>
9 #include <linux/slab.h>
10 #include <linux/blkdev.h>
11 #include <linux/ratelimit.h>
12 #include <linux/kthread.h>
13 #include <linux/raid/pq.h>
14 #include <linux/semaphore.h>
15 #include <linux/uuid.h>
16 #include <linux/list_sort.h>
17 #include <linux/namei.h>
20 #include "extent_map.h"
22 #include "transaction.h"
23 #include "print-tree.h"
26 #include "async-thread.h"
27 #include "check-integrity.h"
28 #include "rcu-string.h"
29 #include "dev-replace.h"
31 #include "tree-checker.h"
32 #include "space-info.h"
33 #include "block-group.h"
36 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
37 [BTRFS_RAID_RAID10] = {
40 .devs_max = 0, /* 0 == as many as possible */
42 .tolerated_failures = 1,
46 .raid_name = "raid10",
47 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
48 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
50 [BTRFS_RAID_RAID1] = {
55 .tolerated_failures = 1,
60 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
61 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
63 [BTRFS_RAID_RAID1C3] = {
68 .tolerated_failures = 2,
72 .raid_name = "raid1c3",
73 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
74 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
76 [BTRFS_RAID_RAID1C4] = {
81 .tolerated_failures = 3,
85 .raid_name = "raid1c4",
86 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
87 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
94 .tolerated_failures = 0,
99 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
102 [BTRFS_RAID_RAID0] = {
107 .tolerated_failures = 0,
111 .raid_name = "raid0",
112 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
115 [BTRFS_RAID_SINGLE] = {
120 .tolerated_failures = 0,
124 .raid_name = "single",
128 [BTRFS_RAID_RAID5] = {
133 .tolerated_failures = 1,
137 .raid_name = "raid5",
138 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
139 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
141 [BTRFS_RAID_RAID6] = {
146 .tolerated_failures = 2,
150 .raid_name = "raid6",
151 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
152 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
156 const char *btrfs_bg_type_to_raid_name(u64 flags)
158 const int index = btrfs_bg_flags_to_raid_index(flags);
160 if (index >= BTRFS_NR_RAID_TYPES)
163 return btrfs_raid_array[index].raid_name;
167 * Fill @buf with textual description of @bg_flags, no more than @size_buf
168 * bytes including terminating null byte.
170 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
175 u64 flags = bg_flags;
176 u32 size_bp = size_buf;
183 #define DESCRIBE_FLAG(flag, desc) \
185 if (flags & (flag)) { \
186 ret = snprintf(bp, size_bp, "%s|", (desc)); \
187 if (ret < 0 || ret >= size_bp) \
195 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
196 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
197 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
199 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
200 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
201 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
202 btrfs_raid_array[i].raid_name);
206 ret = snprintf(bp, size_bp, "0x%llx|", flags);
210 if (size_bp < size_buf)
211 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
214 * The text is trimmed, it's up to the caller to provide sufficiently
220 static int init_first_rw_device(struct btrfs_trans_handle *trans);
221 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
222 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
223 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
224 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
225 enum btrfs_map_op op,
226 u64 logical, u64 *length,
227 struct btrfs_bio **bbio_ret,
228 int mirror_num, int need_raid_map);
234 * There are several mutexes that protect manipulation of devices and low-level
235 * structures like chunks but not block groups, extents or files
237 * uuid_mutex (global lock)
238 * ------------------------
239 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
240 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
241 * device) or requested by the device= mount option
243 * the mutex can be very coarse and can cover long-running operations
245 * protects: updates to fs_devices counters like missing devices, rw devices,
246 * seeding, structure cloning, opening/closing devices at mount/umount time
248 * global::fs_devs - add, remove, updates to the global list
250 * does not protect: manipulation of the fs_devices::devices list in general
251 * but in mount context it could be used to exclude list modifications by eg.
254 * btrfs_device::name - renames (write side), read is RCU
256 * fs_devices::device_list_mutex (per-fs, with RCU)
257 * ------------------------------------------------
258 * protects updates to fs_devices::devices, ie. adding and deleting
260 * simple list traversal with read-only actions can be done with RCU protection
262 * may be used to exclude some operations from running concurrently without any
263 * modifications to the list (see write_all_supers)
265 * Is not required at mount and close times, because our device list is
266 * protected by the uuid_mutex at that point.
270 * protects balance structures (status, state) and context accessed from
271 * several places (internally, ioctl)
275 * protects chunks, adding or removing during allocation, trim or when a new
276 * device is added/removed. Additionally it also protects post_commit_list of
277 * individual devices, since they can be added to the transaction's
278 * post_commit_list only with chunk_mutex held.
282 * a big lock that is held by the cleaner thread and prevents running subvolume
283 * cleaning together with relocation or delayed iputs
295 * Exclusive operations
296 * ====================
298 * Maintains the exclusivity of the following operations that apply to the
299 * whole filesystem and cannot run in parallel.
304 * - Device replace (*)
307 * The device operations (as above) can be in one of the following states:
313 * Only device operations marked with (*) can go into the Paused state for the
316 * - ioctl (only Balance can be Paused through ioctl)
317 * - filesystem remounted as read-only
318 * - filesystem unmounted and mounted as read-only
319 * - system power-cycle and filesystem mounted as read-only
320 * - filesystem or device errors leading to forced read-only
322 * The status of exclusive operation is set and cleared atomically.
323 * During the course of Paused state, fs_info::exclusive_operation remains set.
324 * A device operation in Paused or Running state can be canceled or resumed
325 * either by ioctl (Balance only) or when remounted as read-write.
326 * The exclusive status is cleared when the device operation is canceled or
330 DEFINE_MUTEX(uuid_mutex);
331 static LIST_HEAD(fs_uuids);
332 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
338 * alloc_fs_devices - allocate struct btrfs_fs_devices
339 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
340 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
342 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
343 * The returned struct is not linked onto any lists and can be destroyed with
344 * kfree() right away.
346 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
347 const u8 *metadata_fsid)
349 struct btrfs_fs_devices *fs_devs;
351 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
353 return ERR_PTR(-ENOMEM);
355 mutex_init(&fs_devs->device_list_mutex);
357 INIT_LIST_HEAD(&fs_devs->devices);
358 INIT_LIST_HEAD(&fs_devs->alloc_list);
359 INIT_LIST_HEAD(&fs_devs->fs_list);
360 INIT_LIST_HEAD(&fs_devs->seed_list);
362 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
365 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
367 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
372 void btrfs_free_device(struct btrfs_device *device)
374 WARN_ON(!list_empty(&device->post_commit_list));
375 rcu_string_free(device->name);
376 extent_io_tree_release(&device->alloc_state);
377 bio_put(device->flush_bio);
381 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
383 struct btrfs_device *device;
385 WARN_ON(fs_devices->opened);
386 while (!list_empty(&fs_devices->devices)) {
387 device = list_entry(fs_devices->devices.next,
388 struct btrfs_device, dev_list);
389 list_del(&device->dev_list);
390 btrfs_free_device(device);
395 void __exit btrfs_cleanup_fs_uuids(void)
397 struct btrfs_fs_devices *fs_devices;
399 while (!list_empty(&fs_uuids)) {
400 fs_devices = list_entry(fs_uuids.next,
401 struct btrfs_fs_devices, fs_list);
402 list_del(&fs_devices->fs_list);
403 free_fs_devices(fs_devices);
408 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
409 * Returned struct is not linked onto any lists and must be destroyed using
412 static struct btrfs_device *__alloc_device(struct btrfs_fs_info *fs_info)
414 struct btrfs_device *dev;
416 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
418 return ERR_PTR(-ENOMEM);
421 * Preallocate a bio that's always going to be used for flushing device
422 * barriers and matches the device lifespan
424 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
425 if (!dev->flush_bio) {
427 return ERR_PTR(-ENOMEM);
430 INIT_LIST_HEAD(&dev->dev_list);
431 INIT_LIST_HEAD(&dev->dev_alloc_list);
432 INIT_LIST_HEAD(&dev->post_commit_list);
434 atomic_set(&dev->reada_in_flight, 0);
435 atomic_set(&dev->dev_stats_ccnt, 0);
436 btrfs_device_data_ordered_init(dev);
437 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
438 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
439 extent_io_tree_init(fs_info, &dev->alloc_state,
440 IO_TREE_DEVICE_ALLOC_STATE, NULL);
445 static noinline struct btrfs_fs_devices *find_fsid(
446 const u8 *fsid, const u8 *metadata_fsid)
448 struct btrfs_fs_devices *fs_devices;
452 /* Handle non-split brain cases */
453 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
455 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
456 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
457 BTRFS_FSID_SIZE) == 0)
460 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
467 static struct btrfs_fs_devices *find_fsid_with_metadata_uuid(
468 struct btrfs_super_block *disk_super)
471 struct btrfs_fs_devices *fs_devices;
474 * Handle scanned device having completed its fsid change but
475 * belonging to a fs_devices that was created by first scanning
476 * a device which didn't have its fsid/metadata_uuid changed
477 * at all and the CHANGING_FSID_V2 flag set.
479 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
480 if (fs_devices->fsid_change &&
481 memcmp(disk_super->metadata_uuid, fs_devices->fsid,
482 BTRFS_FSID_SIZE) == 0 &&
483 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
484 BTRFS_FSID_SIZE) == 0) {
489 * Handle scanned device having completed its fsid change but
490 * belonging to a fs_devices that was created by a device that
491 * has an outdated pair of fsid/metadata_uuid and
492 * CHANGING_FSID_V2 flag set.
494 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
495 if (fs_devices->fsid_change &&
496 memcmp(fs_devices->metadata_uuid,
497 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
498 memcmp(disk_super->metadata_uuid, fs_devices->metadata_uuid,
499 BTRFS_FSID_SIZE) == 0) {
504 return find_fsid(disk_super->fsid, disk_super->metadata_uuid);
509 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
510 int flush, struct block_device **bdev,
511 struct btrfs_super_block **disk_super)
515 *bdev = blkdev_get_by_path(device_path, flags, holder);
518 ret = PTR_ERR(*bdev);
523 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
524 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
526 blkdev_put(*bdev, flags);
529 invalidate_bdev(*bdev);
530 *disk_super = btrfs_read_dev_super(*bdev);
531 if (IS_ERR(*disk_super)) {
532 ret = PTR_ERR(*disk_super);
533 blkdev_put(*bdev, flags);
545 * Check if the device in the path matches the device in the given struct device.
548 * true If it is the same device.
549 * false If it is not the same device or on error.
551 static bool device_matched(const struct btrfs_device *device, const char *path)
554 struct block_device *bdev_old;
555 struct block_device *bdev_new;
558 * If we are looking for a device with the matching dev_t, then skip
559 * device without a name (a missing device).
564 device_name = kzalloc(BTRFS_PATH_NAME_MAX, GFP_KERNEL);
569 scnprintf(device_name, BTRFS_PATH_NAME_MAX, "%s", rcu_str_deref(device->name));
572 bdev_old = lookup_bdev(device_name);
574 if (IS_ERR(bdev_old))
577 bdev_new = lookup_bdev(path);
578 if (IS_ERR(bdev_new))
581 if (bdev_old == bdev_new)
588 * Search and remove all stale (devices which are not mounted) devices.
589 * When both inputs are NULL, it will search and release all stale devices.
590 * path: Optional. When provided will it release all unmounted devices
591 * matching this path only.
592 * skip_dev: Optional. Will skip this device when searching for the stale
594 * Return: 0 for success or if @path is NULL.
595 * -EBUSY if @path is a mounted device.
596 * -ENOENT if @path does not match any device in the list.
598 static int btrfs_free_stale_devices(const char *path,
599 struct btrfs_device *skip_device)
601 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
602 struct btrfs_device *device, *tmp_device;
605 lockdep_assert_held(&uuid_mutex);
610 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
612 mutex_lock(&fs_devices->device_list_mutex);
613 list_for_each_entry_safe(device, tmp_device,
614 &fs_devices->devices, dev_list) {
615 if (skip_device && skip_device == device)
617 if (path && !device_matched(device, path))
619 if (fs_devices->opened) {
620 /* for an already deleted device return 0 */
621 if (path && ret != 0)
626 /* delete the stale device */
627 fs_devices->num_devices--;
628 list_del(&device->dev_list);
629 btrfs_free_device(device);
633 mutex_unlock(&fs_devices->device_list_mutex);
635 if (fs_devices->num_devices == 0) {
636 btrfs_sysfs_remove_fsid(fs_devices);
637 list_del(&fs_devices->fs_list);
638 free_fs_devices(fs_devices);
646 * This is only used on mount, and we are protected from competing things
647 * messing with our fs_devices by the uuid_mutex, thus we do not need the
648 * fs_devices->device_list_mutex here.
650 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
651 struct btrfs_device *device, fmode_t flags,
654 struct request_queue *q;
655 struct block_device *bdev;
656 struct btrfs_super_block *disk_super;
665 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
670 devid = btrfs_stack_device_id(&disk_super->dev_item);
671 if (devid != device->devid)
672 goto error_free_page;
674 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
675 goto error_free_page;
677 device->generation = btrfs_super_generation(disk_super);
679 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
680 if (btrfs_super_incompat_flags(disk_super) &
681 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
683 "BTRFS: Invalid seeding and uuid-changed device detected\n");
684 goto error_free_page;
687 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
688 fs_devices->seeding = true;
690 if (bdev_read_only(bdev))
691 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
693 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
696 q = bdev_get_queue(bdev);
697 if (!blk_queue_nonrot(q))
698 fs_devices->rotating = true;
701 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
702 device->mode = flags;
704 fs_devices->open_devices++;
705 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
706 device->devid != BTRFS_DEV_REPLACE_DEVID) {
707 fs_devices->rw_devices++;
708 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
710 btrfs_release_disk_super(disk_super);
715 btrfs_release_disk_super(disk_super);
716 blkdev_put(bdev, flags);
721 u8 *btrfs_sb_fsid_ptr(struct btrfs_super_block *sb)
723 bool has_metadata_uuid = (btrfs_super_incompat_flags(sb) &
724 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
726 return has_metadata_uuid ? sb->metadata_uuid : sb->fsid;
730 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
731 * being created with a disk that has already completed its fsid change. Such
732 * disk can belong to an fs which has its FSID changed or to one which doesn't.
733 * Handle both cases here.
735 static struct btrfs_fs_devices *find_fsid_inprogress(
736 struct btrfs_super_block *disk_super)
738 struct btrfs_fs_devices *fs_devices;
740 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
741 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
742 BTRFS_FSID_SIZE) != 0 &&
743 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
744 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
749 return find_fsid(disk_super->fsid, NULL);
753 static struct btrfs_fs_devices *find_fsid_changed(
754 struct btrfs_super_block *disk_super)
756 struct btrfs_fs_devices *fs_devices;
759 * Handles the case where scanned device is part of an fs that had
760 * multiple successful changes of FSID but curently device didn't
761 * observe it. Meaning our fsid will be different than theirs. We need
762 * to handle two subcases :
763 * 1 - The fs still continues to have different METADATA/FSID uuids.
764 * 2 - The fs is switched back to its original FSID (METADATA/FSID
767 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
769 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
770 BTRFS_FSID_SIZE) != 0 &&
771 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
772 BTRFS_FSID_SIZE) == 0 &&
773 memcmp(fs_devices->fsid, disk_super->fsid,
774 BTRFS_FSID_SIZE) != 0)
777 /* Unchanged UUIDs */
778 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
779 BTRFS_FSID_SIZE) == 0 &&
780 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
781 BTRFS_FSID_SIZE) == 0)
788 static struct btrfs_fs_devices *find_fsid_reverted_metadata(
789 struct btrfs_super_block *disk_super)
791 struct btrfs_fs_devices *fs_devices;
794 * Handle the case where the scanned device is part of an fs whose last
795 * metadata UUID change reverted it to the original FSID. At the same
796 * time * fs_devices was first created by another constitutent device
797 * which didn't fully observe the operation. This results in an
798 * btrfs_fs_devices created with metadata/fsid different AND
799 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
800 * fs_devices equal to the FSID of the disk.
802 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
803 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
804 BTRFS_FSID_SIZE) != 0 &&
805 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
806 BTRFS_FSID_SIZE) == 0 &&
807 fs_devices->fsid_change)
814 * Add new device to list of registered devices
817 * device pointer which was just added or updated when successful
818 * error pointer when failed
820 static noinline struct btrfs_device *device_list_add(const char *path,
821 struct btrfs_super_block *disk_super,
822 bool *new_device_added)
824 struct btrfs_device *device;
825 struct btrfs_fs_devices *fs_devices = NULL;
826 struct rcu_string *name;
827 u64 found_transid = btrfs_super_generation(disk_super);
828 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
829 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
830 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
831 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
832 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
834 if (fsid_change_in_progress) {
835 if (!has_metadata_uuid)
836 fs_devices = find_fsid_inprogress(disk_super);
838 fs_devices = find_fsid_changed(disk_super);
839 } else if (has_metadata_uuid) {
840 fs_devices = find_fsid_with_metadata_uuid(disk_super);
842 fs_devices = find_fsid_reverted_metadata(disk_super);
844 fs_devices = find_fsid(disk_super->fsid, NULL);
849 if (has_metadata_uuid)
850 fs_devices = alloc_fs_devices(disk_super->fsid,
851 disk_super->metadata_uuid);
853 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
855 if (IS_ERR(fs_devices))
856 return ERR_CAST(fs_devices);
858 fs_devices->fsid_change = fsid_change_in_progress;
860 mutex_lock(&fs_devices->device_list_mutex);
861 list_add(&fs_devices->fs_list, &fs_uuids);
865 mutex_lock(&fs_devices->device_list_mutex);
866 device = btrfs_find_device(fs_devices, devid,
867 disk_super->dev_item.uuid, NULL, false);
870 * If this disk has been pulled into an fs devices created by
871 * a device which had the CHANGING_FSID_V2 flag then replace the
872 * metadata_uuid/fsid values of the fs_devices.
874 if (fs_devices->fsid_change &&
875 found_transid > fs_devices->latest_generation) {
876 memcpy(fs_devices->fsid, disk_super->fsid,
879 if (has_metadata_uuid)
880 memcpy(fs_devices->metadata_uuid,
881 disk_super->metadata_uuid,
884 memcpy(fs_devices->metadata_uuid,
885 disk_super->fsid, BTRFS_FSID_SIZE);
887 fs_devices->fsid_change = false;
892 if (fs_devices->opened) {
893 mutex_unlock(&fs_devices->device_list_mutex);
894 return ERR_PTR(-EBUSY);
897 device = btrfs_alloc_device(NULL, &devid,
898 disk_super->dev_item.uuid);
899 if (IS_ERR(device)) {
900 mutex_unlock(&fs_devices->device_list_mutex);
901 /* we can safely leave the fs_devices entry around */
905 name = rcu_string_strdup(path, GFP_NOFS);
907 btrfs_free_device(device);
908 mutex_unlock(&fs_devices->device_list_mutex);
909 return ERR_PTR(-ENOMEM);
911 rcu_assign_pointer(device->name, name);
913 list_add_rcu(&device->dev_list, &fs_devices->devices);
914 fs_devices->num_devices++;
916 device->fs_devices = fs_devices;
917 *new_device_added = true;
919 if (disk_super->label[0])
921 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
922 disk_super->label, devid, found_transid, path,
923 current->comm, task_pid_nr(current));
926 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
927 disk_super->fsid, devid, found_transid, path,
928 current->comm, task_pid_nr(current));
930 } else if (!device->name || strcmp(device->name->str, path)) {
932 * When FS is already mounted.
933 * 1. If you are here and if the device->name is NULL that
934 * means this device was missing at time of FS mount.
935 * 2. If you are here and if the device->name is different
936 * from 'path' that means either
937 * a. The same device disappeared and reappeared with
939 * b. The missing-disk-which-was-replaced, has
942 * We must allow 1 and 2a above. But 2b would be a spurious
945 * Further in case of 1 and 2a above, the disk at 'path'
946 * would have missed some transaction when it was away and
947 * in case of 2a the stale bdev has to be updated as well.
948 * 2b must not be allowed at all time.
952 * For now, we do allow update to btrfs_fs_device through the
953 * btrfs dev scan cli after FS has been mounted. We're still
954 * tracking a problem where systems fail mount by subvolume id
955 * when we reject replacement on a mounted FS.
957 if (!fs_devices->opened && found_transid < device->generation) {
959 * That is if the FS is _not_ mounted and if you
960 * are here, that means there is more than one
961 * disk with same uuid and devid.We keep the one
962 * with larger generation number or the last-in if
963 * generation are equal.
965 mutex_unlock(&fs_devices->device_list_mutex);
966 return ERR_PTR(-EEXIST);
970 * We are going to replace the device path for a given devid,
971 * make sure it's the same device if the device is mounted
974 struct block_device *path_bdev;
976 path_bdev = lookup_bdev(path);
977 if (IS_ERR(path_bdev)) {
978 mutex_unlock(&fs_devices->device_list_mutex);
979 return ERR_CAST(path_bdev);
982 if (device->bdev != path_bdev) {
984 mutex_unlock(&fs_devices->device_list_mutex);
986 * device->fs_info may not be reliable here, so
987 * pass in a NULL instead. This avoids a
988 * possible use-after-free when the fs_info and
989 * fs_info->sb are already torn down.
991 btrfs_warn_in_rcu(NULL,
992 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
993 path, devid, found_transid,
995 task_pid_nr(current));
996 return ERR_PTR(-EEXIST);
999 btrfs_info_in_rcu(device->fs_info,
1000 "devid %llu device path %s changed to %s scanned by %s (%d)",
1001 devid, rcu_str_deref(device->name),
1002 path, current->comm,
1003 task_pid_nr(current));
1006 name = rcu_string_strdup(path, GFP_NOFS);
1008 mutex_unlock(&fs_devices->device_list_mutex);
1009 return ERR_PTR(-ENOMEM);
1011 rcu_string_free(device->name);
1012 rcu_assign_pointer(device->name, name);
1013 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1014 fs_devices->missing_devices--;
1015 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1020 * Unmount does not free the btrfs_device struct but would zero
1021 * generation along with most of the other members. So just update
1022 * it back. We need it to pick the disk with largest generation
1025 if (!fs_devices->opened) {
1026 device->generation = found_transid;
1027 fs_devices->latest_generation = max_t(u64, found_transid,
1028 fs_devices->latest_generation);
1031 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
1033 mutex_unlock(&fs_devices->device_list_mutex);
1037 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1039 struct btrfs_fs_devices *fs_devices;
1040 struct btrfs_device *device;
1041 struct btrfs_device *orig_dev;
1044 lockdep_assert_held(&uuid_mutex);
1046 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1047 if (IS_ERR(fs_devices))
1050 fs_devices->total_devices = orig->total_devices;
1052 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1053 struct rcu_string *name;
1055 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1057 if (IS_ERR(device)) {
1058 ret = PTR_ERR(device);
1063 * This is ok to do without rcu read locked because we hold the
1064 * uuid mutex so nothing we touch in here is going to disappear.
1066 if (orig_dev->name) {
1067 name = rcu_string_strdup(orig_dev->name->str,
1070 btrfs_free_device(device);
1074 rcu_assign_pointer(device->name, name);
1077 list_add(&device->dev_list, &fs_devices->devices);
1078 device->fs_devices = fs_devices;
1079 fs_devices->num_devices++;
1083 free_fs_devices(fs_devices);
1084 return ERR_PTR(ret);
1087 static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
1088 int step, struct btrfs_device **latest_dev)
1090 struct btrfs_device *device, *next;
1092 /* This is the initialized path, it is safe to release the devices. */
1093 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1094 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
1095 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1096 &device->dev_state) &&
1097 !test_bit(BTRFS_DEV_STATE_MISSING,
1098 &device->dev_state) &&
1100 device->generation > (*latest_dev)->generation)) {
1101 *latest_dev = device;
1107 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1108 * in btrfs_init_dev_replace() so just continue.
1110 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1114 blkdev_put(device->bdev, device->mode);
1115 device->bdev = NULL;
1116 fs_devices->open_devices--;
1118 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1119 list_del_init(&device->dev_alloc_list);
1120 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1121 fs_devices->rw_devices--;
1123 list_del_init(&device->dev_list);
1124 fs_devices->num_devices--;
1125 btrfs_free_device(device);
1131 * After we have read the system tree and know devids belonging to this
1132 * filesystem, remove the device which does not belong there.
1134 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1136 struct btrfs_device *latest_dev = NULL;
1137 struct btrfs_fs_devices *seed_dev;
1139 mutex_lock(&uuid_mutex);
1140 __btrfs_free_extra_devids(fs_devices, step, &latest_dev);
1142 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1143 __btrfs_free_extra_devids(seed_dev, step, &latest_dev);
1145 fs_devices->latest_bdev = latest_dev->bdev;
1147 mutex_unlock(&uuid_mutex);
1150 static void btrfs_close_bdev(struct btrfs_device *device)
1155 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1156 sync_blockdev(device->bdev);
1157 invalidate_bdev(device->bdev);
1160 blkdev_put(device->bdev, device->mode);
1163 static void btrfs_close_one_device(struct btrfs_device *device)
1165 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1167 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1168 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1169 list_del_init(&device->dev_alloc_list);
1170 fs_devices->rw_devices--;
1173 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1174 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
1176 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1177 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1178 fs_devices->missing_devices--;
1181 btrfs_close_bdev(device);
1183 fs_devices->open_devices--;
1184 device->bdev = NULL;
1186 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1188 device->fs_info = NULL;
1189 atomic_set(&device->dev_stats_ccnt, 0);
1190 extent_io_tree_release(&device->alloc_state);
1193 * Reset the flush error record. We might have a transient flush error
1194 * in this mount, and if so we aborted the current transaction and set
1195 * the fs to an error state, guaranteeing no super blocks can be further
1196 * committed. However that error might be transient and if we unmount the
1197 * filesystem and mount it again, we should allow the mount to succeed
1198 * (btrfs_check_rw_degradable() should not fail) - if after mounting the
1199 * filesystem again we still get flush errors, then we will again abort
1200 * any transaction and set the error state, guaranteeing no commits of
1201 * unsafe super blocks.
1203 device->last_flush_error = 0;
1205 /* Verify the device is back in a pristine state */
1206 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1207 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1208 ASSERT(list_empty(&device->dev_alloc_list));
1209 ASSERT(list_empty(&device->post_commit_list));
1210 ASSERT(atomic_read(&device->reada_in_flight) == 0);
1213 static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
1215 struct btrfs_device *device, *tmp;
1217 lockdep_assert_held(&uuid_mutex);
1219 if (--fs_devices->opened > 0)
1222 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
1223 btrfs_close_one_device(device);
1225 WARN_ON(fs_devices->open_devices);
1226 WARN_ON(fs_devices->rw_devices);
1227 fs_devices->opened = 0;
1228 fs_devices->seeding = false;
1229 fs_devices->fs_info = NULL;
1232 void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1235 struct btrfs_fs_devices *tmp;
1237 mutex_lock(&uuid_mutex);
1238 close_fs_devices(fs_devices);
1239 if (!fs_devices->opened) {
1240 list_splice_init(&fs_devices->seed_list, &list);
1243 * If the struct btrfs_fs_devices is not assembled with any
1244 * other device, it can be re-initialized during the next mount
1245 * without the needing device-scan step. Therefore, it can be
1248 if (fs_devices->num_devices == 1) {
1249 list_del(&fs_devices->fs_list);
1250 free_fs_devices(fs_devices);
1255 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
1256 close_fs_devices(fs_devices);
1257 list_del(&fs_devices->seed_list);
1258 free_fs_devices(fs_devices);
1260 mutex_unlock(&uuid_mutex);
1263 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1264 fmode_t flags, void *holder)
1266 struct btrfs_device *device;
1267 struct btrfs_device *latest_dev = NULL;
1268 struct btrfs_device *tmp_device;
1271 flags |= FMODE_EXCL;
1273 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1277 ret2 = btrfs_open_one_device(fs_devices, device, flags, holder);
1279 (!latest_dev || device->generation > latest_dev->generation)) {
1280 latest_dev = device;
1281 } else if (ret2 == -ENODATA) {
1282 fs_devices->num_devices--;
1283 list_del(&device->dev_list);
1284 btrfs_free_device(device);
1286 if (ret == 0 && ret2 != 0)
1290 if (fs_devices->open_devices == 0) {
1296 fs_devices->opened = 1;
1297 fs_devices->latest_bdev = latest_dev->bdev;
1298 fs_devices->total_rw_bytes = 0;
1299 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1304 static int devid_cmp(void *priv, const struct list_head *a,
1305 const struct list_head *b)
1307 struct btrfs_device *dev1, *dev2;
1309 dev1 = list_entry(a, struct btrfs_device, dev_list);
1310 dev2 = list_entry(b, struct btrfs_device, dev_list);
1312 if (dev1->devid < dev2->devid)
1314 else if (dev1->devid > dev2->devid)
1319 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1320 fmode_t flags, void *holder)
1324 lockdep_assert_held(&uuid_mutex);
1326 * The device_list_mutex cannot be taken here in case opening the
1327 * underlying device takes further locks like bd_mutex.
1329 * We also don't need the lock here as this is called during mount and
1330 * exclusion is provided by uuid_mutex
1333 if (fs_devices->opened) {
1334 fs_devices->opened++;
1337 list_sort(NULL, &fs_devices->devices, devid_cmp);
1338 ret = open_fs_devices(fs_devices, flags, holder);
1344 void btrfs_release_disk_super(struct btrfs_super_block *super)
1346 struct page *page = virt_to_page(super);
1351 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1354 struct btrfs_super_block *disk_super;
1359 /* make sure our super fits in the device */
1360 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1361 return ERR_PTR(-EINVAL);
1363 /* make sure our super fits in the page */
1364 if (sizeof(*disk_super) > PAGE_SIZE)
1365 return ERR_PTR(-EINVAL);
1367 /* make sure our super doesn't straddle pages on disk */
1368 index = bytenr >> PAGE_SHIFT;
1369 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1370 return ERR_PTR(-EINVAL);
1372 /* pull in the page with our super */
1373 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1376 return ERR_CAST(page);
1378 p = page_address(page);
1380 /* align our pointer to the offset of the super block */
1381 disk_super = p + offset_in_page(bytenr);
1383 if (btrfs_super_bytenr(disk_super) != bytenr ||
1384 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1385 btrfs_release_disk_super(p);
1386 return ERR_PTR(-EINVAL);
1389 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1390 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1395 int btrfs_forget_devices(const char *path)
1399 mutex_lock(&uuid_mutex);
1400 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1401 mutex_unlock(&uuid_mutex);
1407 * Look for a btrfs signature on a device. This may be called out of the mount path
1408 * and we are not allowed to call set_blocksize during the scan. The superblock
1409 * is read via pagecache
1411 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1414 struct btrfs_super_block *disk_super;
1415 bool new_device_added = false;
1416 struct btrfs_device *device = NULL;
1417 struct block_device *bdev;
1420 lockdep_assert_held(&uuid_mutex);
1423 * we would like to check all the supers, but that would make
1424 * a btrfs mount succeed after a mkfs from a different FS.
1425 * So, we need to add a special mount option to scan for
1426 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1428 bytenr = btrfs_sb_offset(0);
1431 * Avoid using flag |= FMODE_EXCL here, as the systemd-udev may
1432 * initiate the device scan which may race with the user's mount
1433 * or mkfs command, resulting in failure.
1434 * Since the device scan is solely for reading purposes, there is
1435 * no need for FMODE_EXCL. Additionally, the devices are read again
1436 * during the mount process. It is ok to get some inconsistent
1437 * values temporarily, as the device paths of the fsid are the only
1438 * required information for assembling the volume.
1440 bdev = blkdev_get_by_path(path, flags, holder);
1442 return ERR_CAST(bdev);
1444 disk_super = btrfs_read_disk_super(bdev, bytenr);
1445 if (IS_ERR(disk_super)) {
1446 device = ERR_CAST(disk_super);
1447 goto error_bdev_put;
1450 device = device_list_add(path, disk_super, &new_device_added);
1451 if (!IS_ERR(device)) {
1452 if (new_device_added)
1453 btrfs_free_stale_devices(path, device);
1456 btrfs_release_disk_super(disk_super);
1459 blkdev_put(bdev, flags);
1465 * Try to find a chunk that intersects [start, start + len] range and when one
1466 * such is found, record the end of it in *start
1468 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1471 u64 physical_start, physical_end;
1473 lockdep_assert_held(&device->fs_info->chunk_mutex);
1475 if (!find_first_extent_bit(&device->alloc_state, *start,
1476 &physical_start, &physical_end,
1477 CHUNK_ALLOCATED, NULL)) {
1479 if (in_range(physical_start, *start, len) ||
1480 in_range(*start, physical_start,
1481 physical_end + 1 - physical_start)) {
1482 *start = physical_end + 1;
1489 static u64 dev_extent_search_start(struct btrfs_device *device, u64 start)
1491 switch (device->fs_devices->chunk_alloc_policy) {
1492 case BTRFS_CHUNK_ALLOC_REGULAR:
1494 * We don't want to overwrite the superblock on the drive nor
1495 * any area used by the boot loader (grub for example), so we
1496 * make sure to start at an offset of at least 1MB.
1498 return max_t(u64, start, SZ_1M);
1505 * dev_extent_hole_check - check if specified hole is suitable for allocation
1506 * @device: the device which we have the hole
1507 * @hole_start: starting position of the hole
1508 * @hole_size: the size of the hole
1509 * @num_bytes: the size of the free space that we need
1511 * This function may modify @hole_start and @hole_end to reflect the suitable
1512 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1514 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1515 u64 *hole_size, u64 num_bytes)
1517 bool changed = false;
1518 u64 hole_end = *hole_start + *hole_size;
1521 * Check before we set max_hole_start, otherwise we could end up
1522 * sending back this offset anyway.
1524 if (contains_pending_extent(device, hole_start, *hole_size)) {
1525 if (hole_end >= *hole_start)
1526 *hole_size = hole_end - *hole_start;
1532 switch (device->fs_devices->chunk_alloc_policy) {
1533 case BTRFS_CHUNK_ALLOC_REGULAR:
1534 /* No extra check */
1544 * find_free_dev_extent_start - find free space in the specified device
1545 * @device: the device which we search the free space in
1546 * @num_bytes: the size of the free space that we need
1547 * @search_start: the position from which to begin the search
1548 * @start: store the start of the free space.
1549 * @len: the size of the free space. that we find, or the size
1550 * of the max free space if we don't find suitable free space
1552 * this uses a pretty simple search, the expectation is that it is
1553 * called very infrequently and that a given device has a small number
1556 * @start is used to store the start of the free space if we find. But if we
1557 * don't find suitable free space, it will be used to store the start position
1558 * of the max free space.
1560 * @len is used to store the size of the free space that we find.
1561 * But if we don't find suitable free space, it is used to store the size of
1562 * the max free space.
1564 * NOTE: This function will search *commit* root of device tree, and does extra
1565 * check to ensure dev extents are not double allocated.
1566 * This makes the function safe to allocate dev extents but may not report
1567 * correct usable device space, as device extent freed in current transaction
1568 * is not reported as avaiable.
1570 static int find_free_dev_extent_start(struct btrfs_device *device,
1571 u64 num_bytes, u64 search_start, u64 *start,
1574 struct btrfs_fs_info *fs_info = device->fs_info;
1575 struct btrfs_root *root = fs_info->dev_root;
1576 struct btrfs_key key;
1577 struct btrfs_dev_extent *dev_extent;
1578 struct btrfs_path *path;
1583 u64 search_end = device->total_bytes;
1586 struct extent_buffer *l;
1588 search_start = dev_extent_search_start(device, search_start);
1590 path = btrfs_alloc_path();
1594 max_hole_start = search_start;
1598 if (search_start >= search_end ||
1599 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1604 path->reada = READA_FORWARD;
1605 path->search_commit_root = 1;
1606 path->skip_locking = 1;
1608 key.objectid = device->devid;
1609 key.offset = search_start;
1610 key.type = BTRFS_DEV_EXTENT_KEY;
1612 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1616 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1621 while (search_start < search_end) {
1623 slot = path->slots[0];
1624 if (slot >= btrfs_header_nritems(l)) {
1625 ret = btrfs_next_leaf(root, path);
1633 btrfs_item_key_to_cpu(l, &key, slot);
1635 if (key.objectid < device->devid)
1638 if (key.objectid > device->devid)
1641 if (key.type != BTRFS_DEV_EXTENT_KEY)
1644 if (key.offset > search_end)
1647 if (key.offset > search_start) {
1648 hole_size = key.offset - search_start;
1649 dev_extent_hole_check(device, &search_start, &hole_size,
1652 if (hole_size > max_hole_size) {
1653 max_hole_start = search_start;
1654 max_hole_size = hole_size;
1658 * If this free space is greater than which we need,
1659 * it must be the max free space that we have found
1660 * until now, so max_hole_start must point to the start
1661 * of this free space and the length of this free space
1662 * is stored in max_hole_size. Thus, we return
1663 * max_hole_start and max_hole_size and go back to the
1666 if (hole_size >= num_bytes) {
1672 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1673 extent_end = key.offset + btrfs_dev_extent_length(l,
1675 if (extent_end > search_start)
1676 search_start = extent_end;
1683 * At this point, search_start should be the end of
1684 * allocated dev extents, and when shrinking the device,
1685 * search_end may be smaller than search_start.
1687 if (search_end > search_start) {
1688 hole_size = search_end - search_start;
1689 if (dev_extent_hole_check(device, &search_start, &hole_size,
1691 btrfs_release_path(path);
1695 if (hole_size > max_hole_size) {
1696 max_hole_start = search_start;
1697 max_hole_size = hole_size;
1702 if (max_hole_size < num_bytes)
1707 ASSERT(max_hole_start + max_hole_size <= search_end);
1709 btrfs_free_path(path);
1710 *start = max_hole_start;
1712 *len = max_hole_size;
1716 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1717 u64 *start, u64 *len)
1719 /* FIXME use last free of some kind */
1720 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1723 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1724 struct btrfs_device *device,
1725 u64 start, u64 *dev_extent_len)
1727 struct btrfs_fs_info *fs_info = device->fs_info;
1728 struct btrfs_root *root = fs_info->dev_root;
1730 struct btrfs_path *path;
1731 struct btrfs_key key;
1732 struct btrfs_key found_key;
1733 struct extent_buffer *leaf = NULL;
1734 struct btrfs_dev_extent *extent = NULL;
1736 path = btrfs_alloc_path();
1740 key.objectid = device->devid;
1742 key.type = BTRFS_DEV_EXTENT_KEY;
1744 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1746 ret = btrfs_previous_item(root, path, key.objectid,
1747 BTRFS_DEV_EXTENT_KEY);
1750 leaf = path->nodes[0];
1751 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1752 extent = btrfs_item_ptr(leaf, path->slots[0],
1753 struct btrfs_dev_extent);
1754 BUG_ON(found_key.offset > start || found_key.offset +
1755 btrfs_dev_extent_length(leaf, extent) < start);
1757 btrfs_release_path(path);
1759 } else if (ret == 0) {
1760 leaf = path->nodes[0];
1761 extent = btrfs_item_ptr(leaf, path->slots[0],
1762 struct btrfs_dev_extent);
1764 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1768 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1770 ret = btrfs_del_item(trans, root, path);
1772 btrfs_handle_fs_error(fs_info, ret,
1773 "Failed to remove dev extent item");
1775 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1778 btrfs_free_path(path);
1782 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1783 struct btrfs_device *device,
1784 u64 chunk_offset, u64 start, u64 num_bytes)
1787 struct btrfs_path *path;
1788 struct btrfs_fs_info *fs_info = device->fs_info;
1789 struct btrfs_root *root = fs_info->dev_root;
1790 struct btrfs_dev_extent *extent;
1791 struct extent_buffer *leaf;
1792 struct btrfs_key key;
1794 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1795 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1796 path = btrfs_alloc_path();
1800 key.objectid = device->devid;
1802 key.type = BTRFS_DEV_EXTENT_KEY;
1803 ret = btrfs_insert_empty_item(trans, root, path, &key,
1808 leaf = path->nodes[0];
1809 extent = btrfs_item_ptr(leaf, path->slots[0],
1810 struct btrfs_dev_extent);
1811 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1812 BTRFS_CHUNK_TREE_OBJECTID);
1813 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1814 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1815 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1817 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1818 btrfs_mark_buffer_dirty(leaf);
1820 btrfs_free_path(path);
1824 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1826 struct extent_map_tree *em_tree;
1827 struct extent_map *em;
1831 em_tree = &fs_info->mapping_tree;
1832 read_lock(&em_tree->lock);
1833 n = rb_last(&em_tree->map.rb_root);
1835 em = rb_entry(n, struct extent_map, rb_node);
1836 ret = em->start + em->len;
1838 read_unlock(&em_tree->lock);
1843 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1847 struct btrfs_key key;
1848 struct btrfs_key found_key;
1849 struct btrfs_path *path;
1851 path = btrfs_alloc_path();
1855 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1856 key.type = BTRFS_DEV_ITEM_KEY;
1857 key.offset = (u64)-1;
1859 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1865 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1870 ret = btrfs_previous_item(fs_info->chunk_root, path,
1871 BTRFS_DEV_ITEMS_OBJECTID,
1872 BTRFS_DEV_ITEM_KEY);
1876 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1878 *devid_ret = found_key.offset + 1;
1882 btrfs_free_path(path);
1887 * the device information is stored in the chunk root
1888 * the btrfs_device struct should be fully filled in
1890 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1891 struct btrfs_device *device)
1894 struct btrfs_path *path;
1895 struct btrfs_dev_item *dev_item;
1896 struct extent_buffer *leaf;
1897 struct btrfs_key key;
1900 path = btrfs_alloc_path();
1904 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1905 key.type = BTRFS_DEV_ITEM_KEY;
1906 key.offset = device->devid;
1908 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1909 &key, sizeof(*dev_item));
1913 leaf = path->nodes[0];
1914 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1916 btrfs_set_device_id(leaf, dev_item, device->devid);
1917 btrfs_set_device_generation(leaf, dev_item, 0);
1918 btrfs_set_device_type(leaf, dev_item, device->type);
1919 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1920 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1921 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1922 btrfs_set_device_total_bytes(leaf, dev_item,
1923 btrfs_device_get_disk_total_bytes(device));
1924 btrfs_set_device_bytes_used(leaf, dev_item,
1925 btrfs_device_get_bytes_used(device));
1926 btrfs_set_device_group(leaf, dev_item, 0);
1927 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1928 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1929 btrfs_set_device_start_offset(leaf, dev_item, 0);
1931 ptr = btrfs_device_uuid(dev_item);
1932 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1933 ptr = btrfs_device_fsid(dev_item);
1934 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1935 ptr, BTRFS_FSID_SIZE);
1936 btrfs_mark_buffer_dirty(leaf);
1940 btrfs_free_path(path);
1945 * Function to update ctime/mtime for a given device path.
1946 * Mainly used for ctime/mtime based probe like libblkid.
1948 * We don't care about errors here, this is just to be kind to userspace.
1950 static void update_dev_time(const char *device_path)
1953 struct timespec64 now;
1956 ret = kern_path(device_path, LOOKUP_FOLLOW, &path);
1960 now = current_time(d_inode(path.dentry));
1961 inode_update_time(d_inode(path.dentry), &now, S_MTIME | S_CTIME);
1965 static int btrfs_rm_dev_item(struct btrfs_device *device)
1967 struct btrfs_root *root = device->fs_info->chunk_root;
1969 struct btrfs_path *path;
1970 struct btrfs_key key;
1971 struct btrfs_trans_handle *trans;
1973 path = btrfs_alloc_path();
1977 trans = btrfs_start_transaction(root, 0);
1978 if (IS_ERR(trans)) {
1979 btrfs_free_path(path);
1980 return PTR_ERR(trans);
1982 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1983 key.type = BTRFS_DEV_ITEM_KEY;
1984 key.offset = device->devid;
1986 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1990 btrfs_abort_transaction(trans, ret);
1991 btrfs_end_transaction(trans);
1995 ret = btrfs_del_item(trans, root, path);
1997 btrfs_abort_transaction(trans, ret);
1998 btrfs_end_transaction(trans);
2002 btrfs_free_path(path);
2004 ret = btrfs_commit_transaction(trans);
2009 * Verify that @num_devices satisfies the RAID profile constraints in the whole
2010 * filesystem. It's up to the caller to adjust that number regarding eg. device
2013 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
2021 seq = read_seqbegin(&fs_info->profiles_lock);
2023 all_avail = fs_info->avail_data_alloc_bits |
2024 fs_info->avail_system_alloc_bits |
2025 fs_info->avail_metadata_alloc_bits;
2026 } while (read_seqretry(&fs_info->profiles_lock, seq));
2028 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2029 if (!(all_avail & btrfs_raid_array[i].bg_flag))
2032 if (num_devices < btrfs_raid_array[i].devs_min) {
2033 int ret = btrfs_raid_array[i].mindev_error;
2043 static struct btrfs_device * btrfs_find_next_active_device(
2044 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2046 struct btrfs_device *next_device;
2048 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2049 if (next_device != device &&
2050 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2051 && next_device->bdev)
2059 * Helper function to check if the given device is part of s_bdev / latest_bdev
2060 * and replace it with the provided or the next active device, in the context
2061 * where this function called, there should be always be another device (or
2062 * this_dev) which is active.
2064 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
2065 struct btrfs_device *next_device)
2067 struct btrfs_fs_info *fs_info = device->fs_info;
2070 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2072 ASSERT(next_device);
2074 if (fs_info->sb->s_bdev &&
2075 (fs_info->sb->s_bdev == device->bdev))
2076 fs_info->sb->s_bdev = next_device->bdev;
2078 if (fs_info->fs_devices->latest_bdev == device->bdev)
2079 fs_info->fs_devices->latest_bdev = next_device->bdev;
2083 * Return btrfs_fs_devices::num_devices excluding the device that's being
2084 * currently replaced.
2086 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2088 u64 num_devices = fs_info->fs_devices->num_devices;
2090 down_read(&fs_info->dev_replace.rwsem);
2091 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2092 ASSERT(num_devices > 1);
2095 up_read(&fs_info->dev_replace.rwsem);
2100 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2101 struct block_device *bdev,
2102 const char *device_path)
2104 struct btrfs_super_block *disk_super;
2110 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2114 disk_super = btrfs_read_dev_one_super(bdev, copy_num);
2115 if (IS_ERR(disk_super))
2118 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
2120 page = virt_to_page(disk_super);
2121 set_page_dirty(page);
2123 /* write_on_page() unlocks the page */
2124 ret = write_one_page(page);
2127 "error clearing superblock number %d (%d)",
2129 btrfs_release_disk_super(disk_super);
2133 /* Notify udev that device has changed */
2134 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2136 /* Update ctime/mtime for device path for libblkid */
2137 update_dev_time(device_path);
2140 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2143 struct btrfs_device *device;
2144 struct btrfs_fs_devices *cur_devices;
2145 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2150 * The device list in fs_devices is accessed without locks (neither
2151 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2152 * filesystem and another device rm cannot run.
2154 num_devices = btrfs_num_devices(fs_info);
2156 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2160 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2162 if (IS_ERR(device)) {
2163 if (PTR_ERR(device) == -ENOENT &&
2164 device_path && strcmp(device_path, "missing") == 0)
2165 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2167 ret = PTR_ERR(device);
2171 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2172 btrfs_warn_in_rcu(fs_info,
2173 "cannot remove device %s (devid %llu) due to active swapfile",
2174 rcu_str_deref(device->name), device->devid);
2179 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2180 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2184 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2185 fs_info->fs_devices->rw_devices == 1) {
2186 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2190 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2191 mutex_lock(&fs_info->chunk_mutex);
2192 list_del_init(&device->dev_alloc_list);
2193 device->fs_devices->rw_devices--;
2194 mutex_unlock(&fs_info->chunk_mutex);
2197 ret = btrfs_shrink_device(device, 0);
2199 btrfs_reada_remove_dev(device);
2204 * TODO: the superblock still includes this device in its num_devices
2205 * counter although write_all_supers() is not locked out. This
2206 * could give a filesystem state which requires a degraded mount.
2208 ret = btrfs_rm_dev_item(device);
2212 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2213 btrfs_scrub_cancel_dev(device);
2216 * the device list mutex makes sure that we don't change
2217 * the device list while someone else is writing out all
2218 * the device supers. Whoever is writing all supers, should
2219 * lock the device list mutex before getting the number of
2220 * devices in the super block (super_copy). Conversely,
2221 * whoever updates the number of devices in the super block
2222 * (super_copy) should hold the device list mutex.
2226 * In normal cases the cur_devices == fs_devices. But in case
2227 * of deleting a seed device, the cur_devices should point to
2228 * its own fs_devices listed under the fs_devices->seed.
2230 cur_devices = device->fs_devices;
2231 mutex_lock(&fs_devices->device_list_mutex);
2232 list_del_rcu(&device->dev_list);
2234 cur_devices->num_devices--;
2235 cur_devices->total_devices--;
2236 /* Update total_devices of the parent fs_devices if it's seed */
2237 if (cur_devices != fs_devices)
2238 fs_devices->total_devices--;
2240 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2241 cur_devices->missing_devices--;
2243 btrfs_assign_next_active_device(device, NULL);
2246 cur_devices->open_devices--;
2247 /* remove sysfs entry */
2248 btrfs_sysfs_remove_device(device);
2251 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2252 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2253 mutex_unlock(&fs_devices->device_list_mutex);
2256 * at this point, the device is zero sized and detached from
2257 * the devices list. All that's left is to zero out the old
2258 * supers and free the device.
2260 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2261 btrfs_scratch_superblocks(fs_info, device->bdev,
2264 btrfs_close_bdev(device);
2266 btrfs_free_device(device);
2268 if (cur_devices->open_devices == 0) {
2269 list_del_init(&cur_devices->seed_list);
2270 close_fs_devices(cur_devices);
2271 free_fs_devices(cur_devices);
2278 btrfs_reada_undo_remove_dev(device);
2279 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2280 mutex_lock(&fs_info->chunk_mutex);
2281 list_add(&device->dev_alloc_list,
2282 &fs_devices->alloc_list);
2283 device->fs_devices->rw_devices++;
2284 mutex_unlock(&fs_info->chunk_mutex);
2289 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2291 struct btrfs_fs_devices *fs_devices;
2293 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2296 * in case of fs with no seed, srcdev->fs_devices will point
2297 * to fs_devices of fs_info. However when the dev being replaced is
2298 * a seed dev it will point to the seed's local fs_devices. In short
2299 * srcdev will have its correct fs_devices in both the cases.
2301 fs_devices = srcdev->fs_devices;
2303 list_del_rcu(&srcdev->dev_list);
2304 list_del(&srcdev->dev_alloc_list);
2305 fs_devices->num_devices--;
2306 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2307 fs_devices->missing_devices--;
2309 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2310 fs_devices->rw_devices--;
2313 fs_devices->open_devices--;
2316 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2318 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2320 mutex_lock(&uuid_mutex);
2322 btrfs_close_bdev(srcdev);
2324 btrfs_free_device(srcdev);
2326 /* if this is no devs we rather delete the fs_devices */
2327 if (!fs_devices->num_devices) {
2329 * On a mounted FS, num_devices can't be zero unless it's a
2330 * seed. In case of a seed device being replaced, the replace
2331 * target added to the sprout FS, so there will be no more
2332 * device left under the seed FS.
2334 ASSERT(fs_devices->seeding);
2336 list_del_init(&fs_devices->seed_list);
2337 close_fs_devices(fs_devices);
2338 free_fs_devices(fs_devices);
2340 mutex_unlock(&uuid_mutex);
2343 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2345 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2347 mutex_lock(&fs_devices->device_list_mutex);
2349 btrfs_sysfs_remove_device(tgtdev);
2352 fs_devices->open_devices--;
2354 fs_devices->num_devices--;
2356 btrfs_assign_next_active_device(tgtdev, NULL);
2358 list_del_rcu(&tgtdev->dev_list);
2360 mutex_unlock(&fs_devices->device_list_mutex);
2363 * The update_dev_time() with in btrfs_scratch_superblocks()
2364 * may lead to a call to btrfs_show_devname() which will try
2365 * to hold device_list_mutex. And here this device
2366 * is already out of device list, so we don't have to hold
2367 * the device_list_mutex lock.
2369 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2372 btrfs_close_bdev(tgtdev);
2374 btrfs_free_device(tgtdev);
2377 static struct btrfs_device *btrfs_find_device_by_path(
2378 struct btrfs_fs_info *fs_info, const char *device_path)
2381 struct btrfs_super_block *disk_super;
2384 struct block_device *bdev;
2385 struct btrfs_device *device;
2387 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2388 fs_info->bdev_holder, 0, &bdev, &disk_super);
2390 return ERR_PTR(ret);
2392 devid = btrfs_stack_device_id(&disk_super->dev_item);
2393 dev_uuid = disk_super->dev_item.uuid;
2394 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2395 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2396 disk_super->metadata_uuid, true);
2398 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2399 disk_super->fsid, true);
2401 btrfs_release_disk_super(disk_super);
2403 device = ERR_PTR(-ENOENT);
2404 blkdev_put(bdev, FMODE_READ);
2409 * Lookup a device given by device id, or the path if the id is 0.
2411 struct btrfs_device *btrfs_find_device_by_devspec(
2412 struct btrfs_fs_info *fs_info, u64 devid,
2413 const char *device_path)
2415 struct btrfs_device *device;
2418 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2421 return ERR_PTR(-ENOENT);
2425 if (!device_path || !device_path[0])
2426 return ERR_PTR(-EINVAL);
2428 if (strcmp(device_path, "missing") == 0) {
2429 /* Find first missing device */
2430 list_for_each_entry(device, &fs_info->fs_devices->devices,
2432 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2433 &device->dev_state) && !device->bdev)
2436 return ERR_PTR(-ENOENT);
2439 return btrfs_find_device_by_path(fs_info, device_path);
2443 * does all the dirty work required for changing file system's UUID.
2445 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2447 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2448 struct btrfs_fs_devices *old_devices;
2449 struct btrfs_fs_devices *seed_devices;
2450 struct btrfs_super_block *disk_super = fs_info->super_copy;
2451 struct btrfs_device *device;
2454 lockdep_assert_held(&uuid_mutex);
2455 if (!fs_devices->seeding)
2459 * Private copy of the seed devices, anchored at
2460 * fs_info->fs_devices->seed_list
2462 seed_devices = alloc_fs_devices(NULL, NULL);
2463 if (IS_ERR(seed_devices))
2464 return PTR_ERR(seed_devices);
2467 * It's necessary to retain a copy of the original seed fs_devices in
2468 * fs_uuids so that filesystems which have been seeded can successfully
2469 * reference the seed device from open_seed_devices. This also supports
2472 old_devices = clone_fs_devices(fs_devices);
2473 if (IS_ERR(old_devices)) {
2474 kfree(seed_devices);
2475 return PTR_ERR(old_devices);
2478 list_add(&old_devices->fs_list, &fs_uuids);
2480 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2481 seed_devices->opened = 1;
2482 INIT_LIST_HEAD(&seed_devices->devices);
2483 INIT_LIST_HEAD(&seed_devices->alloc_list);
2484 mutex_init(&seed_devices->device_list_mutex);
2486 mutex_lock(&fs_devices->device_list_mutex);
2487 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2489 list_for_each_entry(device, &seed_devices->devices, dev_list)
2490 device->fs_devices = seed_devices;
2492 fs_devices->seeding = false;
2493 fs_devices->num_devices = 0;
2494 fs_devices->open_devices = 0;
2495 fs_devices->missing_devices = 0;
2496 fs_devices->rotating = false;
2497 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2499 generate_random_uuid(fs_devices->fsid);
2500 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2501 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2502 mutex_unlock(&fs_devices->device_list_mutex);
2504 super_flags = btrfs_super_flags(disk_super) &
2505 ~BTRFS_SUPER_FLAG_SEEDING;
2506 btrfs_set_super_flags(disk_super, super_flags);
2512 * Store the expected generation for seed devices in device items.
2514 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2516 struct btrfs_fs_info *fs_info = trans->fs_info;
2517 struct btrfs_root *root = fs_info->chunk_root;
2518 struct btrfs_path *path;
2519 struct extent_buffer *leaf;
2520 struct btrfs_dev_item *dev_item;
2521 struct btrfs_device *device;
2522 struct btrfs_key key;
2523 u8 fs_uuid[BTRFS_FSID_SIZE];
2524 u8 dev_uuid[BTRFS_UUID_SIZE];
2528 path = btrfs_alloc_path();
2532 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2534 key.type = BTRFS_DEV_ITEM_KEY;
2537 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2541 leaf = path->nodes[0];
2543 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2544 ret = btrfs_next_leaf(root, path);
2549 leaf = path->nodes[0];
2550 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2551 btrfs_release_path(path);
2555 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2556 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2557 key.type != BTRFS_DEV_ITEM_KEY)
2560 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2561 struct btrfs_dev_item);
2562 devid = btrfs_device_id(leaf, dev_item);
2563 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2565 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2567 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2569 BUG_ON(!device); /* Logic error */
2571 if (device->fs_devices->seeding) {
2572 btrfs_set_device_generation(leaf, dev_item,
2573 device->generation);
2574 btrfs_mark_buffer_dirty(leaf);
2582 btrfs_free_path(path);
2586 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2588 struct btrfs_root *root = fs_info->dev_root;
2589 struct request_queue *q;
2590 struct btrfs_trans_handle *trans;
2591 struct btrfs_device *device;
2592 struct block_device *bdev;
2593 struct super_block *sb = fs_info->sb;
2594 struct rcu_string *name;
2595 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2596 u64 orig_super_total_bytes;
2597 u64 orig_super_num_devices;
2598 int seeding_dev = 0;
2600 bool locked = false;
2602 if (sb_rdonly(sb) && !fs_devices->seeding)
2605 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2606 fs_info->bdev_holder);
2608 return PTR_ERR(bdev);
2610 if (fs_devices->seeding) {
2612 down_write(&sb->s_umount);
2613 mutex_lock(&uuid_mutex);
2617 sync_blockdev(bdev);
2620 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2621 if (device->bdev == bdev) {
2629 device = btrfs_alloc_device(fs_info, NULL, NULL);
2630 if (IS_ERR(device)) {
2631 /* we can safely leave the fs_devices entry around */
2632 ret = PTR_ERR(device);
2636 name = rcu_string_strdup(device_path, GFP_KERNEL);
2639 goto error_free_device;
2641 rcu_assign_pointer(device->name, name);
2643 trans = btrfs_start_transaction(root, 0);
2644 if (IS_ERR(trans)) {
2645 ret = PTR_ERR(trans);
2646 goto error_free_device;
2649 q = bdev_get_queue(bdev);
2650 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2651 device->generation = trans->transid;
2652 device->io_width = fs_info->sectorsize;
2653 device->io_align = fs_info->sectorsize;
2654 device->sector_size = fs_info->sectorsize;
2655 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2656 fs_info->sectorsize);
2657 device->disk_total_bytes = device->total_bytes;
2658 device->commit_total_bytes = device->total_bytes;
2659 device->fs_info = fs_info;
2660 device->bdev = bdev;
2661 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2662 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2663 device->mode = FMODE_EXCL;
2664 device->dev_stats_valid = 1;
2665 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2668 sb->s_flags &= ~SB_RDONLY;
2669 ret = btrfs_prepare_sprout(fs_info);
2671 btrfs_abort_transaction(trans, ret);
2676 device->fs_devices = fs_devices;
2678 mutex_lock(&fs_devices->device_list_mutex);
2679 mutex_lock(&fs_info->chunk_mutex);
2680 list_add_rcu(&device->dev_list, &fs_devices->devices);
2681 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2682 fs_devices->num_devices++;
2683 fs_devices->open_devices++;
2684 fs_devices->rw_devices++;
2685 fs_devices->total_devices++;
2686 fs_devices->total_rw_bytes += device->total_bytes;
2688 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2690 if (!blk_queue_nonrot(q))
2691 fs_devices->rotating = true;
2693 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2694 btrfs_set_super_total_bytes(fs_info->super_copy,
2695 round_down(orig_super_total_bytes + device->total_bytes,
2696 fs_info->sectorsize));
2698 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2699 btrfs_set_super_num_devices(fs_info->super_copy,
2700 orig_super_num_devices + 1);
2703 * we've got more storage, clear any full flags on the space
2706 btrfs_clear_space_info_full(fs_info);
2708 mutex_unlock(&fs_info->chunk_mutex);
2710 /* Add sysfs device entry */
2711 btrfs_sysfs_add_device(device);
2713 mutex_unlock(&fs_devices->device_list_mutex);
2716 mutex_lock(&fs_info->chunk_mutex);
2717 ret = init_first_rw_device(trans);
2718 mutex_unlock(&fs_info->chunk_mutex);
2720 btrfs_abort_transaction(trans, ret);
2725 ret = btrfs_add_dev_item(trans, device);
2727 btrfs_abort_transaction(trans, ret);
2732 ret = btrfs_finish_sprout(trans);
2734 btrfs_abort_transaction(trans, ret);
2739 * fs_devices now represents the newly sprouted filesystem and
2740 * its fsid has been changed by btrfs_prepare_sprout
2742 btrfs_sysfs_update_sprout_fsid(fs_devices);
2745 ret = btrfs_commit_transaction(trans);
2748 mutex_unlock(&uuid_mutex);
2749 up_write(&sb->s_umount);
2752 if (ret) /* transaction commit */
2755 ret = btrfs_relocate_sys_chunks(fs_info);
2757 btrfs_handle_fs_error(fs_info, ret,
2758 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2759 trans = btrfs_attach_transaction(root);
2760 if (IS_ERR(trans)) {
2761 if (PTR_ERR(trans) == -ENOENT)
2763 ret = PTR_ERR(trans);
2767 ret = btrfs_commit_transaction(trans);
2771 * Now that we have written a new super block to this device, check all
2772 * other fs_devices list if device_path alienates any other scanned
2774 * We can ignore the return value as it typically returns -EINVAL and
2775 * only succeeds if the device was an alien.
2777 btrfs_forget_devices(device_path);
2779 /* Update ctime/mtime for blkid or udev */
2780 update_dev_time(device_path);
2785 btrfs_sysfs_remove_device(device);
2786 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2787 mutex_lock(&fs_info->chunk_mutex);
2788 list_del_rcu(&device->dev_list);
2789 list_del(&device->dev_alloc_list);
2790 fs_info->fs_devices->num_devices--;
2791 fs_info->fs_devices->open_devices--;
2792 fs_info->fs_devices->rw_devices--;
2793 fs_info->fs_devices->total_devices--;
2794 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2795 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2796 btrfs_set_super_total_bytes(fs_info->super_copy,
2797 orig_super_total_bytes);
2798 btrfs_set_super_num_devices(fs_info->super_copy,
2799 orig_super_num_devices);
2800 mutex_unlock(&fs_info->chunk_mutex);
2801 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2804 sb->s_flags |= SB_RDONLY;
2806 btrfs_end_transaction(trans);
2808 btrfs_free_device(device);
2810 blkdev_put(bdev, FMODE_EXCL);
2812 mutex_unlock(&uuid_mutex);
2813 up_write(&sb->s_umount);
2818 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2819 struct btrfs_device *device)
2822 struct btrfs_path *path;
2823 struct btrfs_root *root = device->fs_info->chunk_root;
2824 struct btrfs_dev_item *dev_item;
2825 struct extent_buffer *leaf;
2826 struct btrfs_key key;
2828 path = btrfs_alloc_path();
2832 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2833 key.type = BTRFS_DEV_ITEM_KEY;
2834 key.offset = device->devid;
2836 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2845 leaf = path->nodes[0];
2846 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2848 btrfs_set_device_id(leaf, dev_item, device->devid);
2849 btrfs_set_device_type(leaf, dev_item, device->type);
2850 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2851 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2852 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2853 btrfs_set_device_total_bytes(leaf, dev_item,
2854 btrfs_device_get_disk_total_bytes(device));
2855 btrfs_set_device_bytes_used(leaf, dev_item,
2856 btrfs_device_get_bytes_used(device));
2857 btrfs_mark_buffer_dirty(leaf);
2860 btrfs_free_path(path);
2864 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2865 struct btrfs_device *device, u64 new_size)
2867 struct btrfs_fs_info *fs_info = device->fs_info;
2868 struct btrfs_super_block *super_copy = fs_info->super_copy;
2872 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2875 new_size = round_down(new_size, fs_info->sectorsize);
2877 mutex_lock(&fs_info->chunk_mutex);
2878 old_total = btrfs_super_total_bytes(super_copy);
2879 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2881 if (new_size <= device->total_bytes ||
2882 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2883 mutex_unlock(&fs_info->chunk_mutex);
2887 btrfs_set_super_total_bytes(super_copy,
2888 round_down(old_total + diff, fs_info->sectorsize));
2889 device->fs_devices->total_rw_bytes += diff;
2891 btrfs_device_set_total_bytes(device, new_size);
2892 btrfs_device_set_disk_total_bytes(device, new_size);
2893 btrfs_clear_space_info_full(device->fs_info);
2894 if (list_empty(&device->post_commit_list))
2895 list_add_tail(&device->post_commit_list,
2896 &trans->transaction->dev_update_list);
2897 mutex_unlock(&fs_info->chunk_mutex);
2899 return btrfs_update_device(trans, device);
2902 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2904 struct btrfs_fs_info *fs_info = trans->fs_info;
2905 struct btrfs_root *root = fs_info->chunk_root;
2907 struct btrfs_path *path;
2908 struct btrfs_key key;
2910 path = btrfs_alloc_path();
2914 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2915 key.offset = chunk_offset;
2916 key.type = BTRFS_CHUNK_ITEM_KEY;
2918 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2921 else if (ret > 0) { /* Logic error or corruption */
2922 btrfs_handle_fs_error(fs_info, -ENOENT,
2923 "Failed lookup while freeing chunk.");
2928 ret = btrfs_del_item(trans, root, path);
2930 btrfs_handle_fs_error(fs_info, ret,
2931 "Failed to delete chunk item.");
2933 btrfs_free_path(path);
2937 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2939 struct btrfs_super_block *super_copy = fs_info->super_copy;
2940 struct btrfs_disk_key *disk_key;
2941 struct btrfs_chunk *chunk;
2948 struct btrfs_key key;
2950 mutex_lock(&fs_info->chunk_mutex);
2951 array_size = btrfs_super_sys_array_size(super_copy);
2953 ptr = super_copy->sys_chunk_array;
2956 while (cur < array_size) {
2957 disk_key = (struct btrfs_disk_key *)ptr;
2958 btrfs_disk_key_to_cpu(&key, disk_key);
2960 len = sizeof(*disk_key);
2962 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2963 chunk = (struct btrfs_chunk *)(ptr + len);
2964 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2965 len += btrfs_chunk_item_size(num_stripes);
2970 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2971 key.offset == chunk_offset) {
2972 memmove(ptr, ptr + len, array_size - (cur + len));
2974 btrfs_set_super_sys_array_size(super_copy, array_size);
2980 mutex_unlock(&fs_info->chunk_mutex);
2985 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2986 * @logical: Logical block offset in bytes.
2987 * @length: Length of extent in bytes.
2989 * Return: Chunk mapping or ERR_PTR.
2991 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2992 u64 logical, u64 length)
2994 struct extent_map_tree *em_tree;
2995 struct extent_map *em;
2997 em_tree = &fs_info->mapping_tree;
2998 read_lock(&em_tree->lock);
2999 em = lookup_extent_mapping(em_tree, logical, length);
3000 read_unlock(&em_tree->lock);
3004 "unable to find chunk map for logical %llu length %llu",
3006 return ERR_PTR(-EINVAL);
3009 if (em->start > logical || em->start + em->len <= logical) {
3011 "found a bad chunk map, wanted %llu-%llu, found %llu-%llu",
3012 logical, logical + length, em->start, em->start + em->len);
3013 free_extent_map(em);
3014 return ERR_PTR(-EINVAL);
3017 /* callers are responsible for dropping em's ref. */
3021 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3023 struct btrfs_fs_info *fs_info = trans->fs_info;
3024 struct extent_map *em;
3025 struct map_lookup *map;
3026 u64 dev_extent_len = 0;
3028 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3030 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3033 * This is a logic error, but we don't want to just rely on the
3034 * user having built with ASSERT enabled, so if ASSERT doesn't
3035 * do anything we still error out.
3040 map = em->map_lookup;
3041 mutex_lock(&fs_info->chunk_mutex);
3042 check_system_chunk(trans, map->type);
3043 mutex_unlock(&fs_info->chunk_mutex);
3046 * Take the device list mutex to prevent races with the final phase of
3047 * a device replace operation that replaces the device object associated
3048 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
3050 mutex_lock(&fs_devices->device_list_mutex);
3051 for (i = 0; i < map->num_stripes; i++) {
3052 struct btrfs_device *device = map->stripes[i].dev;
3053 ret = btrfs_free_dev_extent(trans, device,
3054 map->stripes[i].physical,
3057 mutex_unlock(&fs_devices->device_list_mutex);
3058 btrfs_abort_transaction(trans, ret);
3062 if (device->bytes_used > 0) {
3063 mutex_lock(&fs_info->chunk_mutex);
3064 btrfs_device_set_bytes_used(device,
3065 device->bytes_used - dev_extent_len);
3066 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3067 btrfs_clear_space_info_full(fs_info);
3068 mutex_unlock(&fs_info->chunk_mutex);
3071 ret = btrfs_update_device(trans, device);
3073 mutex_unlock(&fs_devices->device_list_mutex);
3074 btrfs_abort_transaction(trans, ret);
3078 mutex_unlock(&fs_devices->device_list_mutex);
3080 ret = btrfs_free_chunk(trans, chunk_offset);
3082 btrfs_abort_transaction(trans, ret);
3086 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3088 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3089 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3091 btrfs_abort_transaction(trans, ret);
3096 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3098 btrfs_abort_transaction(trans, ret);
3104 free_extent_map(em);
3108 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3110 struct btrfs_root *root = fs_info->chunk_root;
3111 struct btrfs_trans_handle *trans;
3112 struct btrfs_block_group *block_group;
3116 * Prevent races with automatic removal of unused block groups.
3117 * After we relocate and before we remove the chunk with offset
3118 * chunk_offset, automatic removal of the block group can kick in,
3119 * resulting in a failure when calling btrfs_remove_chunk() below.
3121 * Make sure to acquire this mutex before doing a tree search (dev
3122 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3123 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3124 * we release the path used to search the chunk/dev tree and before
3125 * the current task acquires this mutex and calls us.
3127 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3129 /* step one, relocate all the extents inside this chunk */
3130 btrfs_scrub_pause(fs_info);
3131 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3132 btrfs_scrub_continue(fs_info);
3136 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3139 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3140 btrfs_put_block_group(block_group);
3142 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3144 if (IS_ERR(trans)) {
3145 ret = PTR_ERR(trans);
3146 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3151 * step two, delete the device extents and the
3152 * chunk tree entries
3154 ret = btrfs_remove_chunk(trans, chunk_offset);
3155 btrfs_end_transaction(trans);
3159 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3161 struct btrfs_root *chunk_root = fs_info->chunk_root;
3162 struct btrfs_path *path;
3163 struct extent_buffer *leaf;
3164 struct btrfs_chunk *chunk;
3165 struct btrfs_key key;
3166 struct btrfs_key found_key;
3168 bool retried = false;
3172 path = btrfs_alloc_path();
3177 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3178 key.offset = (u64)-1;
3179 key.type = BTRFS_CHUNK_ITEM_KEY;
3182 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3183 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3185 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3190 * On the first search we would find chunk tree with
3191 * offset -1, which is not possible. On subsequent
3192 * loops this would find an existing item on an invalid
3193 * offset (one less than the previous one, wrong
3194 * alignment and size).
3197 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3201 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3204 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3210 leaf = path->nodes[0];
3211 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3213 chunk = btrfs_item_ptr(leaf, path->slots[0],
3214 struct btrfs_chunk);
3215 chunk_type = btrfs_chunk_type(leaf, chunk);
3216 btrfs_release_path(path);
3218 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3219 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3225 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3227 if (found_key.offset == 0)
3229 key.offset = found_key.offset - 1;
3232 if (failed && !retried) {
3236 } else if (WARN_ON(failed && retried)) {
3240 btrfs_free_path(path);
3245 * return 1 : allocate a data chunk successfully,
3246 * return <0: errors during allocating a data chunk,
3247 * return 0 : no need to allocate a data chunk.
3249 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3252 struct btrfs_block_group *cache;
3256 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3258 chunk_type = cache->flags;
3259 btrfs_put_block_group(cache);
3261 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3264 spin_lock(&fs_info->data_sinfo->lock);
3265 bytes_used = fs_info->data_sinfo->bytes_used;
3266 spin_unlock(&fs_info->data_sinfo->lock);
3269 struct btrfs_trans_handle *trans;
3272 trans = btrfs_join_transaction(fs_info->tree_root);
3274 return PTR_ERR(trans);
3276 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3277 btrfs_end_transaction(trans);
3286 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3287 struct btrfs_balance_control *bctl)
3289 struct btrfs_root *root = fs_info->tree_root;
3290 struct btrfs_trans_handle *trans;
3291 struct btrfs_balance_item *item;
3292 struct btrfs_disk_balance_args disk_bargs;
3293 struct btrfs_path *path;
3294 struct extent_buffer *leaf;
3295 struct btrfs_key key;
3298 path = btrfs_alloc_path();
3302 trans = btrfs_start_transaction(root, 0);
3303 if (IS_ERR(trans)) {
3304 btrfs_free_path(path);
3305 return PTR_ERR(trans);
3308 key.objectid = BTRFS_BALANCE_OBJECTID;
3309 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3312 ret = btrfs_insert_empty_item(trans, root, path, &key,
3317 leaf = path->nodes[0];
3318 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3320 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3322 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3323 btrfs_set_balance_data(leaf, item, &disk_bargs);
3324 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3325 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3326 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3327 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3329 btrfs_set_balance_flags(leaf, item, bctl->flags);
3331 btrfs_mark_buffer_dirty(leaf);
3333 btrfs_free_path(path);
3334 err = btrfs_commit_transaction(trans);
3340 static int del_balance_item(struct btrfs_fs_info *fs_info)
3342 struct btrfs_root *root = fs_info->tree_root;
3343 struct btrfs_trans_handle *trans;
3344 struct btrfs_path *path;
3345 struct btrfs_key key;
3348 path = btrfs_alloc_path();
3352 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3353 if (IS_ERR(trans)) {
3354 btrfs_free_path(path);
3355 return PTR_ERR(trans);
3358 key.objectid = BTRFS_BALANCE_OBJECTID;
3359 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3362 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3370 ret = btrfs_del_item(trans, root, path);
3372 btrfs_free_path(path);
3373 err = btrfs_commit_transaction(trans);
3380 * This is a heuristic used to reduce the number of chunks balanced on
3381 * resume after balance was interrupted.
3383 static void update_balance_args(struct btrfs_balance_control *bctl)
3386 * Turn on soft mode for chunk types that were being converted.
3388 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3389 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3390 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3391 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3392 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3393 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3396 * Turn on usage filter if is not already used. The idea is
3397 * that chunks that we have already balanced should be
3398 * reasonably full. Don't do it for chunks that are being
3399 * converted - that will keep us from relocating unconverted
3400 * (albeit full) chunks.
3402 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3403 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3404 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3405 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3406 bctl->data.usage = 90;
3408 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3409 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3410 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3411 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3412 bctl->sys.usage = 90;
3414 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3415 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3416 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3417 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3418 bctl->meta.usage = 90;
3423 * Clear the balance status in fs_info and delete the balance item from disk.
3425 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3427 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3430 BUG_ON(!fs_info->balance_ctl);
3432 spin_lock(&fs_info->balance_lock);
3433 fs_info->balance_ctl = NULL;
3434 spin_unlock(&fs_info->balance_lock);
3437 ret = del_balance_item(fs_info);
3439 btrfs_handle_fs_error(fs_info, ret, NULL);
3443 * Balance filters. Return 1 if chunk should be filtered out
3444 * (should not be balanced).
3446 static int chunk_profiles_filter(u64 chunk_type,
3447 struct btrfs_balance_args *bargs)
3449 chunk_type = chunk_to_extended(chunk_type) &
3450 BTRFS_EXTENDED_PROFILE_MASK;
3452 if (bargs->profiles & chunk_type)
3458 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3459 struct btrfs_balance_args *bargs)
3461 struct btrfs_block_group *cache;
3463 u64 user_thresh_min;
3464 u64 user_thresh_max;
3467 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3468 chunk_used = cache->used;
3470 if (bargs->usage_min == 0)
3471 user_thresh_min = 0;
3473 user_thresh_min = div_factor_fine(cache->length,
3476 if (bargs->usage_max == 0)
3477 user_thresh_max = 1;
3478 else if (bargs->usage_max > 100)
3479 user_thresh_max = cache->length;
3481 user_thresh_max = div_factor_fine(cache->length,
3484 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3487 btrfs_put_block_group(cache);
3491 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3492 u64 chunk_offset, struct btrfs_balance_args *bargs)
3494 struct btrfs_block_group *cache;
3495 u64 chunk_used, user_thresh;
3498 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3499 chunk_used = cache->used;
3501 if (bargs->usage_min == 0)
3503 else if (bargs->usage > 100)
3504 user_thresh = cache->length;
3506 user_thresh = div_factor_fine(cache->length, bargs->usage);
3508 if (chunk_used < user_thresh)
3511 btrfs_put_block_group(cache);
3515 static int chunk_devid_filter(struct extent_buffer *leaf,
3516 struct btrfs_chunk *chunk,
3517 struct btrfs_balance_args *bargs)
3519 struct btrfs_stripe *stripe;
3520 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3523 for (i = 0; i < num_stripes; i++) {
3524 stripe = btrfs_stripe_nr(chunk, i);
3525 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3532 static u64 calc_data_stripes(u64 type, int num_stripes)
3534 const int index = btrfs_bg_flags_to_raid_index(type);
3535 const int ncopies = btrfs_raid_array[index].ncopies;
3536 const int nparity = btrfs_raid_array[index].nparity;
3539 return num_stripes - nparity;
3541 return num_stripes / ncopies;
3544 /* [pstart, pend) */
3545 static int chunk_drange_filter(struct extent_buffer *leaf,
3546 struct btrfs_chunk *chunk,
3547 struct btrfs_balance_args *bargs)
3549 struct btrfs_stripe *stripe;
3550 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3557 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3560 type = btrfs_chunk_type(leaf, chunk);
3561 factor = calc_data_stripes(type, num_stripes);
3563 for (i = 0; i < num_stripes; i++) {
3564 stripe = btrfs_stripe_nr(chunk, i);
3565 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3568 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3569 stripe_length = btrfs_chunk_length(leaf, chunk);
3570 stripe_length = div_u64(stripe_length, factor);
3572 if (stripe_offset < bargs->pend &&
3573 stripe_offset + stripe_length > bargs->pstart)
3580 /* [vstart, vend) */
3581 static int chunk_vrange_filter(struct extent_buffer *leaf,
3582 struct btrfs_chunk *chunk,
3584 struct btrfs_balance_args *bargs)
3586 if (chunk_offset < bargs->vend &&
3587 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3588 /* at least part of the chunk is inside this vrange */
3594 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3595 struct btrfs_chunk *chunk,
3596 struct btrfs_balance_args *bargs)
3598 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3600 if (bargs->stripes_min <= num_stripes
3601 && num_stripes <= bargs->stripes_max)
3607 static int chunk_soft_convert_filter(u64 chunk_type,
3608 struct btrfs_balance_args *bargs)
3610 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3613 chunk_type = chunk_to_extended(chunk_type) &
3614 BTRFS_EXTENDED_PROFILE_MASK;
3616 if (bargs->target == chunk_type)
3622 static int should_balance_chunk(struct extent_buffer *leaf,
3623 struct btrfs_chunk *chunk, u64 chunk_offset)
3625 struct btrfs_fs_info *fs_info = leaf->fs_info;
3626 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3627 struct btrfs_balance_args *bargs = NULL;
3628 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3631 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3632 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3636 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3637 bargs = &bctl->data;
3638 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3640 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3641 bargs = &bctl->meta;
3643 /* profiles filter */
3644 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3645 chunk_profiles_filter(chunk_type, bargs)) {
3650 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3651 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3653 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3654 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3659 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3660 chunk_devid_filter(leaf, chunk, bargs)) {
3664 /* drange filter, makes sense only with devid filter */
3665 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3666 chunk_drange_filter(leaf, chunk, bargs)) {
3671 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3672 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3676 /* stripes filter */
3677 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3678 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3682 /* soft profile changing mode */
3683 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3684 chunk_soft_convert_filter(chunk_type, bargs)) {
3689 * limited by count, must be the last filter
3691 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3692 if (bargs->limit == 0)
3696 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3698 * Same logic as the 'limit' filter; the minimum cannot be
3699 * determined here because we do not have the global information
3700 * about the count of all chunks that satisfy the filters.
3702 if (bargs->limit_max == 0)
3711 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3713 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3714 struct btrfs_root *chunk_root = fs_info->chunk_root;
3716 struct btrfs_chunk *chunk;
3717 struct btrfs_path *path = NULL;
3718 struct btrfs_key key;
3719 struct btrfs_key found_key;
3720 struct extent_buffer *leaf;
3723 int enospc_errors = 0;
3724 bool counting = true;
3725 /* The single value limit and min/max limits use the same bytes in the */
3726 u64 limit_data = bctl->data.limit;
3727 u64 limit_meta = bctl->meta.limit;
3728 u64 limit_sys = bctl->sys.limit;
3732 int chunk_reserved = 0;
3734 path = btrfs_alloc_path();
3740 /* zero out stat counters */
3741 spin_lock(&fs_info->balance_lock);
3742 memset(&bctl->stat, 0, sizeof(bctl->stat));
3743 spin_unlock(&fs_info->balance_lock);
3747 * The single value limit and min/max limits use the same bytes
3750 bctl->data.limit = limit_data;
3751 bctl->meta.limit = limit_meta;
3752 bctl->sys.limit = limit_sys;
3754 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3755 key.offset = (u64)-1;
3756 key.type = BTRFS_CHUNK_ITEM_KEY;
3759 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3760 atomic_read(&fs_info->balance_cancel_req)) {
3765 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3766 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3768 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3773 * this shouldn't happen, it means the last relocate
3777 BUG(); /* FIXME break ? */
3779 ret = btrfs_previous_item(chunk_root, path, 0,
3780 BTRFS_CHUNK_ITEM_KEY);
3782 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3787 leaf = path->nodes[0];
3788 slot = path->slots[0];
3789 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3791 if (found_key.objectid != key.objectid) {
3792 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3796 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3797 chunk_type = btrfs_chunk_type(leaf, chunk);
3800 spin_lock(&fs_info->balance_lock);
3801 bctl->stat.considered++;
3802 spin_unlock(&fs_info->balance_lock);
3805 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3807 btrfs_release_path(path);
3809 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3814 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3815 spin_lock(&fs_info->balance_lock);
3816 bctl->stat.expected++;
3817 spin_unlock(&fs_info->balance_lock);
3819 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3821 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3823 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3830 * Apply limit_min filter, no need to check if the LIMITS
3831 * filter is used, limit_min is 0 by default
3833 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3834 count_data < bctl->data.limit_min)
3835 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3836 count_meta < bctl->meta.limit_min)
3837 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3838 count_sys < bctl->sys.limit_min)) {
3839 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3843 if (!chunk_reserved) {
3845 * We may be relocating the only data chunk we have,
3846 * which could potentially end up with losing data's
3847 * raid profile, so lets allocate an empty one in
3850 ret = btrfs_may_alloc_data_chunk(fs_info,
3853 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3855 } else if (ret == 1) {
3860 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3861 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3862 if (ret == -ENOSPC) {
3864 } else if (ret == -ETXTBSY) {
3866 "skipping relocation of block group %llu due to active swapfile",
3872 spin_lock(&fs_info->balance_lock);
3873 bctl->stat.completed++;
3874 spin_unlock(&fs_info->balance_lock);
3877 if (found_key.offset == 0)
3879 key.offset = found_key.offset - 1;
3883 btrfs_release_path(path);
3888 btrfs_free_path(path);
3889 if (enospc_errors) {
3890 btrfs_info(fs_info, "%d enospc errors during balance",
3900 * alloc_profile_is_valid - see if a given profile is valid and reduced
3901 * @flags: profile to validate
3902 * @extended: if true @flags is treated as an extended profile
3904 static int alloc_profile_is_valid(u64 flags, int extended)
3906 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3907 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3909 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3911 /* 1) check that all other bits are zeroed */
3915 /* 2) see if profile is reduced */
3917 return !extended; /* "0" is valid for usual profiles */
3919 return has_single_bit_set(flags);
3922 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3924 /* cancel requested || normal exit path */
3925 return atomic_read(&fs_info->balance_cancel_req) ||
3926 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3927 atomic_read(&fs_info->balance_cancel_req) == 0);
3931 * Validate target profile against allowed profiles and return true if it's OK.
3932 * Otherwise print the error message and return false.
3934 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
3935 const struct btrfs_balance_args *bargs,
3936 u64 allowed, const char *type)
3938 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3941 /* Profile is valid and does not have bits outside of the allowed set */
3942 if (alloc_profile_is_valid(bargs->target, 1) &&
3943 (bargs->target & ~allowed) == 0)
3946 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
3947 type, btrfs_bg_type_to_raid_name(bargs->target));
3952 * Fill @buf with textual description of balance filter flags @bargs, up to
3953 * @size_buf including the terminating null. The output may be trimmed if it
3954 * does not fit into the provided buffer.
3956 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3960 u32 size_bp = size_buf;
3962 u64 flags = bargs->flags;
3963 char tmp_buf[128] = {'\0'};
3968 #define CHECK_APPEND_NOARG(a) \
3970 ret = snprintf(bp, size_bp, (a)); \
3971 if (ret < 0 || ret >= size_bp) \
3972 goto out_overflow; \
3977 #define CHECK_APPEND_1ARG(a, v1) \
3979 ret = snprintf(bp, size_bp, (a), (v1)); \
3980 if (ret < 0 || ret >= size_bp) \
3981 goto out_overflow; \
3986 #define CHECK_APPEND_2ARG(a, v1, v2) \
3988 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3989 if (ret < 0 || ret >= size_bp) \
3990 goto out_overflow; \
3995 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
3996 CHECK_APPEND_1ARG("convert=%s,",
3997 btrfs_bg_type_to_raid_name(bargs->target));
3999 if (flags & BTRFS_BALANCE_ARGS_SOFT)
4000 CHECK_APPEND_NOARG("soft,");
4002 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4003 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4005 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4008 if (flags & BTRFS_BALANCE_ARGS_USAGE)
4009 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4011 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4012 CHECK_APPEND_2ARG("usage=%u..%u,",
4013 bargs->usage_min, bargs->usage_max);
4015 if (flags & BTRFS_BALANCE_ARGS_DEVID)
4016 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4018 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4019 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4020 bargs->pstart, bargs->pend);
4022 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4023 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4024 bargs->vstart, bargs->vend);
4026 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4027 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4029 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4030 CHECK_APPEND_2ARG("limit=%u..%u,",
4031 bargs->limit_min, bargs->limit_max);
4033 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4034 CHECK_APPEND_2ARG("stripes=%u..%u,",
4035 bargs->stripes_min, bargs->stripes_max);
4037 #undef CHECK_APPEND_2ARG
4038 #undef CHECK_APPEND_1ARG
4039 #undef CHECK_APPEND_NOARG
4043 if (size_bp < size_buf)
4044 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4049 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4051 u32 size_buf = 1024;
4052 char tmp_buf[192] = {'\0'};
4055 u32 size_bp = size_buf;
4057 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4059 buf = kzalloc(size_buf, GFP_KERNEL);
4065 #define CHECK_APPEND_1ARG(a, v1) \
4067 ret = snprintf(bp, size_bp, (a), (v1)); \
4068 if (ret < 0 || ret >= size_bp) \
4069 goto out_overflow; \
4074 if (bctl->flags & BTRFS_BALANCE_FORCE)
4075 CHECK_APPEND_1ARG("%s", "-f ");
4077 if (bctl->flags & BTRFS_BALANCE_DATA) {
4078 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4079 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4082 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4083 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4084 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4087 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4088 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4089 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4092 #undef CHECK_APPEND_1ARG
4096 if (size_bp < size_buf)
4097 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4098 btrfs_info(fs_info, "balance: %s %s",
4099 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4100 "resume" : "start", buf);
4106 * Should be called with balance mutexe held
4108 int btrfs_balance(struct btrfs_fs_info *fs_info,
4109 struct btrfs_balance_control *bctl,
4110 struct btrfs_ioctl_balance_args *bargs)
4112 u64 meta_target, data_target;
4118 bool reducing_redundancy;
4121 if (btrfs_fs_closing(fs_info) ||
4122 atomic_read(&fs_info->balance_pause_req) ||
4123 btrfs_should_cancel_balance(fs_info)) {
4128 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4129 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4133 * In case of mixed groups both data and meta should be picked,
4134 * and identical options should be given for both of them.
4136 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4137 if (mixed && (bctl->flags & allowed)) {
4138 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4139 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4140 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4142 "balance: mixed groups data and metadata options must be the same");
4149 * rw_devices will not change at the moment, device add/delete/replace
4152 num_devices = fs_info->fs_devices->rw_devices;
4155 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4156 * special bit for it, to make it easier to distinguish. Thus we need
4157 * to set it manually, or balance would refuse the profile.
4159 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4160 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4161 if (num_devices >= btrfs_raid_array[i].devs_min)
4162 allowed |= btrfs_raid_array[i].bg_flag;
4164 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4165 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4166 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
4172 * Allow to reduce metadata or system integrity only if force set for
4173 * profiles with redundancy (copies, parity)
4176 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4177 if (btrfs_raid_array[i].ncopies >= 2 ||
4178 btrfs_raid_array[i].tolerated_failures >= 1)
4179 allowed |= btrfs_raid_array[i].bg_flag;
4182 seq = read_seqbegin(&fs_info->profiles_lock);
4184 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4185 (fs_info->avail_system_alloc_bits & allowed) &&
4186 !(bctl->sys.target & allowed)) ||
4187 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4188 (fs_info->avail_metadata_alloc_bits & allowed) &&
4189 !(bctl->meta.target & allowed)))
4190 reducing_redundancy = true;
4192 reducing_redundancy = false;
4194 /* if we're not converting, the target field is uninitialized */
4195 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4196 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4197 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4198 bctl->data.target : fs_info->avail_data_alloc_bits;
4199 } while (read_seqretry(&fs_info->profiles_lock, seq));
4201 if (reducing_redundancy) {
4202 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4204 "balance: force reducing metadata redundancy");
4207 "balance: reduces metadata redundancy, use --force if you want this");
4213 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4214 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4216 "balance: metadata profile %s has lower redundancy than data profile %s",
4217 btrfs_bg_type_to_raid_name(meta_target),
4218 btrfs_bg_type_to_raid_name(data_target));
4221 if (fs_info->send_in_progress) {
4222 btrfs_warn_rl(fs_info,
4223 "cannot run balance while send operations are in progress (%d in progress)",
4224 fs_info->send_in_progress);
4229 ret = insert_balance_item(fs_info, bctl);
4230 if (ret && ret != -EEXIST)
4233 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4234 BUG_ON(ret == -EEXIST);
4235 BUG_ON(fs_info->balance_ctl);
4236 spin_lock(&fs_info->balance_lock);
4237 fs_info->balance_ctl = bctl;
4238 spin_unlock(&fs_info->balance_lock);
4240 BUG_ON(ret != -EEXIST);
4241 spin_lock(&fs_info->balance_lock);
4242 update_balance_args(bctl);
4243 spin_unlock(&fs_info->balance_lock);
4246 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4247 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4248 describe_balance_start_or_resume(fs_info);
4249 mutex_unlock(&fs_info->balance_mutex);
4251 ret = __btrfs_balance(fs_info);
4253 mutex_lock(&fs_info->balance_mutex);
4254 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4255 btrfs_info(fs_info, "balance: paused");
4257 * Balance can be canceled by:
4259 * - Regular cancel request
4260 * Then ret == -ECANCELED and balance_cancel_req > 0
4262 * - Fatal signal to "btrfs" process
4263 * Either the signal caught by wait_reserve_ticket() and callers
4264 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4266 * Either way, in this case balance_cancel_req = 0, and
4267 * ret == -EINTR or ret == -ECANCELED.
4269 * So here we only check the return value to catch canceled balance.
4271 else if (ret == -ECANCELED || ret == -EINTR)
4272 btrfs_info(fs_info, "balance: canceled");
4274 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4276 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4279 memset(bargs, 0, sizeof(*bargs));
4280 btrfs_update_ioctl_balance_args(fs_info, bargs);
4283 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4284 balance_need_close(fs_info)) {
4285 reset_balance_state(fs_info);
4286 btrfs_exclop_finish(fs_info);
4289 wake_up(&fs_info->balance_wait_q);
4293 if (bctl->flags & BTRFS_BALANCE_RESUME)
4294 reset_balance_state(fs_info);
4297 btrfs_exclop_finish(fs_info);
4302 static int balance_kthread(void *data)
4304 struct btrfs_fs_info *fs_info = data;
4307 sb_start_write(fs_info->sb);
4308 mutex_lock(&fs_info->balance_mutex);
4309 if (fs_info->balance_ctl)
4310 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4311 mutex_unlock(&fs_info->balance_mutex);
4312 sb_end_write(fs_info->sb);
4317 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4319 struct task_struct *tsk;
4321 mutex_lock(&fs_info->balance_mutex);
4322 if (!fs_info->balance_ctl) {
4323 mutex_unlock(&fs_info->balance_mutex);
4326 mutex_unlock(&fs_info->balance_mutex);
4328 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4329 btrfs_info(fs_info, "balance: resume skipped");
4334 * A ro->rw remount sequence should continue with the paused balance
4335 * regardless of who pauses it, system or the user as of now, so set
4338 spin_lock(&fs_info->balance_lock);
4339 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4340 spin_unlock(&fs_info->balance_lock);
4342 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4343 return PTR_ERR_OR_ZERO(tsk);
4346 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4348 struct btrfs_balance_control *bctl;
4349 struct btrfs_balance_item *item;
4350 struct btrfs_disk_balance_args disk_bargs;
4351 struct btrfs_path *path;
4352 struct extent_buffer *leaf;
4353 struct btrfs_key key;
4356 path = btrfs_alloc_path();
4360 key.objectid = BTRFS_BALANCE_OBJECTID;
4361 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4364 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4367 if (ret > 0) { /* ret = -ENOENT; */
4372 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4378 leaf = path->nodes[0];
4379 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4381 bctl->flags = btrfs_balance_flags(leaf, item);
4382 bctl->flags |= BTRFS_BALANCE_RESUME;
4384 btrfs_balance_data(leaf, item, &disk_bargs);
4385 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4386 btrfs_balance_meta(leaf, item, &disk_bargs);
4387 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4388 btrfs_balance_sys(leaf, item, &disk_bargs);
4389 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4392 * This should never happen, as the paused balance state is recovered
4393 * during mount without any chance of other exclusive ops to collide.
4395 * This gives the exclusive op status to balance and keeps in paused
4396 * state until user intervention (cancel or umount). If the ownership
4397 * cannot be assigned, show a message but do not fail. The balance
4398 * is in a paused state and must have fs_info::balance_ctl properly
4401 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
4403 "balance: cannot set exclusive op status, resume manually");
4405 btrfs_release_path(path);
4407 mutex_lock(&fs_info->balance_mutex);
4408 BUG_ON(fs_info->balance_ctl);
4409 spin_lock(&fs_info->balance_lock);
4410 fs_info->balance_ctl = bctl;
4411 spin_unlock(&fs_info->balance_lock);
4412 mutex_unlock(&fs_info->balance_mutex);
4414 btrfs_free_path(path);
4418 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4422 mutex_lock(&fs_info->balance_mutex);
4423 if (!fs_info->balance_ctl) {
4424 mutex_unlock(&fs_info->balance_mutex);
4428 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4429 atomic_inc(&fs_info->balance_pause_req);
4430 mutex_unlock(&fs_info->balance_mutex);
4432 wait_event(fs_info->balance_wait_q,
4433 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4435 mutex_lock(&fs_info->balance_mutex);
4436 /* we are good with balance_ctl ripped off from under us */
4437 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4438 atomic_dec(&fs_info->balance_pause_req);
4443 mutex_unlock(&fs_info->balance_mutex);
4447 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4449 mutex_lock(&fs_info->balance_mutex);
4450 if (!fs_info->balance_ctl) {
4451 mutex_unlock(&fs_info->balance_mutex);
4456 * A paused balance with the item stored on disk can be resumed at
4457 * mount time if the mount is read-write. Otherwise it's still paused
4458 * and we must not allow cancelling as it deletes the item.
4460 if (sb_rdonly(fs_info->sb)) {
4461 mutex_unlock(&fs_info->balance_mutex);
4465 atomic_inc(&fs_info->balance_cancel_req);
4467 * if we are running just wait and return, balance item is
4468 * deleted in btrfs_balance in this case
4470 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4471 mutex_unlock(&fs_info->balance_mutex);
4472 wait_event(fs_info->balance_wait_q,
4473 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4474 mutex_lock(&fs_info->balance_mutex);
4476 mutex_unlock(&fs_info->balance_mutex);
4478 * Lock released to allow other waiters to continue, we'll
4479 * reexamine the status again.
4481 mutex_lock(&fs_info->balance_mutex);
4483 if (fs_info->balance_ctl) {
4484 reset_balance_state(fs_info);
4485 btrfs_exclop_finish(fs_info);
4486 btrfs_info(fs_info, "balance: canceled");
4490 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4491 atomic_dec(&fs_info->balance_cancel_req);
4492 mutex_unlock(&fs_info->balance_mutex);
4496 int btrfs_uuid_scan_kthread(void *data)
4498 struct btrfs_fs_info *fs_info = data;
4499 struct btrfs_root *root = fs_info->tree_root;
4500 struct btrfs_key key;
4501 struct btrfs_path *path = NULL;
4503 struct extent_buffer *eb;
4505 struct btrfs_root_item root_item;
4507 struct btrfs_trans_handle *trans = NULL;
4508 bool closing = false;
4510 path = btrfs_alloc_path();
4517 key.type = BTRFS_ROOT_ITEM_KEY;
4521 if (btrfs_fs_closing(fs_info)) {
4525 ret = btrfs_search_forward(root, &key, path,
4526 BTRFS_OLDEST_GENERATION);
4533 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4534 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4535 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4536 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4539 eb = path->nodes[0];
4540 slot = path->slots[0];
4541 item_size = btrfs_item_size_nr(eb, slot);
4542 if (item_size < sizeof(root_item))
4545 read_extent_buffer(eb, &root_item,
4546 btrfs_item_ptr_offset(eb, slot),
4547 (int)sizeof(root_item));
4548 if (btrfs_root_refs(&root_item) == 0)
4551 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4552 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4556 btrfs_release_path(path);
4558 * 1 - subvol uuid item
4559 * 1 - received_subvol uuid item
4561 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4562 if (IS_ERR(trans)) {
4563 ret = PTR_ERR(trans);
4571 btrfs_release_path(path);
4572 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4573 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4574 BTRFS_UUID_KEY_SUBVOL,
4577 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4583 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4584 ret = btrfs_uuid_tree_add(trans,
4585 root_item.received_uuid,
4586 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4589 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4596 btrfs_release_path(path);
4598 ret = btrfs_end_transaction(trans);
4604 if (key.offset < (u64)-1) {
4606 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4608 key.type = BTRFS_ROOT_ITEM_KEY;
4609 } else if (key.objectid < (u64)-1) {
4611 key.type = BTRFS_ROOT_ITEM_KEY;
4620 btrfs_free_path(path);
4621 if (trans && !IS_ERR(trans))
4622 btrfs_end_transaction(trans);
4624 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4626 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4627 up(&fs_info->uuid_tree_rescan_sem);
4631 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4633 struct btrfs_trans_handle *trans;
4634 struct btrfs_root *tree_root = fs_info->tree_root;
4635 struct btrfs_root *uuid_root;
4636 struct task_struct *task;
4643 trans = btrfs_start_transaction(tree_root, 2);
4645 return PTR_ERR(trans);
4647 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4648 if (IS_ERR(uuid_root)) {
4649 ret = PTR_ERR(uuid_root);
4650 btrfs_abort_transaction(trans, ret);
4651 btrfs_end_transaction(trans);
4655 fs_info->uuid_root = uuid_root;
4657 ret = btrfs_commit_transaction(trans);
4661 down(&fs_info->uuid_tree_rescan_sem);
4662 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4664 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4665 btrfs_warn(fs_info, "failed to start uuid_scan task");
4666 up(&fs_info->uuid_tree_rescan_sem);
4667 return PTR_ERR(task);
4674 * shrinking a device means finding all of the device extents past
4675 * the new size, and then following the back refs to the chunks.
4676 * The chunk relocation code actually frees the device extent
4678 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4680 struct btrfs_fs_info *fs_info = device->fs_info;
4681 struct btrfs_root *root = fs_info->dev_root;
4682 struct btrfs_trans_handle *trans;
4683 struct btrfs_dev_extent *dev_extent = NULL;
4684 struct btrfs_path *path;
4690 bool retried = false;
4691 struct extent_buffer *l;
4692 struct btrfs_key key;
4693 struct btrfs_super_block *super_copy = fs_info->super_copy;
4694 u64 old_total = btrfs_super_total_bytes(super_copy);
4695 u64 old_size = btrfs_device_get_total_bytes(device);
4699 new_size = round_down(new_size, fs_info->sectorsize);
4701 diff = round_down(old_size - new_size, fs_info->sectorsize);
4703 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4706 path = btrfs_alloc_path();
4710 path->reada = READA_BACK;
4712 trans = btrfs_start_transaction(root, 0);
4713 if (IS_ERR(trans)) {
4714 btrfs_free_path(path);
4715 return PTR_ERR(trans);
4718 mutex_lock(&fs_info->chunk_mutex);
4720 btrfs_device_set_total_bytes(device, new_size);
4721 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4722 device->fs_devices->total_rw_bytes -= diff;
4723 atomic64_sub(diff, &fs_info->free_chunk_space);
4727 * Once the device's size has been set to the new size, ensure all
4728 * in-memory chunks are synced to disk so that the loop below sees them
4729 * and relocates them accordingly.
4731 if (contains_pending_extent(device, &start, diff)) {
4732 mutex_unlock(&fs_info->chunk_mutex);
4733 ret = btrfs_commit_transaction(trans);
4737 mutex_unlock(&fs_info->chunk_mutex);
4738 btrfs_end_transaction(trans);
4742 key.objectid = device->devid;
4743 key.offset = (u64)-1;
4744 key.type = BTRFS_DEV_EXTENT_KEY;
4747 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4748 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4750 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4754 ret = btrfs_previous_item(root, path, 0, key.type);
4756 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4761 btrfs_release_path(path);
4766 slot = path->slots[0];
4767 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4769 if (key.objectid != device->devid) {
4770 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4771 btrfs_release_path(path);
4775 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4776 length = btrfs_dev_extent_length(l, dev_extent);
4778 if (key.offset + length <= new_size) {
4779 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4780 btrfs_release_path(path);
4784 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4785 btrfs_release_path(path);
4788 * We may be relocating the only data chunk we have,
4789 * which could potentially end up with losing data's
4790 * raid profile, so lets allocate an empty one in
4793 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4795 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4799 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4800 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4801 if (ret == -ENOSPC) {
4804 if (ret == -ETXTBSY) {
4806 "could not shrink block group %llu due to active swapfile",
4811 } while (key.offset-- > 0);
4813 if (failed && !retried) {
4817 } else if (failed && retried) {
4822 /* Shrinking succeeded, else we would be at "done". */
4823 trans = btrfs_start_transaction(root, 0);
4824 if (IS_ERR(trans)) {
4825 ret = PTR_ERR(trans);
4829 mutex_lock(&fs_info->chunk_mutex);
4830 /* Clear all state bits beyond the shrunk device size */
4831 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4834 btrfs_device_set_disk_total_bytes(device, new_size);
4835 if (list_empty(&device->post_commit_list))
4836 list_add_tail(&device->post_commit_list,
4837 &trans->transaction->dev_update_list);
4839 WARN_ON(diff > old_total);
4840 btrfs_set_super_total_bytes(super_copy,
4841 round_down(old_total - diff, fs_info->sectorsize));
4842 mutex_unlock(&fs_info->chunk_mutex);
4844 /* Now btrfs_update_device() will change the on-disk size. */
4845 ret = btrfs_update_device(trans, device);
4847 btrfs_abort_transaction(trans, ret);
4848 btrfs_end_transaction(trans);
4850 ret = btrfs_commit_transaction(trans);
4853 btrfs_free_path(path);
4855 mutex_lock(&fs_info->chunk_mutex);
4856 btrfs_device_set_total_bytes(device, old_size);
4857 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4858 device->fs_devices->total_rw_bytes += diff;
4859 atomic64_add(diff, &fs_info->free_chunk_space);
4860 mutex_unlock(&fs_info->chunk_mutex);
4865 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4866 struct btrfs_key *key,
4867 struct btrfs_chunk *chunk, int item_size)
4869 struct btrfs_super_block *super_copy = fs_info->super_copy;
4870 struct btrfs_disk_key disk_key;
4874 mutex_lock(&fs_info->chunk_mutex);
4875 array_size = btrfs_super_sys_array_size(super_copy);
4876 if (array_size + item_size + sizeof(disk_key)
4877 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4878 mutex_unlock(&fs_info->chunk_mutex);
4882 ptr = super_copy->sys_chunk_array + array_size;
4883 btrfs_cpu_key_to_disk(&disk_key, key);
4884 memcpy(ptr, &disk_key, sizeof(disk_key));
4885 ptr += sizeof(disk_key);
4886 memcpy(ptr, chunk, item_size);
4887 item_size += sizeof(disk_key);
4888 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4889 mutex_unlock(&fs_info->chunk_mutex);
4895 * sort the devices in descending order by max_avail, total_avail
4897 static int btrfs_cmp_device_info(const void *a, const void *b)
4899 const struct btrfs_device_info *di_a = a;
4900 const struct btrfs_device_info *di_b = b;
4902 if (di_a->max_avail > di_b->max_avail)
4904 if (di_a->max_avail < di_b->max_avail)
4906 if (di_a->total_avail > di_b->total_avail)
4908 if (di_a->total_avail < di_b->total_avail)
4913 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4915 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4918 btrfs_set_fs_incompat(info, RAID56);
4921 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
4923 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
4926 btrfs_set_fs_incompat(info, RAID1C34);
4930 * Structure used internally for __btrfs_alloc_chunk() function.
4931 * Wraps needed parameters.
4933 struct alloc_chunk_ctl {
4936 /* Total number of stripes to allocate */
4938 /* sub_stripes info for map */
4940 /* Stripes per device */
4942 /* Maximum number of devices to use */
4944 /* Minimum number of devices to use */
4946 /* ndevs has to be a multiple of this */
4948 /* Number of copies */
4950 /* Number of stripes worth of bytes to store parity information */
4952 u64 max_stripe_size;
4960 static void init_alloc_chunk_ctl_policy_regular(
4961 struct btrfs_fs_devices *fs_devices,
4962 struct alloc_chunk_ctl *ctl)
4964 u64 type = ctl->type;
4966 if (type & BTRFS_BLOCK_GROUP_DATA) {
4967 ctl->max_stripe_size = SZ_1G;
4968 ctl->max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4969 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4970 /* For larger filesystems, use larger metadata chunks */
4971 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4972 ctl->max_stripe_size = SZ_1G;
4974 ctl->max_stripe_size = SZ_256M;
4975 ctl->max_chunk_size = ctl->max_stripe_size;
4976 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4977 ctl->max_stripe_size = SZ_32M;
4978 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
4979 ctl->devs_max = min_t(int, ctl->devs_max,
4980 BTRFS_MAX_DEVS_SYS_CHUNK);
4985 /* We don't want a chunk larger than 10% of writable space */
4986 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4987 ctl->max_chunk_size);
4988 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
4991 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
4992 struct alloc_chunk_ctl *ctl)
4994 int index = btrfs_bg_flags_to_raid_index(ctl->type);
4996 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
4997 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
4998 ctl->devs_max = btrfs_raid_array[index].devs_max;
5000 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5001 ctl->devs_min = btrfs_raid_array[index].devs_min;
5002 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5003 ctl->ncopies = btrfs_raid_array[index].ncopies;
5004 ctl->nparity = btrfs_raid_array[index].nparity;
5007 switch (fs_devices->chunk_alloc_policy) {
5008 case BTRFS_CHUNK_ALLOC_REGULAR:
5009 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5016 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5017 struct alloc_chunk_ctl *ctl,
5018 struct btrfs_device_info *devices_info)
5020 struct btrfs_fs_info *info = fs_devices->fs_info;
5021 struct btrfs_device *device;
5023 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5030 * in the first pass through the devices list, we gather information
5031 * about the available holes on each device.
5033 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5034 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5036 "BTRFS: read-only device in alloc_list\n");
5040 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5041 &device->dev_state) ||
5042 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5045 if (device->total_bytes > device->bytes_used)
5046 total_avail = device->total_bytes - device->bytes_used;
5050 /* If there is no space on this device, skip it. */
5051 if (total_avail < ctl->dev_extent_min)
5054 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5056 if (ret && ret != -ENOSPC)
5060 max_avail = dev_extent_want;
5062 if (max_avail < ctl->dev_extent_min) {
5063 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5065 "%s: devid %llu has no free space, have=%llu want=%llu",
5066 __func__, device->devid, max_avail,
5067 ctl->dev_extent_min);
5071 if (ndevs == fs_devices->rw_devices) {
5072 WARN(1, "%s: found more than %llu devices\n",
5073 __func__, fs_devices->rw_devices);
5076 devices_info[ndevs].dev_offset = dev_offset;
5077 devices_info[ndevs].max_avail = max_avail;
5078 devices_info[ndevs].total_avail = total_avail;
5079 devices_info[ndevs].dev = device;
5085 * now sort the devices by hole size / available space
5087 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5088 btrfs_cmp_device_info, NULL);
5093 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5094 struct btrfs_device_info *devices_info)
5096 /* Number of stripes that count for block group size */
5100 * The primary goal is to maximize the number of stripes, so use as
5101 * many devices as possible, even if the stripes are not maximum sized.
5103 * The DUP profile stores more than one stripe per device, the
5104 * max_avail is the total size so we have to adjust.
5106 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5108 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5110 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5111 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5114 * Use the number of data stripes to figure out how big this chunk is
5115 * really going to be in terms of logical address space, and compare
5116 * that answer with the max chunk size. If it's higher, we try to
5117 * reduce stripe_size.
5119 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5121 * Reduce stripe_size, round it up to a 16MB boundary again and
5122 * then use it, unless it ends up being even bigger than the
5123 * previous value we had already.
5125 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5126 data_stripes), SZ_16M),
5130 /* Align to BTRFS_STRIPE_LEN */
5131 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5132 ctl->chunk_size = ctl->stripe_size * data_stripes;
5137 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5138 struct alloc_chunk_ctl *ctl,
5139 struct btrfs_device_info *devices_info)
5141 struct btrfs_fs_info *info = fs_devices->fs_info;
5144 * Round down to number of usable stripes, devs_increment can be any
5145 * number so we can't use round_down() that requires power of 2, while
5146 * rounddown is safe.
5148 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5150 if (ctl->ndevs < ctl->devs_min) {
5151 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5153 "%s: not enough devices with free space: have=%d minimum required=%d",
5154 __func__, ctl->ndevs, ctl->devs_min);
5159 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5161 switch (fs_devices->chunk_alloc_policy) {
5162 case BTRFS_CHUNK_ALLOC_REGULAR:
5163 return decide_stripe_size_regular(ctl, devices_info);
5169 static int create_chunk(struct btrfs_trans_handle *trans,
5170 struct alloc_chunk_ctl *ctl,
5171 struct btrfs_device_info *devices_info)
5173 struct btrfs_fs_info *info = trans->fs_info;
5174 struct map_lookup *map = NULL;
5175 struct extent_map_tree *em_tree;
5176 struct extent_map *em;
5177 u64 start = ctl->start;
5178 u64 type = ctl->type;
5183 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5186 map->num_stripes = ctl->num_stripes;
5188 for (i = 0; i < ctl->ndevs; ++i) {
5189 for (j = 0; j < ctl->dev_stripes; ++j) {
5190 int s = i * ctl->dev_stripes + j;
5191 map->stripes[s].dev = devices_info[i].dev;
5192 map->stripes[s].physical = devices_info[i].dev_offset +
5193 j * ctl->stripe_size;
5196 map->stripe_len = BTRFS_STRIPE_LEN;
5197 map->io_align = BTRFS_STRIPE_LEN;
5198 map->io_width = BTRFS_STRIPE_LEN;
5200 map->sub_stripes = ctl->sub_stripes;
5202 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5204 em = alloc_extent_map();
5209 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5210 em->map_lookup = map;
5212 em->len = ctl->chunk_size;
5213 em->block_start = 0;
5214 em->block_len = em->len;
5215 em->orig_block_len = ctl->stripe_size;
5217 em_tree = &info->mapping_tree;
5218 write_lock(&em_tree->lock);
5219 ret = add_extent_mapping(em_tree, em, 0);
5221 write_unlock(&em_tree->lock);
5222 free_extent_map(em);
5225 write_unlock(&em_tree->lock);
5227 ret = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5229 goto error_del_extent;
5231 for (i = 0; i < map->num_stripes; i++) {
5232 struct btrfs_device *dev = map->stripes[i].dev;
5234 btrfs_device_set_bytes_used(dev,
5235 dev->bytes_used + ctl->stripe_size);
5236 if (list_empty(&dev->post_commit_list))
5237 list_add_tail(&dev->post_commit_list,
5238 &trans->transaction->dev_update_list);
5241 atomic64_sub(ctl->stripe_size * map->num_stripes,
5242 &info->free_chunk_space);
5244 free_extent_map(em);
5245 check_raid56_incompat_flag(info, type);
5246 check_raid1c34_incompat_flag(info, type);
5251 write_lock(&em_tree->lock);
5252 remove_extent_mapping(em_tree, em);
5253 write_unlock(&em_tree->lock);
5255 /* One for our allocation */
5256 free_extent_map(em);
5257 /* One for the tree reference */
5258 free_extent_map(em);
5263 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5265 struct btrfs_fs_info *info = trans->fs_info;
5266 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5267 struct btrfs_device_info *devices_info = NULL;
5268 struct alloc_chunk_ctl ctl;
5271 lockdep_assert_held(&info->chunk_mutex);
5273 if (!alloc_profile_is_valid(type, 0)) {
5278 if (list_empty(&fs_devices->alloc_list)) {
5279 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5280 btrfs_debug(info, "%s: no writable device", __func__);
5284 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5285 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5290 ctl.start = find_next_chunk(info);
5292 init_alloc_chunk_ctl(fs_devices, &ctl);
5294 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5299 ret = gather_device_info(fs_devices, &ctl, devices_info);
5303 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5307 ret = create_chunk(trans, &ctl, devices_info);
5310 kfree(devices_info);
5315 * Chunk allocation falls into two parts. The first part does work
5316 * that makes the new allocated chunk usable, but does not do any operation
5317 * that modifies the chunk tree. The second part does the work that
5318 * requires modifying the chunk tree. This division is important for the
5319 * bootstrap process of adding storage to a seed btrfs.
5321 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5322 u64 chunk_offset, u64 chunk_size)
5324 struct btrfs_fs_info *fs_info = trans->fs_info;
5325 struct btrfs_root *extent_root = fs_info->extent_root;
5326 struct btrfs_root *chunk_root = fs_info->chunk_root;
5327 struct btrfs_key key;
5328 struct btrfs_device *device;
5329 struct btrfs_chunk *chunk;
5330 struct btrfs_stripe *stripe;
5331 struct extent_map *em;
5332 struct map_lookup *map;
5339 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5343 map = em->map_lookup;
5344 item_size = btrfs_chunk_item_size(map->num_stripes);
5345 stripe_size = em->orig_block_len;
5347 chunk = kzalloc(item_size, GFP_NOFS);
5354 * Take the device list mutex to prevent races with the final phase of
5355 * a device replace operation that replaces the device object associated
5356 * with the map's stripes, because the device object's id can change
5357 * at any time during that final phase of the device replace operation
5358 * (dev-replace.c:btrfs_dev_replace_finishing()).
5360 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5361 for (i = 0; i < map->num_stripes; i++) {
5362 device = map->stripes[i].dev;
5363 dev_offset = map->stripes[i].physical;
5365 ret = btrfs_update_device(trans, device);
5368 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5369 dev_offset, stripe_size);
5374 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5378 stripe = &chunk->stripe;
5379 for (i = 0; i < map->num_stripes; i++) {
5380 device = map->stripes[i].dev;
5381 dev_offset = map->stripes[i].physical;
5383 btrfs_set_stack_stripe_devid(stripe, device->devid);
5384 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5385 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5388 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5390 btrfs_set_stack_chunk_length(chunk, chunk_size);
5391 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5392 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5393 btrfs_set_stack_chunk_type(chunk, map->type);
5394 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5395 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5396 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5397 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5398 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5400 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5401 key.type = BTRFS_CHUNK_ITEM_KEY;
5402 key.offset = chunk_offset;
5404 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5405 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5407 * TODO: Cleanup of inserted chunk root in case of
5410 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5415 free_extent_map(em);
5419 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5421 struct btrfs_fs_info *fs_info = trans->fs_info;
5425 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5426 ret = btrfs_alloc_chunk(trans, alloc_profile);
5430 alloc_profile = btrfs_system_alloc_profile(fs_info);
5431 ret = btrfs_alloc_chunk(trans, alloc_profile);
5435 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5437 const int index = btrfs_bg_flags_to_raid_index(map->type);
5439 return btrfs_raid_array[index].tolerated_failures;
5442 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5444 struct extent_map *em;
5445 struct map_lookup *map;
5450 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5454 map = em->map_lookup;
5455 for (i = 0; i < map->num_stripes; i++) {
5456 if (test_bit(BTRFS_DEV_STATE_MISSING,
5457 &map->stripes[i].dev->dev_state)) {
5461 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5462 &map->stripes[i].dev->dev_state)) {
5469 * If the number of missing devices is larger than max errors,
5470 * we can not write the data into that chunk successfully, so
5473 if (miss_ndevs > btrfs_chunk_max_errors(map))
5476 free_extent_map(em);
5480 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5482 struct extent_map *em;
5485 write_lock(&tree->lock);
5486 em = lookup_extent_mapping(tree, 0, (u64)-1);
5488 remove_extent_mapping(tree, em);
5489 write_unlock(&tree->lock);
5493 free_extent_map(em);
5494 /* once for the tree */
5495 free_extent_map(em);
5499 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5501 struct extent_map *em;
5502 struct map_lookup *map;
5505 em = btrfs_get_chunk_map(fs_info, logical, len);
5508 * We could return errors for these cases, but that could get
5509 * ugly and we'd probably do the same thing which is just not do
5510 * anything else and exit, so return 1 so the callers don't try
5511 * to use other copies.
5515 map = em->map_lookup;
5516 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5517 ret = map->num_stripes;
5518 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5519 ret = map->sub_stripes;
5520 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5522 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5524 * There could be two corrupted data stripes, we need
5525 * to loop retry in order to rebuild the correct data.
5527 * Fail a stripe at a time on every retry except the
5528 * stripe under reconstruction.
5530 ret = map->num_stripes;
5533 free_extent_map(em);
5535 down_read(&fs_info->dev_replace.rwsem);
5536 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5537 fs_info->dev_replace.tgtdev)
5539 up_read(&fs_info->dev_replace.rwsem);
5544 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5547 struct extent_map *em;
5548 struct map_lookup *map;
5549 unsigned long len = fs_info->sectorsize;
5551 em = btrfs_get_chunk_map(fs_info, logical, len);
5553 if (!WARN_ON(IS_ERR(em))) {
5554 map = em->map_lookup;
5555 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5556 len = map->stripe_len * nr_data_stripes(map);
5557 free_extent_map(em);
5562 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5564 struct extent_map *em;
5565 struct map_lookup *map;
5568 em = btrfs_get_chunk_map(fs_info, logical, len);
5570 if(!WARN_ON(IS_ERR(em))) {
5571 map = em->map_lookup;
5572 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5574 free_extent_map(em);
5579 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5580 struct map_lookup *map, int first,
5581 int dev_replace_is_ongoing)
5585 int preferred_mirror;
5587 struct btrfs_device *srcdev;
5590 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5592 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5593 num_stripes = map->sub_stripes;
5595 num_stripes = map->num_stripes;
5597 preferred_mirror = first + current->pid % num_stripes;
5599 if (dev_replace_is_ongoing &&
5600 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5601 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5602 srcdev = fs_info->dev_replace.srcdev;
5607 * try to avoid the drive that is the source drive for a
5608 * dev-replace procedure, only choose it if no other non-missing
5609 * mirror is available
5611 for (tolerance = 0; tolerance < 2; tolerance++) {
5612 if (map->stripes[preferred_mirror].dev->bdev &&
5613 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5614 return preferred_mirror;
5615 for (i = first; i < first + num_stripes; i++) {
5616 if (map->stripes[i].dev->bdev &&
5617 (tolerance || map->stripes[i].dev != srcdev))
5622 /* we couldn't find one that doesn't fail. Just return something
5623 * and the io error handling code will clean up eventually
5625 return preferred_mirror;
5628 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5629 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5636 for (i = 0; i < num_stripes - 1; i++) {
5637 /* Swap if parity is on a smaller index */
5638 if (bbio->raid_map[i] > bbio->raid_map[i + 1]) {
5639 swap(bbio->stripes[i], bbio->stripes[i + 1]);
5640 swap(bbio->raid_map[i], bbio->raid_map[i + 1]);
5647 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5649 struct btrfs_bio *bbio = kzalloc(
5650 /* the size of the btrfs_bio */
5651 sizeof(struct btrfs_bio) +
5652 /* plus the variable array for the stripes */
5653 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5654 /* plus the variable array for the tgt dev */
5655 sizeof(int) * (real_stripes) +
5657 * plus the raid_map, which includes both the tgt dev
5660 sizeof(u64) * (total_stripes),
5661 GFP_NOFS|__GFP_NOFAIL);
5663 atomic_set(&bbio->error, 0);
5664 refcount_set(&bbio->refs, 1);
5666 bbio->tgtdev_map = (int *)(bbio->stripes + total_stripes);
5667 bbio->raid_map = (u64 *)(bbio->tgtdev_map + real_stripes);
5672 void btrfs_get_bbio(struct btrfs_bio *bbio)
5674 WARN_ON(!refcount_read(&bbio->refs));
5675 refcount_inc(&bbio->refs);
5678 void btrfs_put_bbio(struct btrfs_bio *bbio)
5682 if (refcount_dec_and_test(&bbio->refs))
5686 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5688 * Please note that, discard won't be sent to target device of device
5691 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5692 u64 logical, u64 *length_ret,
5693 struct btrfs_bio **bbio_ret)
5695 struct extent_map *em;
5696 struct map_lookup *map;
5697 struct btrfs_bio *bbio;
5698 u64 length = *length_ret;
5702 u64 stripe_end_offset;
5709 u32 sub_stripes = 0;
5710 u64 stripes_per_dev = 0;
5711 u32 remaining_stripes = 0;
5712 u32 last_stripe = 0;
5716 /* discard always return a bbio */
5719 em = btrfs_get_chunk_map(fs_info, logical, length);
5723 map = em->map_lookup;
5724 /* we don't discard raid56 yet */
5725 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5730 offset = logical - em->start;
5731 length = min_t(u64, em->start + em->len - logical, length);
5732 *length_ret = length;
5734 stripe_len = map->stripe_len;
5736 * stripe_nr counts the total number of stripes we have to stride
5737 * to get to this block
5739 stripe_nr = div64_u64(offset, stripe_len);
5741 /* stripe_offset is the offset of this block in its stripe */
5742 stripe_offset = offset - stripe_nr * stripe_len;
5744 stripe_nr_end = round_up(offset + length, map->stripe_len);
5745 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5746 stripe_cnt = stripe_nr_end - stripe_nr;
5747 stripe_end_offset = stripe_nr_end * map->stripe_len -
5750 * after this, stripe_nr is the number of stripes on this
5751 * device we have to walk to find the data, and stripe_index is
5752 * the number of our device in the stripe array
5756 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5757 BTRFS_BLOCK_GROUP_RAID10)) {
5758 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5761 sub_stripes = map->sub_stripes;
5763 factor = map->num_stripes / sub_stripes;
5764 num_stripes = min_t(u64, map->num_stripes,
5765 sub_stripes * stripe_cnt);
5766 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5767 stripe_index *= sub_stripes;
5768 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5769 &remaining_stripes);
5770 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5771 last_stripe *= sub_stripes;
5772 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5773 BTRFS_BLOCK_GROUP_DUP)) {
5774 num_stripes = map->num_stripes;
5776 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5780 bbio = alloc_btrfs_bio(num_stripes, 0);
5786 for (i = 0; i < num_stripes; i++) {
5787 bbio->stripes[i].physical =
5788 map->stripes[stripe_index].physical +
5789 stripe_offset + stripe_nr * map->stripe_len;
5790 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5792 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5793 BTRFS_BLOCK_GROUP_RAID10)) {
5794 bbio->stripes[i].length = stripes_per_dev *
5797 if (i / sub_stripes < remaining_stripes)
5798 bbio->stripes[i].length +=
5802 * Special for the first stripe and
5805 * |-------|...|-------|
5809 if (i < sub_stripes)
5810 bbio->stripes[i].length -=
5813 if (stripe_index >= last_stripe &&
5814 stripe_index <= (last_stripe +
5816 bbio->stripes[i].length -=
5819 if (i == sub_stripes - 1)
5822 bbio->stripes[i].length = length;
5826 if (stripe_index == map->num_stripes) {
5833 bbio->map_type = map->type;
5834 bbio->num_stripes = num_stripes;
5836 free_extent_map(em);
5841 * In dev-replace case, for repair case (that's the only case where the mirror
5842 * is selected explicitly when calling btrfs_map_block), blocks left of the
5843 * left cursor can also be read from the target drive.
5845 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5847 * For READ, it also needs to be supported using the same mirror number.
5849 * If the requested block is not left of the left cursor, EIO is returned. This
5850 * can happen because btrfs_num_copies() returns one more in the dev-replace
5853 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5854 u64 logical, u64 length,
5855 u64 srcdev_devid, int *mirror_num,
5858 struct btrfs_bio *bbio = NULL;
5860 int index_srcdev = 0;
5862 u64 physical_of_found = 0;
5866 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5867 logical, &length, &bbio, 0, 0);
5869 ASSERT(bbio == NULL);
5873 num_stripes = bbio->num_stripes;
5874 if (*mirror_num > num_stripes) {
5876 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5877 * that means that the requested area is not left of the left
5880 btrfs_put_bbio(bbio);
5885 * process the rest of the function using the mirror_num of the source
5886 * drive. Therefore look it up first. At the end, patch the device
5887 * pointer to the one of the target drive.
5889 for (i = 0; i < num_stripes; i++) {
5890 if (bbio->stripes[i].dev->devid != srcdev_devid)
5894 * In case of DUP, in order to keep it simple, only add the
5895 * mirror with the lowest physical address
5898 physical_of_found <= bbio->stripes[i].physical)
5903 physical_of_found = bbio->stripes[i].physical;
5906 btrfs_put_bbio(bbio);
5912 *mirror_num = index_srcdev + 1;
5913 *physical = physical_of_found;
5917 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5918 struct btrfs_bio **bbio_ret,
5919 struct btrfs_dev_replace *dev_replace,
5920 int *num_stripes_ret, int *max_errors_ret)
5922 struct btrfs_bio *bbio = *bbio_ret;
5923 u64 srcdev_devid = dev_replace->srcdev->devid;
5924 int tgtdev_indexes = 0;
5925 int num_stripes = *num_stripes_ret;
5926 int max_errors = *max_errors_ret;
5929 if (op == BTRFS_MAP_WRITE) {
5930 int index_where_to_add;
5933 * duplicate the write operations while the dev replace
5934 * procedure is running. Since the copying of the old disk to
5935 * the new disk takes place at run time while the filesystem is
5936 * mounted writable, the regular write operations to the old
5937 * disk have to be duplicated to go to the new disk as well.
5939 * Note that device->missing is handled by the caller, and that
5940 * the write to the old disk is already set up in the stripes
5943 index_where_to_add = num_stripes;
5944 for (i = 0; i < num_stripes; i++) {
5945 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5946 /* write to new disk, too */
5947 struct btrfs_bio_stripe *new =
5948 bbio->stripes + index_where_to_add;
5949 struct btrfs_bio_stripe *old =
5952 new->physical = old->physical;
5953 new->length = old->length;
5954 new->dev = dev_replace->tgtdev;
5955 bbio->tgtdev_map[i] = index_where_to_add;
5956 index_where_to_add++;
5961 num_stripes = index_where_to_add;
5962 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5963 int index_srcdev = 0;
5965 u64 physical_of_found = 0;
5968 * During the dev-replace procedure, the target drive can also
5969 * be used to read data in case it is needed to repair a corrupt
5970 * block elsewhere. This is possible if the requested area is
5971 * left of the left cursor. In this area, the target drive is a
5972 * full copy of the source drive.
5974 for (i = 0; i < num_stripes; i++) {
5975 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5977 * In case of DUP, in order to keep it simple,
5978 * only add the mirror with the lowest physical
5982 physical_of_found <=
5983 bbio->stripes[i].physical)
5987 physical_of_found = bbio->stripes[i].physical;
5991 struct btrfs_bio_stripe *tgtdev_stripe =
5992 bbio->stripes + num_stripes;
5994 tgtdev_stripe->physical = physical_of_found;
5995 tgtdev_stripe->length =
5996 bbio->stripes[index_srcdev].length;
5997 tgtdev_stripe->dev = dev_replace->tgtdev;
5998 bbio->tgtdev_map[index_srcdev] = num_stripes;
6005 *num_stripes_ret = num_stripes;
6006 *max_errors_ret = max_errors;
6007 bbio->num_tgtdevs = tgtdev_indexes;
6011 static bool need_full_stripe(enum btrfs_map_op op)
6013 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
6017 * btrfs_get_io_geometry - calculates the geomery of a particular (address, len)
6018 * tuple. This information is used to calculate how big a
6019 * particular bio can get before it straddles a stripe.
6021 * @fs_info - the filesystem
6022 * @logical - address that we want to figure out the geometry of
6023 * @len - the length of IO we are going to perform, starting at @logical
6024 * @op - type of operation - write or read
6025 * @io_geom - pointer used to return values
6027 * Returns < 0 in case a chunk for the given logical address cannot be found,
6028 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
6030 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6031 u64 logical, u64 len, struct btrfs_io_geometry *io_geom)
6033 struct extent_map *em;
6034 struct map_lookup *map;
6039 u64 raid56_full_stripe_start = (u64)-1;
6043 ASSERT(op != BTRFS_MAP_DISCARD);
6045 em = btrfs_get_chunk_map(fs_info, logical, len);
6049 map = em->map_lookup;
6050 /* Offset of this logical address in the chunk */
6051 offset = logical - em->start;
6052 /* Len of a stripe in a chunk */
6053 stripe_len = map->stripe_len;
6054 /* Stripe wher this block falls in */
6055 stripe_nr = div64_u64(offset, stripe_len);
6056 /* Offset of stripe in the chunk */
6057 stripe_offset = stripe_nr * stripe_len;
6058 if (offset < stripe_offset) {
6060 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
6061 stripe_offset, offset, em->start, logical, stripe_len);
6066 /* stripe_offset is the offset of this block in its stripe */
6067 stripe_offset = offset - stripe_offset;
6068 data_stripes = nr_data_stripes(map);
6070 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6071 u64 max_len = stripe_len - stripe_offset;
6074 * In case of raid56, we need to know the stripe aligned start
6076 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6077 unsigned long full_stripe_len = stripe_len * data_stripes;
6078 raid56_full_stripe_start = offset;
6081 * Allow a write of a full stripe, but make sure we
6082 * don't allow straddling of stripes
6084 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6086 raid56_full_stripe_start *= full_stripe_len;
6089 * For writes to RAID[56], allow a full stripeset across
6090 * all disks. For other RAID types and for RAID[56]
6091 * reads, just allow a single stripe (on a single disk).
6093 if (op == BTRFS_MAP_WRITE) {
6094 max_len = stripe_len * data_stripes -
6095 (offset - raid56_full_stripe_start);
6098 len = min_t(u64, em->len - offset, max_len);
6100 len = em->len - offset;
6104 io_geom->offset = offset;
6105 io_geom->stripe_len = stripe_len;
6106 io_geom->stripe_nr = stripe_nr;
6107 io_geom->stripe_offset = stripe_offset;
6108 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6112 free_extent_map(em);
6116 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6117 enum btrfs_map_op op,
6118 u64 logical, u64 *length,
6119 struct btrfs_bio **bbio_ret,
6120 int mirror_num, int need_raid_map)
6122 struct extent_map *em;
6123 struct map_lookup *map;
6133 int tgtdev_indexes = 0;
6134 struct btrfs_bio *bbio = NULL;
6135 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6136 int dev_replace_is_ongoing = 0;
6137 int num_alloc_stripes;
6138 int patch_the_first_stripe_for_dev_replace = 0;
6139 u64 physical_to_patch_in_first_stripe = 0;
6140 u64 raid56_full_stripe_start = (u64)-1;
6141 struct btrfs_io_geometry geom;
6144 ASSERT(op != BTRFS_MAP_DISCARD);
6146 ret = btrfs_get_io_geometry(fs_info, op, logical, *length, &geom);
6150 em = btrfs_get_chunk_map(fs_info, logical, *length);
6151 ASSERT(!IS_ERR(em));
6152 map = em->map_lookup;
6155 stripe_len = geom.stripe_len;
6156 stripe_nr = geom.stripe_nr;
6157 stripe_offset = geom.stripe_offset;
6158 raid56_full_stripe_start = geom.raid56_stripe_offset;
6159 data_stripes = nr_data_stripes(map);
6161 down_read(&dev_replace->rwsem);
6162 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6164 * Hold the semaphore for read during the whole operation, write is
6165 * requested at commit time but must wait.
6167 if (!dev_replace_is_ongoing)
6168 up_read(&dev_replace->rwsem);
6170 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6171 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6172 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6173 dev_replace->srcdev->devid,
6175 &physical_to_patch_in_first_stripe);
6179 patch_the_first_stripe_for_dev_replace = 1;
6180 } else if (mirror_num > map->num_stripes) {
6186 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6187 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6189 if (!need_full_stripe(op))
6191 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6192 if (need_full_stripe(op))
6193 num_stripes = map->num_stripes;
6194 else if (mirror_num)
6195 stripe_index = mirror_num - 1;
6197 stripe_index = find_live_mirror(fs_info, map, 0,
6198 dev_replace_is_ongoing);
6199 mirror_num = stripe_index + 1;
6202 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6203 if (need_full_stripe(op)) {
6204 num_stripes = map->num_stripes;
6205 } else if (mirror_num) {
6206 stripe_index = mirror_num - 1;
6211 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6212 u32 factor = map->num_stripes / map->sub_stripes;
6214 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6215 stripe_index *= map->sub_stripes;
6217 if (need_full_stripe(op))
6218 num_stripes = map->sub_stripes;
6219 else if (mirror_num)
6220 stripe_index += mirror_num - 1;
6222 int old_stripe_index = stripe_index;
6223 stripe_index = find_live_mirror(fs_info, map,
6225 dev_replace_is_ongoing);
6226 mirror_num = stripe_index - old_stripe_index + 1;
6229 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6230 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6231 /* push stripe_nr back to the start of the full stripe */
6232 stripe_nr = div64_u64(raid56_full_stripe_start,
6233 stripe_len * data_stripes);
6235 /* RAID[56] write or recovery. Return all stripes */
6236 num_stripes = map->num_stripes;
6237 max_errors = nr_parity_stripes(map);
6239 *length = map->stripe_len;
6244 * Mirror #0 or #1 means the original data block.
6245 * Mirror #2 is RAID5 parity block.
6246 * Mirror #3 is RAID6 Q block.
6248 stripe_nr = div_u64_rem(stripe_nr,
6249 data_stripes, &stripe_index);
6251 stripe_index = data_stripes + mirror_num - 2;
6253 /* We distribute the parity blocks across stripes */
6254 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6256 if (!need_full_stripe(op) && mirror_num <= 1)
6261 * after this, stripe_nr is the number of stripes on this
6262 * device we have to walk to find the data, and stripe_index is
6263 * the number of our device in the stripe array
6265 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6267 mirror_num = stripe_index + 1;
6269 if (stripe_index >= map->num_stripes) {
6271 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6272 stripe_index, map->num_stripes);
6277 num_alloc_stripes = num_stripes;
6278 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6279 if (op == BTRFS_MAP_WRITE)
6280 num_alloc_stripes <<= 1;
6281 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6282 num_alloc_stripes++;
6283 tgtdev_indexes = num_stripes;
6286 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6292 for (i = 0; i < num_stripes; i++) {
6293 bbio->stripes[i].physical = map->stripes[stripe_index].physical +
6294 stripe_offset + stripe_nr * map->stripe_len;
6295 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
6299 /* build raid_map */
6300 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6301 (need_full_stripe(op) || mirror_num > 1)) {
6305 /* Work out the disk rotation on this stripe-set */
6306 div_u64_rem(stripe_nr, num_stripes, &rot);
6308 /* Fill in the logical address of each stripe */
6309 tmp = stripe_nr * data_stripes;
6310 for (i = 0; i < data_stripes; i++)
6311 bbio->raid_map[(i+rot) % num_stripes] =
6312 em->start + (tmp + i) * map->stripe_len;
6314 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6315 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6316 bbio->raid_map[(i+rot+1) % num_stripes] =
6319 sort_parity_stripes(bbio, num_stripes);
6322 if (need_full_stripe(op))
6323 max_errors = btrfs_chunk_max_errors(map);
6325 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6326 need_full_stripe(op)) {
6327 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6332 bbio->map_type = map->type;
6333 bbio->num_stripes = num_stripes;
6334 bbio->max_errors = max_errors;
6335 bbio->mirror_num = mirror_num;
6338 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6339 * mirror_num == num_stripes + 1 && dev_replace target drive is
6340 * available as a mirror
6342 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6343 WARN_ON(num_stripes > 1);
6344 bbio->stripes[0].dev = dev_replace->tgtdev;
6345 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6346 bbio->mirror_num = map->num_stripes + 1;
6349 if (dev_replace_is_ongoing) {
6350 lockdep_assert_held(&dev_replace->rwsem);
6351 /* Unlock and let waiting writers proceed */
6352 up_read(&dev_replace->rwsem);
6354 free_extent_map(em);
6358 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6359 u64 logical, u64 *length,
6360 struct btrfs_bio **bbio_ret, int mirror_num)
6362 if (op == BTRFS_MAP_DISCARD)
6363 return __btrfs_map_block_for_discard(fs_info, logical,
6366 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6370 /* For Scrub/replace */
6371 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6372 u64 logical, u64 *length,
6373 struct btrfs_bio **bbio_ret)
6375 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6378 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6380 bio->bi_private = bbio->private;
6381 bio->bi_end_io = bbio->end_io;
6384 btrfs_put_bbio(bbio);
6387 static void btrfs_end_bio(struct bio *bio)
6389 struct btrfs_bio *bbio = bio->bi_private;
6390 int is_orig_bio = 0;
6392 if (bio->bi_status) {
6393 atomic_inc(&bbio->error);
6394 if (bio->bi_status == BLK_STS_IOERR ||
6395 bio->bi_status == BLK_STS_TARGET) {
6396 struct btrfs_device *dev = btrfs_io_bio(bio)->device;
6399 if (bio_op(bio) == REQ_OP_WRITE)
6400 btrfs_dev_stat_inc_and_print(dev,
6401 BTRFS_DEV_STAT_WRITE_ERRS);
6402 else if (!(bio->bi_opf & REQ_RAHEAD))
6403 btrfs_dev_stat_inc_and_print(dev,
6404 BTRFS_DEV_STAT_READ_ERRS);
6405 if (bio->bi_opf & REQ_PREFLUSH)
6406 btrfs_dev_stat_inc_and_print(dev,
6407 BTRFS_DEV_STAT_FLUSH_ERRS);
6411 if (bio == bbio->orig_bio)
6414 btrfs_bio_counter_dec(bbio->fs_info);
6416 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6419 bio = bbio->orig_bio;
6422 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6423 /* only send an error to the higher layers if it is
6424 * beyond the tolerance of the btrfs bio
6426 if (atomic_read(&bbio->error) > bbio->max_errors) {
6427 bio->bi_status = BLK_STS_IOERR;
6430 * this bio is actually up to date, we didn't
6431 * go over the max number of errors
6433 bio->bi_status = BLK_STS_OK;
6436 btrfs_end_bbio(bbio, bio);
6437 } else if (!is_orig_bio) {
6442 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6443 u64 physical, struct btrfs_device *dev)
6445 struct btrfs_fs_info *fs_info = bbio->fs_info;
6447 bio->bi_private = bbio;
6448 btrfs_io_bio(bio)->device = dev;
6449 bio->bi_end_io = btrfs_end_bio;
6450 bio->bi_iter.bi_sector = physical >> 9;
6451 btrfs_debug_in_rcu(fs_info,
6452 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6453 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6454 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6455 dev->devid, bio->bi_iter.bi_size);
6456 bio_set_dev(bio, dev->bdev);
6458 btrfs_bio_counter_inc_noblocked(fs_info);
6460 btrfsic_submit_bio(bio);
6463 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6465 atomic_inc(&bbio->error);
6466 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6467 /* Should be the original bio. */
6468 WARN_ON(bio != bbio->orig_bio);
6470 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6471 bio->bi_iter.bi_sector = logical >> 9;
6472 if (atomic_read(&bbio->error) > bbio->max_errors)
6473 bio->bi_status = BLK_STS_IOERR;
6475 bio->bi_status = BLK_STS_OK;
6476 btrfs_end_bbio(bbio, bio);
6480 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6483 struct btrfs_device *dev;
6484 struct bio *first_bio = bio;
6485 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6491 struct btrfs_bio *bbio = NULL;
6493 length = bio->bi_iter.bi_size;
6494 map_length = length;
6496 btrfs_bio_counter_inc_blocked(fs_info);
6497 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6498 &map_length, &bbio, mirror_num, 1);
6500 btrfs_bio_counter_dec(fs_info);
6501 return errno_to_blk_status(ret);
6504 total_devs = bbio->num_stripes;
6505 bbio->orig_bio = first_bio;
6506 bbio->private = first_bio->bi_private;
6507 bbio->end_io = first_bio->bi_end_io;
6508 bbio->fs_info = fs_info;
6509 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6511 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6512 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6513 /* In this case, map_length has been set to the length of
6514 a single stripe; not the whole write */
6515 if (bio_op(bio) == REQ_OP_WRITE) {
6516 ret = raid56_parity_write(fs_info, bio, bbio,
6519 ret = raid56_parity_recover(fs_info, bio, bbio,
6520 map_length, mirror_num, 1);
6523 btrfs_bio_counter_dec(fs_info);
6524 return errno_to_blk_status(ret);
6527 if (map_length < length) {
6529 "mapping failed logical %llu bio len %llu len %llu",
6530 logical, length, map_length);
6534 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6535 dev = bbio->stripes[dev_nr].dev;
6536 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6538 (bio_op(first_bio) == REQ_OP_WRITE &&
6539 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6540 bbio_error(bbio, first_bio, logical);
6544 if (dev_nr < total_devs - 1)
6545 bio = btrfs_bio_clone(first_bio);
6549 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical, dev);
6551 btrfs_bio_counter_dec(fs_info);
6556 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6559 * If devid and uuid are both specified, the match must be exact, otherwise
6560 * only devid is used.
6562 * If @seed is true, traverse through the seed devices.
6564 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6565 u64 devid, u8 *uuid, u8 *fsid,
6568 struct btrfs_device *device;
6569 struct btrfs_fs_devices *seed_devs;
6571 if (!fsid || !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6572 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6573 if (device->devid == devid &&
6574 (!uuid || memcmp(device->uuid, uuid,
6575 BTRFS_UUID_SIZE) == 0))
6580 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6582 !memcmp(seed_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6583 list_for_each_entry(device, &seed_devs->devices,
6585 if (device->devid == devid &&
6586 (!uuid || memcmp(device->uuid, uuid,
6587 BTRFS_UUID_SIZE) == 0))
6596 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6597 u64 devid, u8 *dev_uuid)
6599 struct btrfs_device *device;
6600 unsigned int nofs_flag;
6603 * We call this under the chunk_mutex, so we want to use NOFS for this
6604 * allocation, however we don't want to change btrfs_alloc_device() to
6605 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6608 nofs_flag = memalloc_nofs_save();
6609 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6610 memalloc_nofs_restore(nofs_flag);
6614 list_add(&device->dev_list, &fs_devices->devices);
6615 device->fs_devices = fs_devices;
6616 fs_devices->num_devices++;
6618 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6619 fs_devices->missing_devices++;
6625 * btrfs_alloc_device - allocate struct btrfs_device
6626 * @fs_info: used only for generating a new devid, can be NULL if
6627 * devid is provided (i.e. @devid != NULL).
6628 * @devid: a pointer to devid for this device. If NULL a new devid
6630 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6633 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6634 * on error. Returned struct is not linked onto any lists and must be
6635 * destroyed with btrfs_free_device.
6637 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6641 struct btrfs_device *dev;
6644 if (WARN_ON(!devid && !fs_info))
6645 return ERR_PTR(-EINVAL);
6647 dev = __alloc_device(fs_info);
6656 ret = find_next_devid(fs_info, &tmp);
6658 btrfs_free_device(dev);
6659 return ERR_PTR(ret);
6665 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6667 generate_random_uuid(dev->uuid);
6672 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6673 u64 devid, u8 *uuid, bool error)
6676 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6679 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6683 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6685 int index = btrfs_bg_flags_to_raid_index(type);
6686 int ncopies = btrfs_raid_array[index].ncopies;
6687 const int nparity = btrfs_raid_array[index].nparity;
6691 data_stripes = num_stripes - nparity;
6693 data_stripes = num_stripes / ncopies;
6695 return div_u64(chunk_len, data_stripes);
6698 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6699 struct btrfs_chunk *chunk)
6701 struct btrfs_fs_info *fs_info = leaf->fs_info;
6702 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6703 struct map_lookup *map;
6704 struct extent_map *em;
6708 u8 uuid[BTRFS_UUID_SIZE];
6713 logical = key->offset;
6714 length = btrfs_chunk_length(leaf, chunk);
6715 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6718 * Only need to verify chunk item if we're reading from sys chunk array,
6719 * as chunk item in tree block is already verified by tree-checker.
6721 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6722 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6727 read_lock(&map_tree->lock);
6728 em = lookup_extent_mapping(map_tree, logical, 1);
6729 read_unlock(&map_tree->lock);
6731 /* already mapped? */
6732 if (em && em->start <= logical && em->start + em->len > logical) {
6733 free_extent_map(em);
6736 free_extent_map(em);
6739 em = alloc_extent_map();
6742 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6744 free_extent_map(em);
6748 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6749 em->map_lookup = map;
6750 em->start = logical;
6753 em->block_start = 0;
6754 em->block_len = em->len;
6756 map->num_stripes = num_stripes;
6757 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6758 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6759 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6760 map->type = btrfs_chunk_type(leaf, chunk);
6761 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6762 map->verified_stripes = 0;
6763 em->orig_block_len = calc_stripe_length(map->type, em->len,
6765 for (i = 0; i < num_stripes; i++) {
6766 map->stripes[i].physical =
6767 btrfs_stripe_offset_nr(leaf, chunk, i);
6768 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6769 read_extent_buffer(leaf, uuid, (unsigned long)
6770 btrfs_stripe_dev_uuid_nr(chunk, i),
6772 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6773 devid, uuid, NULL, true);
6774 if (!map->stripes[i].dev &&
6775 !btrfs_test_opt(fs_info, DEGRADED)) {
6776 free_extent_map(em);
6777 btrfs_report_missing_device(fs_info, devid, uuid, true);
6780 if (!map->stripes[i].dev) {
6781 map->stripes[i].dev =
6782 add_missing_dev(fs_info->fs_devices, devid,
6784 if (IS_ERR(map->stripes[i].dev)) {
6785 free_extent_map(em);
6787 "failed to init missing dev %llu: %ld",
6788 devid, PTR_ERR(map->stripes[i].dev));
6789 return PTR_ERR(map->stripes[i].dev);
6791 btrfs_report_missing_device(fs_info, devid, uuid, false);
6793 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6794 &(map->stripes[i].dev->dev_state));
6798 write_lock(&map_tree->lock);
6799 ret = add_extent_mapping(map_tree, em, 0);
6800 write_unlock(&map_tree->lock);
6803 "failed to add chunk map, start=%llu len=%llu: %d",
6804 em->start, em->len, ret);
6806 free_extent_map(em);
6811 static void fill_device_from_item(struct extent_buffer *leaf,
6812 struct btrfs_dev_item *dev_item,
6813 struct btrfs_device *device)
6817 device->devid = btrfs_device_id(leaf, dev_item);
6818 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6819 device->total_bytes = device->disk_total_bytes;
6820 device->commit_total_bytes = device->disk_total_bytes;
6821 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6822 device->commit_bytes_used = device->bytes_used;
6823 device->type = btrfs_device_type(leaf, dev_item);
6824 device->io_align = btrfs_device_io_align(leaf, dev_item);
6825 device->io_width = btrfs_device_io_width(leaf, dev_item);
6826 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6827 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6828 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6830 ptr = btrfs_device_uuid(dev_item);
6831 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6834 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6837 struct btrfs_fs_devices *fs_devices;
6840 lockdep_assert_held(&uuid_mutex);
6843 /* This will match only for multi-device seed fs */
6844 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
6845 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6849 fs_devices = find_fsid(fsid, NULL);
6851 if (!btrfs_test_opt(fs_info, DEGRADED))
6852 return ERR_PTR(-ENOENT);
6854 fs_devices = alloc_fs_devices(fsid, NULL);
6855 if (IS_ERR(fs_devices))
6858 fs_devices->seeding = true;
6859 fs_devices->opened = 1;
6864 * Upon first call for a seed fs fsid, just create a private copy of the
6865 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
6867 fs_devices = clone_fs_devices(fs_devices);
6868 if (IS_ERR(fs_devices))
6871 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6873 free_fs_devices(fs_devices);
6874 return ERR_PTR(ret);
6877 if (!fs_devices->seeding) {
6878 close_fs_devices(fs_devices);
6879 free_fs_devices(fs_devices);
6880 return ERR_PTR(-EINVAL);
6883 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
6888 static int read_one_dev(struct extent_buffer *leaf,
6889 struct btrfs_dev_item *dev_item)
6891 struct btrfs_fs_info *fs_info = leaf->fs_info;
6892 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6893 struct btrfs_device *device;
6896 u8 fs_uuid[BTRFS_FSID_SIZE];
6897 u8 dev_uuid[BTRFS_UUID_SIZE];
6899 devid = btrfs_device_id(leaf, dev_item);
6900 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6902 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6905 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6906 fs_devices = open_seed_devices(fs_info, fs_uuid);
6907 if (IS_ERR(fs_devices))
6908 return PTR_ERR(fs_devices);
6911 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6914 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6915 btrfs_report_missing_device(fs_info, devid,
6920 device = add_missing_dev(fs_devices, devid, dev_uuid);
6921 if (IS_ERR(device)) {
6923 "failed to add missing dev %llu: %ld",
6924 devid, PTR_ERR(device));
6925 return PTR_ERR(device);
6927 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6929 if (!device->bdev) {
6930 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6931 btrfs_report_missing_device(fs_info,
6932 devid, dev_uuid, true);
6935 btrfs_report_missing_device(fs_info, devid,
6939 if (!device->bdev &&
6940 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6942 * this happens when a device that was properly setup
6943 * in the device info lists suddenly goes bad.
6944 * device->bdev is NULL, and so we have to set
6945 * device->missing to one here
6947 device->fs_devices->missing_devices++;
6948 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6951 /* Move the device to its own fs_devices */
6952 if (device->fs_devices != fs_devices) {
6953 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6954 &device->dev_state));
6956 list_move(&device->dev_list, &fs_devices->devices);
6957 device->fs_devices->num_devices--;
6958 fs_devices->num_devices++;
6960 device->fs_devices->missing_devices--;
6961 fs_devices->missing_devices++;
6963 device->fs_devices = fs_devices;
6967 if (device->fs_devices != fs_info->fs_devices) {
6968 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6969 if (device->generation !=
6970 btrfs_device_generation(leaf, dev_item))
6974 fill_device_from_item(leaf, dev_item, device);
6975 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6976 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6977 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6978 device->fs_devices->total_rw_bytes += device->total_bytes;
6979 atomic64_add(device->total_bytes - device->bytes_used,
6980 &fs_info->free_chunk_space);
6986 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6988 struct btrfs_root *root = fs_info->tree_root;
6989 struct btrfs_super_block *super_copy = fs_info->super_copy;
6990 struct extent_buffer *sb;
6991 struct btrfs_disk_key *disk_key;
6992 struct btrfs_chunk *chunk;
6994 unsigned long sb_array_offset;
7001 struct btrfs_key key;
7003 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7005 * This will create extent buffer of nodesize, superblock size is
7006 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7007 * overallocate but we can keep it as-is, only the first page is used.
7009 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
7012 set_extent_buffer_uptodate(sb);
7013 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
7015 * The sb extent buffer is artificial and just used to read the system array.
7016 * set_extent_buffer_uptodate() call does not properly mark all it's
7017 * pages up-to-date when the page is larger: extent does not cover the
7018 * whole page and consequently check_page_uptodate does not find all
7019 * the page's extents up-to-date (the hole beyond sb),
7020 * write_extent_buffer then triggers a WARN_ON.
7022 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7023 * but sb spans only this function. Add an explicit SetPageUptodate call
7024 * to silence the warning eg. on PowerPC 64.
7026 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
7027 SetPageUptodate(sb->pages[0]);
7029 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7030 array_size = btrfs_super_sys_array_size(super_copy);
7032 array_ptr = super_copy->sys_chunk_array;
7033 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7036 while (cur_offset < array_size) {
7037 disk_key = (struct btrfs_disk_key *)array_ptr;
7038 len = sizeof(*disk_key);
7039 if (cur_offset + len > array_size)
7040 goto out_short_read;
7042 btrfs_disk_key_to_cpu(&key, disk_key);
7045 sb_array_offset += len;
7048 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
7050 "unexpected item type %u in sys_array at offset %u",
7051 (u32)key.type, cur_offset);
7056 chunk = (struct btrfs_chunk *)sb_array_offset;
7058 * At least one btrfs_chunk with one stripe must be present,
7059 * exact stripe count check comes afterwards
7061 len = btrfs_chunk_item_size(1);
7062 if (cur_offset + len > array_size)
7063 goto out_short_read;
7065 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7068 "invalid number of stripes %u in sys_array at offset %u",
7069 num_stripes, cur_offset);
7074 type = btrfs_chunk_type(sb, chunk);
7075 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7077 "invalid chunk type %llu in sys_array at offset %u",
7083 len = btrfs_chunk_item_size(num_stripes);
7084 if (cur_offset + len > array_size)
7085 goto out_short_read;
7087 ret = read_one_chunk(&key, sb, chunk);
7092 sb_array_offset += len;
7095 clear_extent_buffer_uptodate(sb);
7096 free_extent_buffer_stale(sb);
7100 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7102 clear_extent_buffer_uptodate(sb);
7103 free_extent_buffer_stale(sb);
7108 * Check if all chunks in the fs are OK for read-write degraded mount
7110 * If the @failing_dev is specified, it's accounted as missing.
7112 * Return true if all chunks meet the minimal RW mount requirements.
7113 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7115 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7116 struct btrfs_device *failing_dev)
7118 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7119 struct extent_map *em;
7123 read_lock(&map_tree->lock);
7124 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7125 read_unlock(&map_tree->lock);
7126 /* No chunk at all? Return false anyway */
7132 struct map_lookup *map;
7137 map = em->map_lookup;
7139 btrfs_get_num_tolerated_disk_barrier_failures(
7141 for (i = 0; i < map->num_stripes; i++) {
7142 struct btrfs_device *dev = map->stripes[i].dev;
7144 if (!dev || !dev->bdev ||
7145 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7146 dev->last_flush_error)
7148 else if (failing_dev && failing_dev == dev)
7151 if (missing > max_tolerated) {
7154 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7155 em->start, missing, max_tolerated);
7156 free_extent_map(em);
7160 next_start = extent_map_end(em);
7161 free_extent_map(em);
7163 read_lock(&map_tree->lock);
7164 em = lookup_extent_mapping(map_tree, next_start,
7165 (u64)(-1) - next_start);
7166 read_unlock(&map_tree->lock);
7172 static void readahead_tree_node_children(struct extent_buffer *node)
7175 const int nr_items = btrfs_header_nritems(node);
7177 for (i = 0; i < nr_items; i++) {
7180 start = btrfs_node_blockptr(node, i);
7181 readahead_tree_block(node->fs_info, start);
7185 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7187 struct btrfs_root *root = fs_info->chunk_root;
7188 struct btrfs_path *path;
7189 struct extent_buffer *leaf;
7190 struct btrfs_key key;
7191 struct btrfs_key found_key;
7195 u64 last_ra_node = 0;
7197 path = btrfs_alloc_path();
7202 * uuid_mutex is needed only if we are mounting a sprout FS
7203 * otherwise we don't need it.
7205 mutex_lock(&uuid_mutex);
7208 * It is possible for mount and umount to race in such a way that
7209 * we execute this code path, but open_fs_devices failed to clear
7210 * total_rw_bytes. We certainly want it cleared before reading the
7211 * device items, so clear it here.
7213 fs_info->fs_devices->total_rw_bytes = 0;
7216 * Read all device items, and then all the chunk items. All
7217 * device items are found before any chunk item (their object id
7218 * is smaller than the lowest possible object id for a chunk
7219 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7221 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7224 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7228 struct extent_buffer *node;
7230 leaf = path->nodes[0];
7231 slot = path->slots[0];
7232 if (slot >= btrfs_header_nritems(leaf)) {
7233 ret = btrfs_next_leaf(root, path);
7241 * The nodes on level 1 are not locked but we don't need to do
7242 * that during mount time as nothing else can access the tree
7244 node = path->nodes[1];
7246 if (last_ra_node != node->start) {
7247 readahead_tree_node_children(node);
7248 last_ra_node = node->start;
7251 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7252 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7253 struct btrfs_dev_item *dev_item;
7254 dev_item = btrfs_item_ptr(leaf, slot,
7255 struct btrfs_dev_item);
7256 ret = read_one_dev(leaf, dev_item);
7260 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7261 struct btrfs_chunk *chunk;
7262 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7263 mutex_lock(&fs_info->chunk_mutex);
7264 ret = read_one_chunk(&found_key, leaf, chunk);
7265 mutex_unlock(&fs_info->chunk_mutex);
7273 * After loading chunk tree, we've got all device information,
7274 * do another round of validation checks.
7276 if (total_dev != fs_info->fs_devices->total_devices) {
7278 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7279 btrfs_super_num_devices(fs_info->super_copy),
7281 fs_info->fs_devices->total_devices = total_dev;
7282 btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
7284 if (btrfs_super_total_bytes(fs_info->super_copy) <
7285 fs_info->fs_devices->total_rw_bytes) {
7287 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7288 btrfs_super_total_bytes(fs_info->super_copy),
7289 fs_info->fs_devices->total_rw_bytes);
7295 mutex_unlock(&uuid_mutex);
7297 btrfs_free_path(path);
7301 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7303 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7304 struct btrfs_device *device;
7306 fs_devices->fs_info = fs_info;
7308 mutex_lock(&fs_devices->device_list_mutex);
7309 list_for_each_entry(device, &fs_devices->devices, dev_list)
7310 device->fs_info = fs_info;
7312 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7313 list_for_each_entry(device, &seed_devs->devices, dev_list)
7314 device->fs_info = fs_info;
7316 seed_devs->fs_info = fs_info;
7318 mutex_unlock(&fs_devices->device_list_mutex);
7321 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7322 const struct btrfs_dev_stats_item *ptr,
7327 read_extent_buffer(eb, &val,
7328 offsetof(struct btrfs_dev_stats_item, values) +
7329 ((unsigned long)ptr) + (index * sizeof(u64)),
7334 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7335 struct btrfs_dev_stats_item *ptr,
7338 write_extent_buffer(eb, &val,
7339 offsetof(struct btrfs_dev_stats_item, values) +
7340 ((unsigned long)ptr) + (index * sizeof(u64)),
7344 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7345 struct btrfs_path *path)
7347 struct btrfs_dev_stats_item *ptr;
7348 struct extent_buffer *eb;
7349 struct btrfs_key key;
7353 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7354 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7355 key.offset = device->devid;
7356 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7358 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7359 btrfs_dev_stat_set(device, i, 0);
7360 device->dev_stats_valid = 1;
7361 btrfs_release_path(path);
7362 return ret < 0 ? ret : 0;
7364 slot = path->slots[0];
7365 eb = path->nodes[0];
7366 item_size = btrfs_item_size_nr(eb, slot);
7368 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7370 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7371 if (item_size >= (1 + i) * sizeof(__le64))
7372 btrfs_dev_stat_set(device, i,
7373 btrfs_dev_stats_value(eb, ptr, i));
7375 btrfs_dev_stat_set(device, i, 0);
7378 device->dev_stats_valid = 1;
7379 btrfs_dev_stat_print_on_load(device);
7380 btrfs_release_path(path);
7385 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7387 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7388 struct btrfs_device *device;
7389 struct btrfs_path *path = NULL;
7392 path = btrfs_alloc_path();
7396 mutex_lock(&fs_devices->device_list_mutex);
7397 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7398 ret = btrfs_device_init_dev_stats(device, path);
7402 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7403 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7404 ret = btrfs_device_init_dev_stats(device, path);
7410 mutex_unlock(&fs_devices->device_list_mutex);
7412 btrfs_free_path(path);
7416 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7417 struct btrfs_device *device)
7419 struct btrfs_fs_info *fs_info = trans->fs_info;
7420 struct btrfs_root *dev_root = fs_info->dev_root;
7421 struct btrfs_path *path;
7422 struct btrfs_key key;
7423 struct extent_buffer *eb;
7424 struct btrfs_dev_stats_item *ptr;
7428 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7429 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7430 key.offset = device->devid;
7432 path = btrfs_alloc_path();
7435 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7437 btrfs_warn_in_rcu(fs_info,
7438 "error %d while searching for dev_stats item for device %s",
7439 ret, rcu_str_deref(device->name));
7444 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7445 /* need to delete old one and insert a new one */
7446 ret = btrfs_del_item(trans, dev_root, path);
7448 btrfs_warn_in_rcu(fs_info,
7449 "delete too small dev_stats item for device %s failed %d",
7450 rcu_str_deref(device->name), ret);
7457 /* need to insert a new item */
7458 btrfs_release_path(path);
7459 ret = btrfs_insert_empty_item(trans, dev_root, path,
7460 &key, sizeof(*ptr));
7462 btrfs_warn_in_rcu(fs_info,
7463 "insert dev_stats item for device %s failed %d",
7464 rcu_str_deref(device->name), ret);
7469 eb = path->nodes[0];
7470 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7471 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7472 btrfs_set_dev_stats_value(eb, ptr, i,
7473 btrfs_dev_stat_read(device, i));
7474 btrfs_mark_buffer_dirty(eb);
7477 btrfs_free_path(path);
7482 * called from commit_transaction. Writes all changed device stats to disk.
7484 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7486 struct btrfs_fs_info *fs_info = trans->fs_info;
7487 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7488 struct btrfs_device *device;
7492 mutex_lock(&fs_devices->device_list_mutex);
7493 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7494 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7495 if (!device->dev_stats_valid || stats_cnt == 0)
7500 * There is a LOAD-LOAD control dependency between the value of
7501 * dev_stats_ccnt and updating the on-disk values which requires
7502 * reading the in-memory counters. Such control dependencies
7503 * require explicit read memory barriers.
7505 * This memory barriers pairs with smp_mb__before_atomic in
7506 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7507 * barrier implied by atomic_xchg in
7508 * btrfs_dev_stats_read_and_reset
7512 ret = update_dev_stat_item(trans, device);
7514 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7516 mutex_unlock(&fs_devices->device_list_mutex);
7521 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7523 btrfs_dev_stat_inc(dev, index);
7524 btrfs_dev_stat_print_on_error(dev);
7527 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7529 if (!dev->dev_stats_valid)
7531 btrfs_err_rl_in_rcu(dev->fs_info,
7532 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7533 rcu_str_deref(dev->name),
7534 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7535 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7536 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7537 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7538 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7541 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7545 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7546 if (btrfs_dev_stat_read(dev, i) != 0)
7548 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7549 return; /* all values == 0, suppress message */
7551 btrfs_info_in_rcu(dev->fs_info,
7552 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7553 rcu_str_deref(dev->name),
7554 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7555 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7556 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7557 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7558 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7561 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7562 struct btrfs_ioctl_get_dev_stats *stats)
7564 struct btrfs_device *dev;
7565 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7568 mutex_lock(&fs_devices->device_list_mutex);
7569 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7571 mutex_unlock(&fs_devices->device_list_mutex);
7574 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7576 } else if (!dev->dev_stats_valid) {
7577 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7579 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7580 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7581 if (stats->nr_items > i)
7583 btrfs_dev_stat_read_and_reset(dev, i);
7585 btrfs_dev_stat_set(dev, i, 0);
7587 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7588 current->comm, task_pid_nr(current));
7590 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7591 if (stats->nr_items > i)
7592 stats->values[i] = btrfs_dev_stat_read(dev, i);
7594 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7595 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7600 * Update the size and bytes used for each device where it changed. This is
7601 * delayed since we would otherwise get errors while writing out the
7604 * Must be invoked during transaction commit.
7606 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7608 struct btrfs_device *curr, *next;
7610 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7612 if (list_empty(&trans->dev_update_list))
7616 * We don't need the device_list_mutex here. This list is owned by the
7617 * transaction and the transaction must complete before the device is
7620 mutex_lock(&trans->fs_info->chunk_mutex);
7621 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7623 list_del_init(&curr->post_commit_list);
7624 curr->commit_total_bytes = curr->disk_total_bytes;
7625 curr->commit_bytes_used = curr->bytes_used;
7627 mutex_unlock(&trans->fs_info->chunk_mutex);
7631 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7633 int btrfs_bg_type_to_factor(u64 flags)
7635 const int index = btrfs_bg_flags_to_raid_index(flags);
7637 return btrfs_raid_array[index].ncopies;
7642 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7643 u64 chunk_offset, u64 devid,
7644 u64 physical_offset, u64 physical_len)
7646 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7647 struct extent_map *em;
7648 struct map_lookup *map;
7649 struct btrfs_device *dev;
7655 read_lock(&em_tree->lock);
7656 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7657 read_unlock(&em_tree->lock);
7661 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7662 physical_offset, devid);
7667 map = em->map_lookup;
7668 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7669 if (physical_len != stripe_len) {
7671 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7672 physical_offset, devid, em->start, physical_len,
7678 for (i = 0; i < map->num_stripes; i++) {
7679 if (map->stripes[i].dev->devid == devid &&
7680 map->stripes[i].physical == physical_offset) {
7682 if (map->verified_stripes >= map->num_stripes) {
7684 "too many dev extents for chunk %llu found",
7689 map->verified_stripes++;
7695 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7696 physical_offset, devid);
7700 /* Make sure no dev extent is beyond device bondary */
7701 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7703 btrfs_err(fs_info, "failed to find devid %llu", devid);
7708 /* It's possible this device is a dummy for seed device */
7709 if (dev->disk_total_bytes == 0) {
7710 struct btrfs_fs_devices *devs;
7712 devs = list_first_entry(&fs_info->fs_devices->seed_list,
7713 struct btrfs_fs_devices, seed_list);
7714 dev = btrfs_find_device(devs, devid, NULL, NULL, false);
7716 btrfs_err(fs_info, "failed to find seed devid %llu",
7723 if (physical_offset + physical_len > dev->disk_total_bytes) {
7725 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7726 devid, physical_offset, physical_len,
7727 dev->disk_total_bytes);
7732 free_extent_map(em);
7736 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7738 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7739 struct extent_map *em;
7740 struct rb_node *node;
7743 read_lock(&em_tree->lock);
7744 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7745 em = rb_entry(node, struct extent_map, rb_node);
7746 if (em->map_lookup->num_stripes !=
7747 em->map_lookup->verified_stripes) {
7749 "chunk %llu has missing dev extent, have %d expect %d",
7750 em->start, em->map_lookup->verified_stripes,
7751 em->map_lookup->num_stripes);
7757 read_unlock(&em_tree->lock);
7762 * Ensure that all dev extents are mapped to correct chunk, otherwise
7763 * later chunk allocation/free would cause unexpected behavior.
7765 * NOTE: This will iterate through the whole device tree, which should be of
7766 * the same size level as the chunk tree. This slightly increases mount time.
7768 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7770 struct btrfs_path *path;
7771 struct btrfs_root *root = fs_info->dev_root;
7772 struct btrfs_key key;
7774 u64 prev_dev_ext_end = 0;
7778 key.type = BTRFS_DEV_EXTENT_KEY;
7781 path = btrfs_alloc_path();
7785 path->reada = READA_FORWARD;
7786 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7790 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7791 ret = btrfs_next_item(root, path);
7794 /* No dev extents at all? Not good */
7801 struct extent_buffer *leaf = path->nodes[0];
7802 struct btrfs_dev_extent *dext;
7803 int slot = path->slots[0];
7805 u64 physical_offset;
7809 btrfs_item_key_to_cpu(leaf, &key, slot);
7810 if (key.type != BTRFS_DEV_EXTENT_KEY)
7812 devid = key.objectid;
7813 physical_offset = key.offset;
7815 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7816 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7817 physical_len = btrfs_dev_extent_length(leaf, dext);
7819 /* Check if this dev extent overlaps with the previous one */
7820 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7822 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7823 devid, physical_offset, prev_dev_ext_end);
7828 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7829 physical_offset, physical_len);
7833 prev_dev_ext_end = physical_offset + physical_len;
7835 ret = btrfs_next_item(root, path);
7844 /* Ensure all chunks have corresponding dev extents */
7845 ret = verify_chunk_dev_extent_mapping(fs_info);
7847 btrfs_free_path(path);
7852 * Check whether the given block group or device is pinned by any inode being
7853 * used as a swapfile.
7855 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7857 struct btrfs_swapfile_pin *sp;
7858 struct rb_node *node;
7860 spin_lock(&fs_info->swapfile_pins_lock);
7861 node = fs_info->swapfile_pins.rb_node;
7863 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7865 node = node->rb_left;
7866 else if (ptr > sp->ptr)
7867 node = node->rb_right;
7871 spin_unlock(&fs_info->swapfile_pins_lock);
7872 return node != NULL;