1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
8 #include <linux/slab.h>
9 #include <linux/blkdev.h>
10 #include <linux/ratelimit.h>
11 #include <linux/kthread.h>
12 #include <linux/raid/pq.h>
13 #include <linux/semaphore.h>
14 #include <linux/uuid.h>
15 #include <linux/list_sort.h>
18 #include "extent_map.h"
20 #include "transaction.h"
21 #include "print-tree.h"
24 #include "async-thread.h"
25 #include "check-integrity.h"
26 #include "rcu-string.h"
27 #include "dev-replace.h"
29 #include "tree-checker.h"
30 #include "space-info.h"
31 #include "block-group.h"
34 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
35 [BTRFS_RAID_RAID10] = {
38 .devs_max = 0, /* 0 == as many as possible */
40 .tolerated_failures = 1,
44 .raid_name = "raid10",
45 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
46 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
48 [BTRFS_RAID_RAID1] = {
53 .tolerated_failures = 1,
58 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
59 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
61 [BTRFS_RAID_RAID1C3] = {
66 .tolerated_failures = 2,
70 .raid_name = "raid1c3",
71 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
72 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
74 [BTRFS_RAID_RAID1C4] = {
79 .tolerated_failures = 3,
83 .raid_name = "raid1c4",
84 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
85 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
92 .tolerated_failures = 0,
97 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
100 [BTRFS_RAID_RAID0] = {
105 .tolerated_failures = 0,
109 .raid_name = "raid0",
110 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
113 [BTRFS_RAID_SINGLE] = {
118 .tolerated_failures = 0,
122 .raid_name = "single",
126 [BTRFS_RAID_RAID5] = {
131 .tolerated_failures = 1,
135 .raid_name = "raid5",
136 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
137 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
139 [BTRFS_RAID_RAID6] = {
144 .tolerated_failures = 2,
148 .raid_name = "raid6",
149 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
150 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
154 const char *btrfs_bg_type_to_raid_name(u64 flags)
156 const int index = btrfs_bg_flags_to_raid_index(flags);
158 if (index >= BTRFS_NR_RAID_TYPES)
161 return btrfs_raid_array[index].raid_name;
165 * Fill @buf with textual description of @bg_flags, no more than @size_buf
166 * bytes including terminating null byte.
168 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
173 u64 flags = bg_flags;
174 u32 size_bp = size_buf;
181 #define DESCRIBE_FLAG(flag, desc) \
183 if (flags & (flag)) { \
184 ret = snprintf(bp, size_bp, "%s|", (desc)); \
185 if (ret < 0 || ret >= size_bp) \
193 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
194 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
195 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
197 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
198 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
199 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
200 btrfs_raid_array[i].raid_name);
204 ret = snprintf(bp, size_bp, "0x%llx|", flags);
208 if (size_bp < size_buf)
209 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
212 * The text is trimmed, it's up to the caller to provide sufficiently
218 static int init_first_rw_device(struct btrfs_trans_handle *trans);
219 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
220 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
221 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
222 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
223 enum btrfs_map_op op,
224 u64 logical, u64 *length,
225 struct btrfs_bio **bbio_ret,
226 int mirror_num, int need_raid_map);
232 * There are several mutexes that protect manipulation of devices and low-level
233 * structures like chunks but not block groups, extents or files
235 * uuid_mutex (global lock)
236 * ------------------------
237 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
238 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
239 * device) or requested by the device= mount option
241 * the mutex can be very coarse and can cover long-running operations
243 * protects: updates to fs_devices counters like missing devices, rw devices,
244 * seeding, structure cloning, opening/closing devices at mount/umount time
246 * global::fs_devs - add, remove, updates to the global list
248 * does not protect: manipulation of the fs_devices::devices list!
250 * btrfs_device::name - renames (write side), read is RCU
252 * fs_devices::device_list_mutex (per-fs, with RCU)
253 * ------------------------------------------------
254 * protects updates to fs_devices::devices, ie. adding and deleting
256 * simple list traversal with read-only actions can be done with RCU protection
258 * may be used to exclude some operations from running concurrently without any
259 * modifications to the list (see write_all_supers)
263 * protects balance structures (status, state) and context accessed from
264 * several places (internally, ioctl)
268 * protects chunks, adding or removing during allocation, trim or when a new
269 * device is added/removed. Additionally it also protects post_commit_list of
270 * individual devices, since they can be added to the transaction's
271 * post_commit_list only with chunk_mutex held.
275 * a big lock that is held by the cleaner thread and prevents running subvolume
276 * cleaning together with relocation or delayed iputs
288 * Exclusive operations, BTRFS_FS_EXCL_OP
289 * ======================================
291 * Maintains the exclusivity of the following operations that apply to the
292 * whole filesystem and cannot run in parallel.
297 * - Device replace (*)
300 * The device operations (as above) can be in one of the following states:
306 * Only device operations marked with (*) can go into the Paused state for the
309 * - ioctl (only Balance can be Paused through ioctl)
310 * - filesystem remounted as read-only
311 * - filesystem unmounted and mounted as read-only
312 * - system power-cycle and filesystem mounted as read-only
313 * - filesystem or device errors leading to forced read-only
315 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
316 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
317 * A device operation in Paused or Running state can be canceled or resumed
318 * either by ioctl (Balance only) or when remounted as read-write.
319 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
323 DEFINE_MUTEX(uuid_mutex);
324 static LIST_HEAD(fs_uuids);
325 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
331 * alloc_fs_devices - allocate struct btrfs_fs_devices
332 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
333 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
335 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
336 * The returned struct is not linked onto any lists and can be destroyed with
337 * kfree() right away.
339 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
340 const u8 *metadata_fsid)
342 struct btrfs_fs_devices *fs_devs;
344 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
346 return ERR_PTR(-ENOMEM);
348 mutex_init(&fs_devs->device_list_mutex);
350 INIT_LIST_HEAD(&fs_devs->devices);
351 INIT_LIST_HEAD(&fs_devs->alloc_list);
352 INIT_LIST_HEAD(&fs_devs->fs_list);
354 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
357 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
359 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
364 void btrfs_free_device(struct btrfs_device *device)
366 WARN_ON(!list_empty(&device->post_commit_list));
367 rcu_string_free(device->name);
368 extent_io_tree_release(&device->alloc_state);
369 bio_put(device->flush_bio);
373 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
375 struct btrfs_device *device;
376 WARN_ON(fs_devices->opened);
377 while (!list_empty(&fs_devices->devices)) {
378 device = list_entry(fs_devices->devices.next,
379 struct btrfs_device, dev_list);
380 list_del(&device->dev_list);
381 btrfs_free_device(device);
386 void __exit btrfs_cleanup_fs_uuids(void)
388 struct btrfs_fs_devices *fs_devices;
390 while (!list_empty(&fs_uuids)) {
391 fs_devices = list_entry(fs_uuids.next,
392 struct btrfs_fs_devices, fs_list);
393 list_del(&fs_devices->fs_list);
394 free_fs_devices(fs_devices);
399 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
400 * Returned struct is not linked onto any lists and must be destroyed using
403 static struct btrfs_device *__alloc_device(void)
405 struct btrfs_device *dev;
407 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
409 return ERR_PTR(-ENOMEM);
412 * Preallocate a bio that's always going to be used for flushing device
413 * barriers and matches the device lifespan
415 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
416 if (!dev->flush_bio) {
418 return ERR_PTR(-ENOMEM);
421 INIT_LIST_HEAD(&dev->dev_list);
422 INIT_LIST_HEAD(&dev->dev_alloc_list);
423 INIT_LIST_HEAD(&dev->post_commit_list);
425 atomic_set(&dev->reada_in_flight, 0);
426 atomic_set(&dev->dev_stats_ccnt, 0);
427 btrfs_device_data_ordered_init(dev);
428 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
429 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
430 extent_io_tree_init(NULL, &dev->alloc_state, 0, NULL);
435 static noinline struct btrfs_fs_devices *find_fsid(
436 const u8 *fsid, const u8 *metadata_fsid)
438 struct btrfs_fs_devices *fs_devices;
442 /* Handle non-split brain cases */
443 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
445 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
446 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
447 BTRFS_FSID_SIZE) == 0)
450 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
457 static struct btrfs_fs_devices *find_fsid_with_metadata_uuid(
458 struct btrfs_super_block *disk_super)
461 struct btrfs_fs_devices *fs_devices;
464 * Handle scanned device having completed its fsid change but
465 * belonging to a fs_devices that was created by first scanning
466 * a device which didn't have its fsid/metadata_uuid changed
467 * at all and the CHANGING_FSID_V2 flag set.
469 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
470 if (fs_devices->fsid_change &&
471 memcmp(disk_super->metadata_uuid, fs_devices->fsid,
472 BTRFS_FSID_SIZE) == 0 &&
473 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
474 BTRFS_FSID_SIZE) == 0) {
479 * Handle scanned device having completed its fsid change but
480 * belonging to a fs_devices that was created by a device that
481 * has an outdated pair of fsid/metadata_uuid and
482 * CHANGING_FSID_V2 flag set.
484 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
485 if (fs_devices->fsid_change &&
486 memcmp(fs_devices->metadata_uuid,
487 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
488 memcmp(disk_super->metadata_uuid, fs_devices->metadata_uuid,
489 BTRFS_FSID_SIZE) == 0) {
494 return find_fsid(disk_super->fsid, disk_super->metadata_uuid);
499 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
500 int flush, struct block_device **bdev,
501 struct btrfs_super_block **disk_super)
505 *bdev = blkdev_get_by_path(device_path, flags, holder);
508 ret = PTR_ERR(*bdev);
513 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
514 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
516 blkdev_put(*bdev, flags);
519 invalidate_bdev(*bdev);
520 *disk_super = btrfs_read_dev_super(*bdev);
521 if (IS_ERR(*disk_super)) {
522 ret = PTR_ERR(*disk_super);
523 blkdev_put(*bdev, flags);
534 static bool device_path_matched(const char *path, struct btrfs_device *device)
539 found = strcmp(rcu_str_deref(device->name), path);
546 * Search and remove all stale (devices which are not mounted) devices.
547 * When both inputs are NULL, it will search and release all stale devices.
548 * path: Optional. When provided will it release all unmounted devices
549 * matching this path only.
550 * skip_dev: Optional. Will skip this device when searching for the stale
552 * Return: 0 for success or if @path is NULL.
553 * -EBUSY if @path is a mounted device.
554 * -ENOENT if @path does not match any device in the list.
556 static int btrfs_free_stale_devices(const char *path,
557 struct btrfs_device *skip_device)
559 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
560 struct btrfs_device *device, *tmp_device;
566 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
568 mutex_lock(&fs_devices->device_list_mutex);
569 list_for_each_entry_safe(device, tmp_device,
570 &fs_devices->devices, dev_list) {
571 if (skip_device && skip_device == device)
573 if (path && !device->name)
575 if (path && !device_path_matched(path, device))
577 if (fs_devices->opened) {
578 /* for an already deleted device return 0 */
579 if (path && ret != 0)
584 /* delete the stale device */
585 fs_devices->num_devices--;
586 list_del(&device->dev_list);
587 btrfs_free_device(device);
590 if (fs_devices->num_devices == 0)
593 mutex_unlock(&fs_devices->device_list_mutex);
595 if (fs_devices->num_devices == 0) {
596 btrfs_sysfs_remove_fsid(fs_devices);
597 list_del(&fs_devices->fs_list);
598 free_fs_devices(fs_devices);
605 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
606 struct btrfs_device *device, fmode_t flags,
609 struct request_queue *q;
610 struct block_device *bdev;
611 struct btrfs_super_block *disk_super;
620 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
625 devid = btrfs_stack_device_id(&disk_super->dev_item);
626 if (devid != device->devid)
627 goto error_free_page;
629 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
630 goto error_free_page;
632 device->generation = btrfs_super_generation(disk_super);
634 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
635 if (btrfs_super_incompat_flags(disk_super) &
636 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
638 "BTRFS: Invalid seeding and uuid-changed device detected\n");
639 goto error_free_page;
642 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
643 fs_devices->seeding = true;
645 if (bdev_read_only(bdev))
646 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
648 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
651 q = bdev_get_queue(bdev);
652 if (!blk_queue_nonrot(q))
653 fs_devices->rotating = true;
656 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
657 device->mode = flags;
659 fs_devices->open_devices++;
660 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
661 device->devid != BTRFS_DEV_REPLACE_DEVID) {
662 fs_devices->rw_devices++;
663 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
665 btrfs_release_disk_super(disk_super);
670 btrfs_release_disk_super(disk_super);
671 blkdev_put(bdev, flags);
677 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
678 * being created with a disk that has already completed its fsid change. Such
679 * disk can belong to an fs which has its FSID changed or to one which doesn't.
680 * Handle both cases here.
682 static struct btrfs_fs_devices *find_fsid_inprogress(
683 struct btrfs_super_block *disk_super)
685 struct btrfs_fs_devices *fs_devices;
687 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
688 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
689 BTRFS_FSID_SIZE) != 0 &&
690 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
691 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
696 return find_fsid(disk_super->fsid, NULL);
700 static struct btrfs_fs_devices *find_fsid_changed(
701 struct btrfs_super_block *disk_super)
703 struct btrfs_fs_devices *fs_devices;
706 * Handles the case where scanned device is part of an fs that had
707 * multiple successful changes of FSID but curently device didn't
708 * observe it. Meaning our fsid will be different than theirs. We need
709 * to handle two subcases :
710 * 1 - The fs still continues to have different METADATA/FSID uuids.
711 * 2 - The fs is switched back to its original FSID (METADATA/FSID
714 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
716 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
717 BTRFS_FSID_SIZE) != 0 &&
718 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
719 BTRFS_FSID_SIZE) == 0 &&
720 memcmp(fs_devices->fsid, disk_super->fsid,
721 BTRFS_FSID_SIZE) != 0)
724 /* Unchanged UUIDs */
725 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
726 BTRFS_FSID_SIZE) == 0 &&
727 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
728 BTRFS_FSID_SIZE) == 0)
735 static struct btrfs_fs_devices *find_fsid_reverted_metadata(
736 struct btrfs_super_block *disk_super)
738 struct btrfs_fs_devices *fs_devices;
741 * Handle the case where the scanned device is part of an fs whose last
742 * metadata UUID change reverted it to the original FSID. At the same
743 * time * fs_devices was first created by another constitutent device
744 * which didn't fully observe the operation. This results in an
745 * btrfs_fs_devices created with metadata/fsid different AND
746 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
747 * fs_devices equal to the FSID of the disk.
749 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
750 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
751 BTRFS_FSID_SIZE) != 0 &&
752 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
753 BTRFS_FSID_SIZE) == 0 &&
754 fs_devices->fsid_change)
761 * Add new device to list of registered devices
764 * device pointer which was just added or updated when successful
765 * error pointer when failed
767 static noinline struct btrfs_device *device_list_add(const char *path,
768 struct btrfs_super_block *disk_super,
769 bool *new_device_added)
771 struct btrfs_device *device;
772 struct btrfs_fs_devices *fs_devices = NULL;
773 struct rcu_string *name;
774 u64 found_transid = btrfs_super_generation(disk_super);
775 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
776 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
777 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
778 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
779 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
781 if (fsid_change_in_progress) {
782 if (!has_metadata_uuid)
783 fs_devices = find_fsid_inprogress(disk_super);
785 fs_devices = find_fsid_changed(disk_super);
786 } else if (has_metadata_uuid) {
787 fs_devices = find_fsid_with_metadata_uuid(disk_super);
789 fs_devices = find_fsid_reverted_metadata(disk_super);
791 fs_devices = find_fsid(disk_super->fsid, NULL);
796 if (has_metadata_uuid)
797 fs_devices = alloc_fs_devices(disk_super->fsid,
798 disk_super->metadata_uuid);
800 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
802 if (IS_ERR(fs_devices))
803 return ERR_CAST(fs_devices);
805 fs_devices->fsid_change = fsid_change_in_progress;
807 mutex_lock(&fs_devices->device_list_mutex);
808 list_add(&fs_devices->fs_list, &fs_uuids);
812 mutex_lock(&fs_devices->device_list_mutex);
813 device = btrfs_find_device(fs_devices, devid,
814 disk_super->dev_item.uuid, NULL, false);
817 * If this disk has been pulled into an fs devices created by
818 * a device which had the CHANGING_FSID_V2 flag then replace the
819 * metadata_uuid/fsid values of the fs_devices.
821 if (fs_devices->fsid_change &&
822 found_transid > fs_devices->latest_generation) {
823 memcpy(fs_devices->fsid, disk_super->fsid,
826 if (has_metadata_uuid)
827 memcpy(fs_devices->metadata_uuid,
828 disk_super->metadata_uuid,
831 memcpy(fs_devices->metadata_uuid,
832 disk_super->fsid, BTRFS_FSID_SIZE);
834 fs_devices->fsid_change = false;
839 if (fs_devices->opened) {
840 mutex_unlock(&fs_devices->device_list_mutex);
841 return ERR_PTR(-EBUSY);
844 device = btrfs_alloc_device(NULL, &devid,
845 disk_super->dev_item.uuid);
846 if (IS_ERR(device)) {
847 mutex_unlock(&fs_devices->device_list_mutex);
848 /* we can safely leave the fs_devices entry around */
852 name = rcu_string_strdup(path, GFP_NOFS);
854 btrfs_free_device(device);
855 mutex_unlock(&fs_devices->device_list_mutex);
856 return ERR_PTR(-ENOMEM);
858 rcu_assign_pointer(device->name, name);
860 list_add_rcu(&device->dev_list, &fs_devices->devices);
861 fs_devices->num_devices++;
863 device->fs_devices = fs_devices;
864 *new_device_added = true;
866 if (disk_super->label[0])
868 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
869 disk_super->label, devid, found_transid, path,
870 current->comm, task_pid_nr(current));
873 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
874 disk_super->fsid, devid, found_transid, path,
875 current->comm, task_pid_nr(current));
877 } else if (!device->name || strcmp(device->name->str, path)) {
879 * When FS is already mounted.
880 * 1. If you are here and if the device->name is NULL that
881 * means this device was missing at time of FS mount.
882 * 2. If you are here and if the device->name is different
883 * from 'path' that means either
884 * a. The same device disappeared and reappeared with
886 * b. The missing-disk-which-was-replaced, has
889 * We must allow 1 and 2a above. But 2b would be a spurious
892 * Further in case of 1 and 2a above, the disk at 'path'
893 * would have missed some transaction when it was away and
894 * in case of 2a the stale bdev has to be updated as well.
895 * 2b must not be allowed at all time.
899 * For now, we do allow update to btrfs_fs_device through the
900 * btrfs dev scan cli after FS has been mounted. We're still
901 * tracking a problem where systems fail mount by subvolume id
902 * when we reject replacement on a mounted FS.
904 if (!fs_devices->opened && found_transid < device->generation) {
906 * That is if the FS is _not_ mounted and if you
907 * are here, that means there is more than one
908 * disk with same uuid and devid.We keep the one
909 * with larger generation number or the last-in if
910 * generation are equal.
912 mutex_unlock(&fs_devices->device_list_mutex);
913 return ERR_PTR(-EEXIST);
917 * We are going to replace the device path for a given devid,
918 * make sure it's the same device if the device is mounted
921 struct block_device *path_bdev;
923 path_bdev = lookup_bdev(path);
924 if (IS_ERR(path_bdev)) {
925 mutex_unlock(&fs_devices->device_list_mutex);
926 return ERR_CAST(path_bdev);
929 if (device->bdev != path_bdev) {
931 mutex_unlock(&fs_devices->device_list_mutex);
932 btrfs_warn_in_rcu(device->fs_info,
933 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
934 disk_super->fsid, devid,
935 rcu_str_deref(device->name), path);
936 return ERR_PTR(-EEXIST);
939 btrfs_info_in_rcu(device->fs_info,
940 "device fsid %pU devid %llu moved old:%s new:%s",
941 disk_super->fsid, devid,
942 rcu_str_deref(device->name), path);
945 name = rcu_string_strdup(path, GFP_NOFS);
947 mutex_unlock(&fs_devices->device_list_mutex);
948 return ERR_PTR(-ENOMEM);
950 rcu_string_free(device->name);
951 rcu_assign_pointer(device->name, name);
952 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
953 fs_devices->missing_devices--;
954 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
959 * Unmount does not free the btrfs_device struct but would zero
960 * generation along with most of the other members. So just update
961 * it back. We need it to pick the disk with largest generation
964 if (!fs_devices->opened) {
965 device->generation = found_transid;
966 fs_devices->latest_generation = max_t(u64, found_transid,
967 fs_devices->latest_generation);
970 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
972 mutex_unlock(&fs_devices->device_list_mutex);
976 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
978 struct btrfs_fs_devices *fs_devices;
979 struct btrfs_device *device;
980 struct btrfs_device *orig_dev;
983 fs_devices = alloc_fs_devices(orig->fsid, NULL);
984 if (IS_ERR(fs_devices))
987 mutex_lock(&orig->device_list_mutex);
988 fs_devices->total_devices = orig->total_devices;
990 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
991 struct rcu_string *name;
993 device = btrfs_alloc_device(NULL, &orig_dev->devid,
995 if (IS_ERR(device)) {
996 ret = PTR_ERR(device);
1001 * This is ok to do without rcu read locked because we hold the
1002 * uuid mutex so nothing we touch in here is going to disappear.
1004 if (orig_dev->name) {
1005 name = rcu_string_strdup(orig_dev->name->str,
1008 btrfs_free_device(device);
1012 rcu_assign_pointer(device->name, name);
1015 list_add(&device->dev_list, &fs_devices->devices);
1016 device->fs_devices = fs_devices;
1017 fs_devices->num_devices++;
1019 mutex_unlock(&orig->device_list_mutex);
1022 mutex_unlock(&orig->device_list_mutex);
1023 free_fs_devices(fs_devices);
1024 return ERR_PTR(ret);
1028 * After we have read the system tree and know devids belonging to
1029 * this filesystem, remove the device which does not belong there.
1031 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1033 struct btrfs_device *device, *next;
1034 struct btrfs_device *latest_dev = NULL;
1036 mutex_lock(&uuid_mutex);
1038 /* This is the initialized path, it is safe to release the devices. */
1039 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1040 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1041 &device->dev_state)) {
1042 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1043 &device->dev_state) &&
1044 !test_bit(BTRFS_DEV_STATE_MISSING,
1045 &device->dev_state) &&
1047 device->generation > latest_dev->generation)) {
1048 latest_dev = device;
1053 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1055 * In the first step, keep the device which has
1056 * the correct fsid and the devid that is used
1057 * for the dev_replace procedure.
1058 * In the second step, the dev_replace state is
1059 * read from the device tree and it is known
1060 * whether the procedure is really active or
1061 * not, which means whether this device is
1062 * used or whether it should be removed.
1064 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1065 &device->dev_state)) {
1070 blkdev_put(device->bdev, device->mode);
1071 device->bdev = NULL;
1072 fs_devices->open_devices--;
1074 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1075 list_del_init(&device->dev_alloc_list);
1076 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1077 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1078 &device->dev_state))
1079 fs_devices->rw_devices--;
1081 list_del_init(&device->dev_list);
1082 fs_devices->num_devices--;
1083 btrfs_free_device(device);
1086 if (fs_devices->seed) {
1087 fs_devices = fs_devices->seed;
1091 fs_devices->latest_bdev = latest_dev->bdev;
1093 mutex_unlock(&uuid_mutex);
1096 static void btrfs_close_bdev(struct btrfs_device *device)
1101 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1102 sync_blockdev(device->bdev);
1103 invalidate_bdev(device->bdev);
1106 blkdev_put(device->bdev, device->mode);
1109 static void btrfs_close_one_device(struct btrfs_device *device)
1111 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1113 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1114 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1115 list_del_init(&device->dev_alloc_list);
1116 fs_devices->rw_devices--;
1119 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1120 fs_devices->missing_devices--;
1122 btrfs_close_bdev(device);
1124 fs_devices->open_devices--;
1125 device->bdev = NULL;
1127 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1129 device->fs_info = NULL;
1130 atomic_set(&device->dev_stats_ccnt, 0);
1131 extent_io_tree_release(&device->alloc_state);
1133 /* Verify the device is back in a pristine state */
1134 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1135 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1136 ASSERT(list_empty(&device->dev_alloc_list));
1137 ASSERT(list_empty(&device->post_commit_list));
1138 ASSERT(atomic_read(&device->reada_in_flight) == 0);
1141 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1143 struct btrfs_device *device, *tmp;
1145 if (--fs_devices->opened > 0)
1148 mutex_lock(&fs_devices->device_list_mutex);
1149 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1150 btrfs_close_one_device(device);
1152 mutex_unlock(&fs_devices->device_list_mutex);
1154 WARN_ON(fs_devices->open_devices);
1155 WARN_ON(fs_devices->rw_devices);
1156 fs_devices->opened = 0;
1157 fs_devices->seeding = false;
1162 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1164 struct btrfs_fs_devices *seed_devices = NULL;
1167 mutex_lock(&uuid_mutex);
1168 ret = close_fs_devices(fs_devices);
1169 if (!fs_devices->opened) {
1170 seed_devices = fs_devices->seed;
1171 fs_devices->seed = NULL;
1173 mutex_unlock(&uuid_mutex);
1175 while (seed_devices) {
1176 fs_devices = seed_devices;
1177 seed_devices = fs_devices->seed;
1178 close_fs_devices(fs_devices);
1179 free_fs_devices(fs_devices);
1184 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1185 fmode_t flags, void *holder)
1187 struct btrfs_device *device;
1188 struct btrfs_device *latest_dev = NULL;
1190 flags |= FMODE_EXCL;
1192 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1193 /* Just open everything we can; ignore failures here */
1194 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1198 device->generation > latest_dev->generation)
1199 latest_dev = device;
1201 if (fs_devices->open_devices == 0)
1204 fs_devices->opened = 1;
1205 fs_devices->latest_bdev = latest_dev->bdev;
1206 fs_devices->total_rw_bytes = 0;
1207 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1212 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1214 struct btrfs_device *dev1, *dev2;
1216 dev1 = list_entry(a, struct btrfs_device, dev_list);
1217 dev2 = list_entry(b, struct btrfs_device, dev_list);
1219 if (dev1->devid < dev2->devid)
1221 else if (dev1->devid > dev2->devid)
1226 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1227 fmode_t flags, void *holder)
1231 lockdep_assert_held(&uuid_mutex);
1233 mutex_lock(&fs_devices->device_list_mutex);
1234 if (fs_devices->opened) {
1235 fs_devices->opened++;
1238 list_sort(NULL, &fs_devices->devices, devid_cmp);
1239 ret = open_fs_devices(fs_devices, flags, holder);
1241 mutex_unlock(&fs_devices->device_list_mutex);
1246 void btrfs_release_disk_super(struct btrfs_super_block *super)
1248 struct page *page = virt_to_page(super);
1253 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1256 struct btrfs_super_block *disk_super;
1261 /* make sure our super fits in the device */
1262 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1263 return ERR_PTR(-EINVAL);
1265 /* make sure our super fits in the page */
1266 if (sizeof(*disk_super) > PAGE_SIZE)
1267 return ERR_PTR(-EINVAL);
1269 /* make sure our super doesn't straddle pages on disk */
1270 index = bytenr >> PAGE_SHIFT;
1271 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1272 return ERR_PTR(-EINVAL);
1274 /* pull in the page with our super */
1275 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1278 return ERR_CAST(page);
1280 p = page_address(page);
1282 /* align our pointer to the offset of the super block */
1283 disk_super = p + offset_in_page(bytenr);
1285 if (btrfs_super_bytenr(disk_super) != bytenr ||
1286 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1287 btrfs_release_disk_super(p);
1288 return ERR_PTR(-EINVAL);
1291 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1292 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1297 int btrfs_forget_devices(const char *path)
1301 mutex_lock(&uuid_mutex);
1302 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1303 mutex_unlock(&uuid_mutex);
1309 * Look for a btrfs signature on a device. This may be called out of the mount path
1310 * and we are not allowed to call set_blocksize during the scan. The superblock
1311 * is read via pagecache
1313 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1316 struct btrfs_super_block *disk_super;
1317 bool new_device_added = false;
1318 struct btrfs_device *device = NULL;
1319 struct block_device *bdev;
1322 lockdep_assert_held(&uuid_mutex);
1325 * we would like to check all the supers, but that would make
1326 * a btrfs mount succeed after a mkfs from a different FS.
1327 * So, we need to add a special mount option to scan for
1328 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1330 bytenr = btrfs_sb_offset(0);
1331 flags |= FMODE_EXCL;
1333 bdev = blkdev_get_by_path(path, flags, holder);
1335 return ERR_CAST(bdev);
1337 disk_super = btrfs_read_disk_super(bdev, bytenr);
1338 if (IS_ERR(disk_super)) {
1339 device = ERR_CAST(disk_super);
1340 goto error_bdev_put;
1343 device = device_list_add(path, disk_super, &new_device_added);
1344 if (!IS_ERR(device)) {
1345 if (new_device_added)
1346 btrfs_free_stale_devices(path, device);
1349 btrfs_release_disk_super(disk_super);
1352 blkdev_put(bdev, flags);
1358 * Try to find a chunk that intersects [start, start + len] range and when one
1359 * such is found, record the end of it in *start
1361 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1364 u64 physical_start, physical_end;
1366 lockdep_assert_held(&device->fs_info->chunk_mutex);
1368 if (!find_first_extent_bit(&device->alloc_state, *start,
1369 &physical_start, &physical_end,
1370 CHUNK_ALLOCATED, NULL)) {
1372 if (in_range(physical_start, *start, len) ||
1373 in_range(*start, physical_start,
1374 physical_end - physical_start)) {
1375 *start = physical_end + 1;
1382 static u64 dev_extent_search_start(struct btrfs_device *device, u64 start)
1384 switch (device->fs_devices->chunk_alloc_policy) {
1385 case BTRFS_CHUNK_ALLOC_REGULAR:
1387 * We don't want to overwrite the superblock on the drive nor
1388 * any area used by the boot loader (grub for example), so we
1389 * make sure to start at an offset of at least 1MB.
1391 return max_t(u64, start, SZ_1M);
1398 * dev_extent_hole_check - check if specified hole is suitable for allocation
1399 * @device: the device which we have the hole
1400 * @hole_start: starting position of the hole
1401 * @hole_size: the size of the hole
1402 * @num_bytes: the size of the free space that we need
1404 * This function may modify @hole_start and @hole_end to reflect the suitable
1405 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1407 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1408 u64 *hole_size, u64 num_bytes)
1410 bool changed = false;
1411 u64 hole_end = *hole_start + *hole_size;
1414 * Check before we set max_hole_start, otherwise we could end up
1415 * sending back this offset anyway.
1417 if (contains_pending_extent(device, hole_start, *hole_size)) {
1418 if (hole_end >= *hole_start)
1419 *hole_size = hole_end - *hole_start;
1425 switch (device->fs_devices->chunk_alloc_policy) {
1426 case BTRFS_CHUNK_ALLOC_REGULAR:
1427 /* No extra check */
1437 * find_free_dev_extent_start - find free space in the specified device
1438 * @device: the device which we search the free space in
1439 * @num_bytes: the size of the free space that we need
1440 * @search_start: the position from which to begin the search
1441 * @start: store the start of the free space.
1442 * @len: the size of the free space. that we find, or the size
1443 * of the max free space if we don't find suitable free space
1445 * this uses a pretty simple search, the expectation is that it is
1446 * called very infrequently and that a given device has a small number
1449 * @start is used to store the start of the free space if we find. But if we
1450 * don't find suitable free space, it will be used to store the start position
1451 * of the max free space.
1453 * @len is used to store the size of the free space that we find.
1454 * But if we don't find suitable free space, it is used to store the size of
1455 * the max free space.
1457 * NOTE: This function will search *commit* root of device tree, and does extra
1458 * check to ensure dev extents are not double allocated.
1459 * This makes the function safe to allocate dev extents but may not report
1460 * correct usable device space, as device extent freed in current transaction
1461 * is not reported as avaiable.
1463 static int find_free_dev_extent_start(struct btrfs_device *device,
1464 u64 num_bytes, u64 search_start, u64 *start,
1467 struct btrfs_fs_info *fs_info = device->fs_info;
1468 struct btrfs_root *root = fs_info->dev_root;
1469 struct btrfs_key key;
1470 struct btrfs_dev_extent *dev_extent;
1471 struct btrfs_path *path;
1476 u64 search_end = device->total_bytes;
1479 struct extent_buffer *l;
1481 search_start = dev_extent_search_start(device, search_start);
1483 path = btrfs_alloc_path();
1487 max_hole_start = search_start;
1491 if (search_start >= search_end ||
1492 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1497 path->reada = READA_FORWARD;
1498 path->search_commit_root = 1;
1499 path->skip_locking = 1;
1501 key.objectid = device->devid;
1502 key.offset = search_start;
1503 key.type = BTRFS_DEV_EXTENT_KEY;
1505 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1509 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1516 slot = path->slots[0];
1517 if (slot >= btrfs_header_nritems(l)) {
1518 ret = btrfs_next_leaf(root, path);
1526 btrfs_item_key_to_cpu(l, &key, slot);
1528 if (key.objectid < device->devid)
1531 if (key.objectid > device->devid)
1534 if (key.type != BTRFS_DEV_EXTENT_KEY)
1537 if (key.offset > search_start) {
1538 hole_size = key.offset - search_start;
1539 dev_extent_hole_check(device, &search_start, &hole_size,
1542 if (hole_size > max_hole_size) {
1543 max_hole_start = search_start;
1544 max_hole_size = hole_size;
1548 * If this free space is greater than which we need,
1549 * it must be the max free space that we have found
1550 * until now, so max_hole_start must point to the start
1551 * of this free space and the length of this free space
1552 * is stored in max_hole_size. Thus, we return
1553 * max_hole_start and max_hole_size and go back to the
1556 if (hole_size >= num_bytes) {
1562 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1563 extent_end = key.offset + btrfs_dev_extent_length(l,
1565 if (extent_end > search_start)
1566 search_start = extent_end;
1573 * At this point, search_start should be the end of
1574 * allocated dev extents, and when shrinking the device,
1575 * search_end may be smaller than search_start.
1577 if (search_end > search_start) {
1578 hole_size = search_end - search_start;
1579 if (dev_extent_hole_check(device, &search_start, &hole_size,
1581 btrfs_release_path(path);
1585 if (hole_size > max_hole_size) {
1586 max_hole_start = search_start;
1587 max_hole_size = hole_size;
1592 if (max_hole_size < num_bytes)
1598 btrfs_free_path(path);
1599 *start = max_hole_start;
1601 *len = max_hole_size;
1605 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1606 u64 *start, u64 *len)
1608 /* FIXME use last free of some kind */
1609 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1612 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1613 struct btrfs_device *device,
1614 u64 start, u64 *dev_extent_len)
1616 struct btrfs_fs_info *fs_info = device->fs_info;
1617 struct btrfs_root *root = fs_info->dev_root;
1619 struct btrfs_path *path;
1620 struct btrfs_key key;
1621 struct btrfs_key found_key;
1622 struct extent_buffer *leaf = NULL;
1623 struct btrfs_dev_extent *extent = NULL;
1625 path = btrfs_alloc_path();
1629 key.objectid = device->devid;
1631 key.type = BTRFS_DEV_EXTENT_KEY;
1633 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1635 ret = btrfs_previous_item(root, path, key.objectid,
1636 BTRFS_DEV_EXTENT_KEY);
1639 leaf = path->nodes[0];
1640 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1641 extent = btrfs_item_ptr(leaf, path->slots[0],
1642 struct btrfs_dev_extent);
1643 BUG_ON(found_key.offset > start || found_key.offset +
1644 btrfs_dev_extent_length(leaf, extent) < start);
1646 btrfs_release_path(path);
1648 } else if (ret == 0) {
1649 leaf = path->nodes[0];
1650 extent = btrfs_item_ptr(leaf, path->slots[0],
1651 struct btrfs_dev_extent);
1653 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1657 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1659 ret = btrfs_del_item(trans, root, path);
1661 btrfs_handle_fs_error(fs_info, ret,
1662 "Failed to remove dev extent item");
1664 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1667 btrfs_free_path(path);
1671 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1672 struct btrfs_device *device,
1673 u64 chunk_offset, u64 start, u64 num_bytes)
1676 struct btrfs_path *path;
1677 struct btrfs_fs_info *fs_info = device->fs_info;
1678 struct btrfs_root *root = fs_info->dev_root;
1679 struct btrfs_dev_extent *extent;
1680 struct extent_buffer *leaf;
1681 struct btrfs_key key;
1683 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1684 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1685 path = btrfs_alloc_path();
1689 key.objectid = device->devid;
1691 key.type = BTRFS_DEV_EXTENT_KEY;
1692 ret = btrfs_insert_empty_item(trans, root, path, &key,
1697 leaf = path->nodes[0];
1698 extent = btrfs_item_ptr(leaf, path->slots[0],
1699 struct btrfs_dev_extent);
1700 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1701 BTRFS_CHUNK_TREE_OBJECTID);
1702 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1703 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1704 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1706 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1707 btrfs_mark_buffer_dirty(leaf);
1709 btrfs_free_path(path);
1713 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1715 struct extent_map_tree *em_tree;
1716 struct extent_map *em;
1720 em_tree = &fs_info->mapping_tree;
1721 read_lock(&em_tree->lock);
1722 n = rb_last(&em_tree->map.rb_root);
1724 em = rb_entry(n, struct extent_map, rb_node);
1725 ret = em->start + em->len;
1727 read_unlock(&em_tree->lock);
1732 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1736 struct btrfs_key key;
1737 struct btrfs_key found_key;
1738 struct btrfs_path *path;
1740 path = btrfs_alloc_path();
1744 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1745 key.type = BTRFS_DEV_ITEM_KEY;
1746 key.offset = (u64)-1;
1748 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1754 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1759 ret = btrfs_previous_item(fs_info->chunk_root, path,
1760 BTRFS_DEV_ITEMS_OBJECTID,
1761 BTRFS_DEV_ITEM_KEY);
1765 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1767 *devid_ret = found_key.offset + 1;
1771 btrfs_free_path(path);
1776 * the device information is stored in the chunk root
1777 * the btrfs_device struct should be fully filled in
1779 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1780 struct btrfs_device *device)
1783 struct btrfs_path *path;
1784 struct btrfs_dev_item *dev_item;
1785 struct extent_buffer *leaf;
1786 struct btrfs_key key;
1789 path = btrfs_alloc_path();
1793 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1794 key.type = BTRFS_DEV_ITEM_KEY;
1795 key.offset = device->devid;
1797 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1798 &key, sizeof(*dev_item));
1802 leaf = path->nodes[0];
1803 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1805 btrfs_set_device_id(leaf, dev_item, device->devid);
1806 btrfs_set_device_generation(leaf, dev_item, 0);
1807 btrfs_set_device_type(leaf, dev_item, device->type);
1808 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1809 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1810 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1811 btrfs_set_device_total_bytes(leaf, dev_item,
1812 btrfs_device_get_disk_total_bytes(device));
1813 btrfs_set_device_bytes_used(leaf, dev_item,
1814 btrfs_device_get_bytes_used(device));
1815 btrfs_set_device_group(leaf, dev_item, 0);
1816 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1817 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1818 btrfs_set_device_start_offset(leaf, dev_item, 0);
1820 ptr = btrfs_device_uuid(dev_item);
1821 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1822 ptr = btrfs_device_fsid(dev_item);
1823 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1824 ptr, BTRFS_FSID_SIZE);
1825 btrfs_mark_buffer_dirty(leaf);
1829 btrfs_free_path(path);
1834 * Function to update ctime/mtime for a given device path.
1835 * Mainly used for ctime/mtime based probe like libblkid.
1837 static void update_dev_time(const char *path_name)
1841 filp = filp_open(path_name, O_RDWR, 0);
1844 file_update_time(filp);
1845 filp_close(filp, NULL);
1848 static int btrfs_rm_dev_item(struct btrfs_device *device)
1850 struct btrfs_root *root = device->fs_info->chunk_root;
1852 struct btrfs_path *path;
1853 struct btrfs_key key;
1854 struct btrfs_trans_handle *trans;
1856 path = btrfs_alloc_path();
1860 trans = btrfs_start_transaction(root, 0);
1861 if (IS_ERR(trans)) {
1862 btrfs_free_path(path);
1863 return PTR_ERR(trans);
1865 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1866 key.type = BTRFS_DEV_ITEM_KEY;
1867 key.offset = device->devid;
1869 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1873 btrfs_abort_transaction(trans, ret);
1874 btrfs_end_transaction(trans);
1878 ret = btrfs_del_item(trans, root, path);
1880 btrfs_abort_transaction(trans, ret);
1881 btrfs_end_transaction(trans);
1885 btrfs_free_path(path);
1887 ret = btrfs_commit_transaction(trans);
1892 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1893 * filesystem. It's up to the caller to adjust that number regarding eg. device
1896 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1904 seq = read_seqbegin(&fs_info->profiles_lock);
1906 all_avail = fs_info->avail_data_alloc_bits |
1907 fs_info->avail_system_alloc_bits |
1908 fs_info->avail_metadata_alloc_bits;
1909 } while (read_seqretry(&fs_info->profiles_lock, seq));
1911 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1912 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1915 if (num_devices < btrfs_raid_array[i].devs_min) {
1916 int ret = btrfs_raid_array[i].mindev_error;
1926 static struct btrfs_device * btrfs_find_next_active_device(
1927 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1929 struct btrfs_device *next_device;
1931 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1932 if (next_device != device &&
1933 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1934 && next_device->bdev)
1942 * Helper function to check if the given device is part of s_bdev / latest_bdev
1943 * and replace it with the provided or the next active device, in the context
1944 * where this function called, there should be always be another device (or
1945 * this_dev) which is active.
1947 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
1948 struct btrfs_device *this_dev)
1950 struct btrfs_fs_info *fs_info = device->fs_info;
1951 struct btrfs_device *next_device;
1954 next_device = this_dev;
1956 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1958 ASSERT(next_device);
1960 if (fs_info->sb->s_bdev &&
1961 (fs_info->sb->s_bdev == device->bdev))
1962 fs_info->sb->s_bdev = next_device->bdev;
1964 if (fs_info->fs_devices->latest_bdev == device->bdev)
1965 fs_info->fs_devices->latest_bdev = next_device->bdev;
1969 * Return btrfs_fs_devices::num_devices excluding the device that's being
1970 * currently replaced.
1972 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1974 u64 num_devices = fs_info->fs_devices->num_devices;
1976 down_read(&fs_info->dev_replace.rwsem);
1977 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1978 ASSERT(num_devices > 1);
1981 up_read(&fs_info->dev_replace.rwsem);
1986 static void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
1987 struct block_device *bdev,
1988 const char *device_path)
1990 struct btrfs_super_block *disk_super;
1996 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2000 disk_super = btrfs_read_dev_one_super(bdev, copy_num);
2001 if (IS_ERR(disk_super))
2004 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
2006 page = virt_to_page(disk_super);
2007 set_page_dirty(page);
2009 /* write_on_page() unlocks the page */
2010 ret = write_one_page(page);
2013 "error clearing superblock number %d (%d)",
2015 btrfs_release_disk_super(disk_super);
2019 /* Notify udev that device has changed */
2020 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2022 /* Update ctime/mtime for device path for libblkid */
2023 update_dev_time(device_path);
2026 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2029 struct btrfs_device *device;
2030 struct btrfs_fs_devices *cur_devices;
2031 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2035 mutex_lock(&uuid_mutex);
2037 num_devices = btrfs_num_devices(fs_info);
2039 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2043 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2045 if (IS_ERR(device)) {
2046 if (PTR_ERR(device) == -ENOENT &&
2047 strcmp(device_path, "missing") == 0)
2048 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2050 ret = PTR_ERR(device);
2054 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2055 btrfs_warn_in_rcu(fs_info,
2056 "cannot remove device %s (devid %llu) due to active swapfile",
2057 rcu_str_deref(device->name), device->devid);
2062 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2063 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2067 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2068 fs_info->fs_devices->rw_devices == 1) {
2069 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2073 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2074 mutex_lock(&fs_info->chunk_mutex);
2075 list_del_init(&device->dev_alloc_list);
2076 device->fs_devices->rw_devices--;
2077 mutex_unlock(&fs_info->chunk_mutex);
2080 mutex_unlock(&uuid_mutex);
2081 ret = btrfs_shrink_device(device, 0);
2082 mutex_lock(&uuid_mutex);
2087 * TODO: the superblock still includes this device in its num_devices
2088 * counter although write_all_supers() is not locked out. This
2089 * could give a filesystem state which requires a degraded mount.
2091 ret = btrfs_rm_dev_item(device);
2095 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2096 btrfs_scrub_cancel_dev(device);
2099 * the device list mutex makes sure that we don't change
2100 * the device list while someone else is writing out all
2101 * the device supers. Whoever is writing all supers, should
2102 * lock the device list mutex before getting the number of
2103 * devices in the super block (super_copy). Conversely,
2104 * whoever updates the number of devices in the super block
2105 * (super_copy) should hold the device list mutex.
2109 * In normal cases the cur_devices == fs_devices. But in case
2110 * of deleting a seed device, the cur_devices should point to
2111 * its own fs_devices listed under the fs_devices->seed.
2113 cur_devices = device->fs_devices;
2114 mutex_lock(&fs_devices->device_list_mutex);
2115 list_del_rcu(&device->dev_list);
2117 cur_devices->num_devices--;
2118 cur_devices->total_devices--;
2119 /* Update total_devices of the parent fs_devices if it's seed */
2120 if (cur_devices != fs_devices)
2121 fs_devices->total_devices--;
2123 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2124 cur_devices->missing_devices--;
2126 btrfs_assign_next_active_device(device, NULL);
2129 cur_devices->open_devices--;
2130 /* remove sysfs entry */
2131 btrfs_sysfs_remove_devices_dir(fs_devices, device);
2134 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2135 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2136 mutex_unlock(&fs_devices->device_list_mutex);
2139 * at this point, the device is zero sized and detached from
2140 * the devices list. All that's left is to zero out the old
2141 * supers and free the device.
2143 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2144 btrfs_scratch_superblocks(fs_info, device->bdev,
2147 btrfs_close_bdev(device);
2149 btrfs_free_device(device);
2151 if (cur_devices->open_devices == 0) {
2152 while (fs_devices) {
2153 if (fs_devices->seed == cur_devices) {
2154 fs_devices->seed = cur_devices->seed;
2157 fs_devices = fs_devices->seed;
2159 cur_devices->seed = NULL;
2160 close_fs_devices(cur_devices);
2161 free_fs_devices(cur_devices);
2165 mutex_unlock(&uuid_mutex);
2169 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2170 mutex_lock(&fs_info->chunk_mutex);
2171 list_add(&device->dev_alloc_list,
2172 &fs_devices->alloc_list);
2173 device->fs_devices->rw_devices++;
2174 mutex_unlock(&fs_info->chunk_mutex);
2179 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2181 struct btrfs_fs_devices *fs_devices;
2183 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2186 * in case of fs with no seed, srcdev->fs_devices will point
2187 * to fs_devices of fs_info. However when the dev being replaced is
2188 * a seed dev it will point to the seed's local fs_devices. In short
2189 * srcdev will have its correct fs_devices in both the cases.
2191 fs_devices = srcdev->fs_devices;
2193 list_del_rcu(&srcdev->dev_list);
2194 list_del(&srcdev->dev_alloc_list);
2195 fs_devices->num_devices--;
2196 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2197 fs_devices->missing_devices--;
2199 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2200 fs_devices->rw_devices--;
2203 fs_devices->open_devices--;
2206 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2208 struct btrfs_fs_info *fs_info = srcdev->fs_info;
2209 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2211 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2212 /* zero out the old super if it is writable */
2213 btrfs_scratch_superblocks(fs_info, srcdev->bdev,
2217 btrfs_close_bdev(srcdev);
2219 btrfs_free_device(srcdev);
2221 /* if this is no devs we rather delete the fs_devices */
2222 if (!fs_devices->num_devices) {
2223 struct btrfs_fs_devices *tmp_fs_devices;
2226 * On a mounted FS, num_devices can't be zero unless it's a
2227 * seed. In case of a seed device being replaced, the replace
2228 * target added to the sprout FS, so there will be no more
2229 * device left under the seed FS.
2231 ASSERT(fs_devices->seeding);
2233 tmp_fs_devices = fs_info->fs_devices;
2234 while (tmp_fs_devices) {
2235 if (tmp_fs_devices->seed == fs_devices) {
2236 tmp_fs_devices->seed = fs_devices->seed;
2239 tmp_fs_devices = tmp_fs_devices->seed;
2241 fs_devices->seed = NULL;
2242 close_fs_devices(fs_devices);
2243 free_fs_devices(fs_devices);
2247 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2249 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2251 mutex_lock(&fs_devices->device_list_mutex);
2253 btrfs_sysfs_remove_devices_dir(fs_devices, tgtdev);
2256 fs_devices->open_devices--;
2258 fs_devices->num_devices--;
2260 btrfs_assign_next_active_device(tgtdev, NULL);
2262 list_del_rcu(&tgtdev->dev_list);
2264 mutex_unlock(&fs_devices->device_list_mutex);
2267 * The update_dev_time() with in btrfs_scratch_superblocks()
2268 * may lead to a call to btrfs_show_devname() which will try
2269 * to hold device_list_mutex. And here this device
2270 * is already out of device list, so we don't have to hold
2271 * the device_list_mutex lock.
2273 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2276 btrfs_close_bdev(tgtdev);
2278 btrfs_free_device(tgtdev);
2281 static struct btrfs_device *btrfs_find_device_by_path(
2282 struct btrfs_fs_info *fs_info, const char *device_path)
2285 struct btrfs_super_block *disk_super;
2288 struct block_device *bdev;
2289 struct btrfs_device *device;
2291 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2292 fs_info->bdev_holder, 0, &bdev, &disk_super);
2294 return ERR_PTR(ret);
2296 devid = btrfs_stack_device_id(&disk_super->dev_item);
2297 dev_uuid = disk_super->dev_item.uuid;
2298 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2299 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2300 disk_super->metadata_uuid, true);
2302 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2303 disk_super->fsid, true);
2305 btrfs_release_disk_super(disk_super);
2307 device = ERR_PTR(-ENOENT);
2308 blkdev_put(bdev, FMODE_READ);
2313 * Lookup a device given by device id, or the path if the id is 0.
2315 struct btrfs_device *btrfs_find_device_by_devspec(
2316 struct btrfs_fs_info *fs_info, u64 devid,
2317 const char *device_path)
2319 struct btrfs_device *device;
2322 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2325 return ERR_PTR(-ENOENT);
2329 if (!device_path || !device_path[0])
2330 return ERR_PTR(-EINVAL);
2332 if (strcmp(device_path, "missing") == 0) {
2333 /* Find first missing device */
2334 list_for_each_entry(device, &fs_info->fs_devices->devices,
2336 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2337 &device->dev_state) && !device->bdev)
2340 return ERR_PTR(-ENOENT);
2343 return btrfs_find_device_by_path(fs_info, device_path);
2347 * does all the dirty work required for changing file system's UUID.
2349 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2351 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2352 struct btrfs_fs_devices *old_devices;
2353 struct btrfs_fs_devices *seed_devices;
2354 struct btrfs_super_block *disk_super = fs_info->super_copy;
2355 struct btrfs_device *device;
2358 lockdep_assert_held(&uuid_mutex);
2359 if (!fs_devices->seeding)
2362 seed_devices = alloc_fs_devices(NULL, NULL);
2363 if (IS_ERR(seed_devices))
2364 return PTR_ERR(seed_devices);
2366 old_devices = clone_fs_devices(fs_devices);
2367 if (IS_ERR(old_devices)) {
2368 kfree(seed_devices);
2369 return PTR_ERR(old_devices);
2372 list_add(&old_devices->fs_list, &fs_uuids);
2374 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2375 seed_devices->opened = 1;
2376 INIT_LIST_HEAD(&seed_devices->devices);
2377 INIT_LIST_HEAD(&seed_devices->alloc_list);
2378 mutex_init(&seed_devices->device_list_mutex);
2380 mutex_lock(&fs_devices->device_list_mutex);
2381 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2383 list_for_each_entry(device, &seed_devices->devices, dev_list)
2384 device->fs_devices = seed_devices;
2386 mutex_lock(&fs_info->chunk_mutex);
2387 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2388 mutex_unlock(&fs_info->chunk_mutex);
2390 fs_devices->seeding = false;
2391 fs_devices->num_devices = 0;
2392 fs_devices->open_devices = 0;
2393 fs_devices->missing_devices = 0;
2394 fs_devices->rotating = false;
2395 fs_devices->seed = seed_devices;
2397 generate_random_uuid(fs_devices->fsid);
2398 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2399 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2400 mutex_unlock(&fs_devices->device_list_mutex);
2402 super_flags = btrfs_super_flags(disk_super) &
2403 ~BTRFS_SUPER_FLAG_SEEDING;
2404 btrfs_set_super_flags(disk_super, super_flags);
2410 * Store the expected generation for seed devices in device items.
2412 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2414 struct btrfs_fs_info *fs_info = trans->fs_info;
2415 struct btrfs_root *root = fs_info->chunk_root;
2416 struct btrfs_path *path;
2417 struct extent_buffer *leaf;
2418 struct btrfs_dev_item *dev_item;
2419 struct btrfs_device *device;
2420 struct btrfs_key key;
2421 u8 fs_uuid[BTRFS_FSID_SIZE];
2422 u8 dev_uuid[BTRFS_UUID_SIZE];
2426 path = btrfs_alloc_path();
2430 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2432 key.type = BTRFS_DEV_ITEM_KEY;
2435 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2439 leaf = path->nodes[0];
2441 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2442 ret = btrfs_next_leaf(root, path);
2447 leaf = path->nodes[0];
2448 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2449 btrfs_release_path(path);
2453 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2454 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2455 key.type != BTRFS_DEV_ITEM_KEY)
2458 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2459 struct btrfs_dev_item);
2460 devid = btrfs_device_id(leaf, dev_item);
2461 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2463 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2465 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2467 BUG_ON(!device); /* Logic error */
2469 if (device->fs_devices->seeding) {
2470 btrfs_set_device_generation(leaf, dev_item,
2471 device->generation);
2472 btrfs_mark_buffer_dirty(leaf);
2480 btrfs_free_path(path);
2484 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2486 struct btrfs_root *root = fs_info->dev_root;
2487 struct request_queue *q;
2488 struct btrfs_trans_handle *trans;
2489 struct btrfs_device *device;
2490 struct block_device *bdev;
2491 struct super_block *sb = fs_info->sb;
2492 struct rcu_string *name;
2493 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2494 u64 orig_super_total_bytes;
2495 u64 orig_super_num_devices;
2496 int seeding_dev = 0;
2498 bool unlocked = false;
2500 if (sb_rdonly(sb) && !fs_devices->seeding)
2503 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2504 fs_info->bdev_holder);
2506 return PTR_ERR(bdev);
2508 if (fs_devices->seeding) {
2510 down_write(&sb->s_umount);
2511 mutex_lock(&uuid_mutex);
2514 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2516 mutex_lock(&fs_devices->device_list_mutex);
2517 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2518 if (device->bdev == bdev) {
2521 &fs_devices->device_list_mutex);
2525 mutex_unlock(&fs_devices->device_list_mutex);
2527 device = btrfs_alloc_device(fs_info, NULL, NULL);
2528 if (IS_ERR(device)) {
2529 /* we can safely leave the fs_devices entry around */
2530 ret = PTR_ERR(device);
2534 name = rcu_string_strdup(device_path, GFP_KERNEL);
2537 goto error_free_device;
2539 rcu_assign_pointer(device->name, name);
2541 trans = btrfs_start_transaction(root, 0);
2542 if (IS_ERR(trans)) {
2543 ret = PTR_ERR(trans);
2544 goto error_free_device;
2547 q = bdev_get_queue(bdev);
2548 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2549 device->generation = trans->transid;
2550 device->io_width = fs_info->sectorsize;
2551 device->io_align = fs_info->sectorsize;
2552 device->sector_size = fs_info->sectorsize;
2553 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2554 fs_info->sectorsize);
2555 device->disk_total_bytes = device->total_bytes;
2556 device->commit_total_bytes = device->total_bytes;
2557 device->fs_info = fs_info;
2558 device->bdev = bdev;
2559 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2560 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2561 device->mode = FMODE_EXCL;
2562 device->dev_stats_valid = 1;
2563 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2566 sb->s_flags &= ~SB_RDONLY;
2567 ret = btrfs_prepare_sprout(fs_info);
2569 btrfs_abort_transaction(trans, ret);
2574 device->fs_devices = fs_devices;
2576 mutex_lock(&fs_devices->device_list_mutex);
2577 mutex_lock(&fs_info->chunk_mutex);
2578 list_add_rcu(&device->dev_list, &fs_devices->devices);
2579 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2580 fs_devices->num_devices++;
2581 fs_devices->open_devices++;
2582 fs_devices->rw_devices++;
2583 fs_devices->total_devices++;
2584 fs_devices->total_rw_bytes += device->total_bytes;
2586 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2588 if (!blk_queue_nonrot(q))
2589 fs_devices->rotating = true;
2591 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2592 btrfs_set_super_total_bytes(fs_info->super_copy,
2593 round_down(orig_super_total_bytes + device->total_bytes,
2594 fs_info->sectorsize));
2596 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2597 btrfs_set_super_num_devices(fs_info->super_copy,
2598 orig_super_num_devices + 1);
2600 /* add sysfs device entry */
2601 btrfs_sysfs_add_devices_dir(fs_devices, device);
2604 * we've got more storage, clear any full flags on the space
2607 btrfs_clear_space_info_full(fs_info);
2609 mutex_unlock(&fs_info->chunk_mutex);
2610 mutex_unlock(&fs_devices->device_list_mutex);
2613 mutex_lock(&fs_info->chunk_mutex);
2614 ret = init_first_rw_device(trans);
2615 mutex_unlock(&fs_info->chunk_mutex);
2617 btrfs_abort_transaction(trans, ret);
2622 ret = btrfs_add_dev_item(trans, device);
2624 btrfs_abort_transaction(trans, ret);
2629 ret = btrfs_finish_sprout(trans);
2631 btrfs_abort_transaction(trans, ret);
2635 btrfs_sysfs_update_sprout_fsid(fs_devices,
2636 fs_info->fs_devices->fsid);
2639 ret = btrfs_commit_transaction(trans);
2642 mutex_unlock(&uuid_mutex);
2643 up_write(&sb->s_umount);
2646 if (ret) /* transaction commit */
2649 ret = btrfs_relocate_sys_chunks(fs_info);
2651 btrfs_handle_fs_error(fs_info, ret,
2652 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2653 trans = btrfs_attach_transaction(root);
2654 if (IS_ERR(trans)) {
2655 if (PTR_ERR(trans) == -ENOENT)
2657 ret = PTR_ERR(trans);
2661 ret = btrfs_commit_transaction(trans);
2665 * Now that we have written a new super block to this device, check all
2666 * other fs_devices list if device_path alienates any other scanned
2668 * We can ignore the return value as it typically returns -EINVAL and
2669 * only succeeds if the device was an alien.
2671 btrfs_forget_devices(device_path);
2673 /* Update ctime/mtime for blkid or udev */
2674 update_dev_time(device_path);
2679 btrfs_sysfs_remove_devices_dir(fs_devices, device);
2680 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2681 mutex_lock(&fs_info->chunk_mutex);
2682 list_del_rcu(&device->dev_list);
2683 list_del(&device->dev_alloc_list);
2684 fs_info->fs_devices->num_devices--;
2685 fs_info->fs_devices->open_devices--;
2686 fs_info->fs_devices->rw_devices--;
2687 fs_info->fs_devices->total_devices--;
2688 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2689 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2690 btrfs_set_super_total_bytes(fs_info->super_copy,
2691 orig_super_total_bytes);
2692 btrfs_set_super_num_devices(fs_info->super_copy,
2693 orig_super_num_devices);
2694 mutex_unlock(&fs_info->chunk_mutex);
2695 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2698 sb->s_flags |= SB_RDONLY;
2700 btrfs_end_transaction(trans);
2702 btrfs_free_device(device);
2704 blkdev_put(bdev, FMODE_EXCL);
2705 if (seeding_dev && !unlocked) {
2706 mutex_unlock(&uuid_mutex);
2707 up_write(&sb->s_umount);
2712 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2713 struct btrfs_device *device)
2716 struct btrfs_path *path;
2717 struct btrfs_root *root = device->fs_info->chunk_root;
2718 struct btrfs_dev_item *dev_item;
2719 struct extent_buffer *leaf;
2720 struct btrfs_key key;
2722 path = btrfs_alloc_path();
2726 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2727 key.type = BTRFS_DEV_ITEM_KEY;
2728 key.offset = device->devid;
2730 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2739 leaf = path->nodes[0];
2740 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2742 btrfs_set_device_id(leaf, dev_item, device->devid);
2743 btrfs_set_device_type(leaf, dev_item, device->type);
2744 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2745 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2746 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2747 btrfs_set_device_total_bytes(leaf, dev_item,
2748 btrfs_device_get_disk_total_bytes(device));
2749 btrfs_set_device_bytes_used(leaf, dev_item,
2750 btrfs_device_get_bytes_used(device));
2751 btrfs_mark_buffer_dirty(leaf);
2754 btrfs_free_path(path);
2758 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2759 struct btrfs_device *device, u64 new_size)
2761 struct btrfs_fs_info *fs_info = device->fs_info;
2762 struct btrfs_super_block *super_copy = fs_info->super_copy;
2766 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2769 new_size = round_down(new_size, fs_info->sectorsize);
2771 mutex_lock(&fs_info->chunk_mutex);
2772 old_total = btrfs_super_total_bytes(super_copy);
2773 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2775 if (new_size <= device->total_bytes ||
2776 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2777 mutex_unlock(&fs_info->chunk_mutex);
2781 btrfs_set_super_total_bytes(super_copy,
2782 round_down(old_total + diff, fs_info->sectorsize));
2783 device->fs_devices->total_rw_bytes += diff;
2785 btrfs_device_set_total_bytes(device, new_size);
2786 btrfs_device_set_disk_total_bytes(device, new_size);
2787 btrfs_clear_space_info_full(device->fs_info);
2788 if (list_empty(&device->post_commit_list))
2789 list_add_tail(&device->post_commit_list,
2790 &trans->transaction->dev_update_list);
2791 mutex_unlock(&fs_info->chunk_mutex);
2793 return btrfs_update_device(trans, device);
2796 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2798 struct btrfs_fs_info *fs_info = trans->fs_info;
2799 struct btrfs_root *root = fs_info->chunk_root;
2801 struct btrfs_path *path;
2802 struct btrfs_key key;
2804 path = btrfs_alloc_path();
2808 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2809 key.offset = chunk_offset;
2810 key.type = BTRFS_CHUNK_ITEM_KEY;
2812 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2815 else if (ret > 0) { /* Logic error or corruption */
2816 btrfs_handle_fs_error(fs_info, -ENOENT,
2817 "Failed lookup while freeing chunk.");
2822 ret = btrfs_del_item(trans, root, path);
2824 btrfs_handle_fs_error(fs_info, ret,
2825 "Failed to delete chunk item.");
2827 btrfs_free_path(path);
2831 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2833 struct btrfs_super_block *super_copy = fs_info->super_copy;
2834 struct btrfs_disk_key *disk_key;
2835 struct btrfs_chunk *chunk;
2842 struct btrfs_key key;
2844 mutex_lock(&fs_info->chunk_mutex);
2845 array_size = btrfs_super_sys_array_size(super_copy);
2847 ptr = super_copy->sys_chunk_array;
2850 while (cur < array_size) {
2851 disk_key = (struct btrfs_disk_key *)ptr;
2852 btrfs_disk_key_to_cpu(&key, disk_key);
2854 len = sizeof(*disk_key);
2856 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2857 chunk = (struct btrfs_chunk *)(ptr + len);
2858 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2859 len += btrfs_chunk_item_size(num_stripes);
2864 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2865 key.offset == chunk_offset) {
2866 memmove(ptr, ptr + len, array_size - (cur + len));
2868 btrfs_set_super_sys_array_size(super_copy, array_size);
2874 mutex_unlock(&fs_info->chunk_mutex);
2879 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2880 * @logical: Logical block offset in bytes.
2881 * @length: Length of extent in bytes.
2883 * Return: Chunk mapping or ERR_PTR.
2885 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2886 u64 logical, u64 length)
2888 struct extent_map_tree *em_tree;
2889 struct extent_map *em;
2891 em_tree = &fs_info->mapping_tree;
2892 read_lock(&em_tree->lock);
2893 em = lookup_extent_mapping(em_tree, logical, length);
2894 read_unlock(&em_tree->lock);
2897 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2899 return ERR_PTR(-EINVAL);
2902 if (em->start > logical || em->start + em->len < logical) {
2904 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2905 logical, length, em->start, em->start + em->len);
2906 free_extent_map(em);
2907 return ERR_PTR(-EINVAL);
2910 /* callers are responsible for dropping em's ref. */
2914 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2916 struct btrfs_fs_info *fs_info = trans->fs_info;
2917 struct extent_map *em;
2918 struct map_lookup *map;
2919 u64 dev_extent_len = 0;
2921 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2923 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2926 * This is a logic error, but we don't want to just rely on the
2927 * user having built with ASSERT enabled, so if ASSERT doesn't
2928 * do anything we still error out.
2933 map = em->map_lookup;
2934 mutex_lock(&fs_info->chunk_mutex);
2935 check_system_chunk(trans, map->type);
2936 mutex_unlock(&fs_info->chunk_mutex);
2939 * Take the device list mutex to prevent races with the final phase of
2940 * a device replace operation that replaces the device object associated
2941 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2943 mutex_lock(&fs_devices->device_list_mutex);
2944 for (i = 0; i < map->num_stripes; i++) {
2945 struct btrfs_device *device = map->stripes[i].dev;
2946 ret = btrfs_free_dev_extent(trans, device,
2947 map->stripes[i].physical,
2950 mutex_unlock(&fs_devices->device_list_mutex);
2951 btrfs_abort_transaction(trans, ret);
2955 if (device->bytes_used > 0) {
2956 mutex_lock(&fs_info->chunk_mutex);
2957 btrfs_device_set_bytes_used(device,
2958 device->bytes_used - dev_extent_len);
2959 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2960 btrfs_clear_space_info_full(fs_info);
2961 mutex_unlock(&fs_info->chunk_mutex);
2964 ret = btrfs_update_device(trans, device);
2966 mutex_unlock(&fs_devices->device_list_mutex);
2967 btrfs_abort_transaction(trans, ret);
2971 mutex_unlock(&fs_devices->device_list_mutex);
2973 ret = btrfs_free_chunk(trans, chunk_offset);
2975 btrfs_abort_transaction(trans, ret);
2979 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2981 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2982 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2984 btrfs_abort_transaction(trans, ret);
2989 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2991 btrfs_abort_transaction(trans, ret);
2997 free_extent_map(em);
3001 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3003 struct btrfs_root *root = fs_info->chunk_root;
3004 struct btrfs_trans_handle *trans;
3005 struct btrfs_block_group *block_group;
3009 * Prevent races with automatic removal of unused block groups.
3010 * After we relocate and before we remove the chunk with offset
3011 * chunk_offset, automatic removal of the block group can kick in,
3012 * resulting in a failure when calling btrfs_remove_chunk() below.
3014 * Make sure to acquire this mutex before doing a tree search (dev
3015 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3016 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3017 * we release the path used to search the chunk/dev tree and before
3018 * the current task acquires this mutex and calls us.
3020 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3022 /* step one, relocate all the extents inside this chunk */
3023 btrfs_scrub_pause(fs_info);
3024 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3025 btrfs_scrub_continue(fs_info);
3029 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3032 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3033 btrfs_put_block_group(block_group);
3035 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3037 if (IS_ERR(trans)) {
3038 ret = PTR_ERR(trans);
3039 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3044 * step two, delete the device extents and the
3045 * chunk tree entries
3047 ret = btrfs_remove_chunk(trans, chunk_offset);
3048 btrfs_end_transaction(trans);
3052 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3054 struct btrfs_root *chunk_root = fs_info->chunk_root;
3055 struct btrfs_path *path;
3056 struct extent_buffer *leaf;
3057 struct btrfs_chunk *chunk;
3058 struct btrfs_key key;
3059 struct btrfs_key found_key;
3061 bool retried = false;
3065 path = btrfs_alloc_path();
3070 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3071 key.offset = (u64)-1;
3072 key.type = BTRFS_CHUNK_ITEM_KEY;
3075 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3076 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3078 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3081 BUG_ON(ret == 0); /* Corruption */
3083 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3086 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3092 leaf = path->nodes[0];
3093 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3095 chunk = btrfs_item_ptr(leaf, path->slots[0],
3096 struct btrfs_chunk);
3097 chunk_type = btrfs_chunk_type(leaf, chunk);
3098 btrfs_release_path(path);
3100 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3101 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3107 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3109 if (found_key.offset == 0)
3111 key.offset = found_key.offset - 1;
3114 if (failed && !retried) {
3118 } else if (WARN_ON(failed && retried)) {
3122 btrfs_free_path(path);
3127 * return 1 : allocate a data chunk successfully,
3128 * return <0: errors during allocating a data chunk,
3129 * return 0 : no need to allocate a data chunk.
3131 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3134 struct btrfs_block_group *cache;
3138 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3140 chunk_type = cache->flags;
3141 btrfs_put_block_group(cache);
3143 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3146 spin_lock(&fs_info->data_sinfo->lock);
3147 bytes_used = fs_info->data_sinfo->bytes_used;
3148 spin_unlock(&fs_info->data_sinfo->lock);
3151 struct btrfs_trans_handle *trans;
3154 trans = btrfs_join_transaction(fs_info->tree_root);
3156 return PTR_ERR(trans);
3158 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3159 btrfs_end_transaction(trans);
3168 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3169 struct btrfs_balance_control *bctl)
3171 struct btrfs_root *root = fs_info->tree_root;
3172 struct btrfs_trans_handle *trans;
3173 struct btrfs_balance_item *item;
3174 struct btrfs_disk_balance_args disk_bargs;
3175 struct btrfs_path *path;
3176 struct extent_buffer *leaf;
3177 struct btrfs_key key;
3180 path = btrfs_alloc_path();
3184 trans = btrfs_start_transaction(root, 0);
3185 if (IS_ERR(trans)) {
3186 btrfs_free_path(path);
3187 return PTR_ERR(trans);
3190 key.objectid = BTRFS_BALANCE_OBJECTID;
3191 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3194 ret = btrfs_insert_empty_item(trans, root, path, &key,
3199 leaf = path->nodes[0];
3200 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3202 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3204 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3205 btrfs_set_balance_data(leaf, item, &disk_bargs);
3206 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3207 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3208 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3209 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3211 btrfs_set_balance_flags(leaf, item, bctl->flags);
3213 btrfs_mark_buffer_dirty(leaf);
3215 btrfs_free_path(path);
3216 err = btrfs_commit_transaction(trans);
3222 static int del_balance_item(struct btrfs_fs_info *fs_info)
3224 struct btrfs_root *root = fs_info->tree_root;
3225 struct btrfs_trans_handle *trans;
3226 struct btrfs_path *path;
3227 struct btrfs_key key;
3230 path = btrfs_alloc_path();
3234 trans = btrfs_start_transaction(root, 0);
3235 if (IS_ERR(trans)) {
3236 btrfs_free_path(path);
3237 return PTR_ERR(trans);
3240 key.objectid = BTRFS_BALANCE_OBJECTID;
3241 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3244 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3252 ret = btrfs_del_item(trans, root, path);
3254 btrfs_free_path(path);
3255 err = btrfs_commit_transaction(trans);
3262 * This is a heuristic used to reduce the number of chunks balanced on
3263 * resume after balance was interrupted.
3265 static void update_balance_args(struct btrfs_balance_control *bctl)
3268 * Turn on soft mode for chunk types that were being converted.
3270 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3271 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3272 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3273 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3274 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3275 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3278 * Turn on usage filter if is not already used. The idea is
3279 * that chunks that we have already balanced should be
3280 * reasonably full. Don't do it for chunks that are being
3281 * converted - that will keep us from relocating unconverted
3282 * (albeit full) chunks.
3284 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3285 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3286 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3287 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3288 bctl->data.usage = 90;
3290 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3291 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3292 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3293 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3294 bctl->sys.usage = 90;
3296 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3297 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3298 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3299 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3300 bctl->meta.usage = 90;
3305 * Clear the balance status in fs_info and delete the balance item from disk.
3307 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3309 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3312 BUG_ON(!fs_info->balance_ctl);
3314 spin_lock(&fs_info->balance_lock);
3315 fs_info->balance_ctl = NULL;
3316 spin_unlock(&fs_info->balance_lock);
3319 ret = del_balance_item(fs_info);
3321 btrfs_handle_fs_error(fs_info, ret, NULL);
3325 * Balance filters. Return 1 if chunk should be filtered out
3326 * (should not be balanced).
3328 static int chunk_profiles_filter(u64 chunk_type,
3329 struct btrfs_balance_args *bargs)
3331 chunk_type = chunk_to_extended(chunk_type) &
3332 BTRFS_EXTENDED_PROFILE_MASK;
3334 if (bargs->profiles & chunk_type)
3340 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3341 struct btrfs_balance_args *bargs)
3343 struct btrfs_block_group *cache;
3345 u64 user_thresh_min;
3346 u64 user_thresh_max;
3349 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3350 chunk_used = cache->used;
3352 if (bargs->usage_min == 0)
3353 user_thresh_min = 0;
3355 user_thresh_min = div_factor_fine(cache->length,
3358 if (bargs->usage_max == 0)
3359 user_thresh_max = 1;
3360 else if (bargs->usage_max > 100)
3361 user_thresh_max = cache->length;
3363 user_thresh_max = div_factor_fine(cache->length,
3366 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3369 btrfs_put_block_group(cache);
3373 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3374 u64 chunk_offset, struct btrfs_balance_args *bargs)
3376 struct btrfs_block_group *cache;
3377 u64 chunk_used, user_thresh;
3380 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3381 chunk_used = cache->used;
3383 if (bargs->usage_min == 0)
3385 else if (bargs->usage > 100)
3386 user_thresh = cache->length;
3388 user_thresh = div_factor_fine(cache->length, bargs->usage);
3390 if (chunk_used < user_thresh)
3393 btrfs_put_block_group(cache);
3397 static int chunk_devid_filter(struct extent_buffer *leaf,
3398 struct btrfs_chunk *chunk,
3399 struct btrfs_balance_args *bargs)
3401 struct btrfs_stripe *stripe;
3402 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3405 for (i = 0; i < num_stripes; i++) {
3406 stripe = btrfs_stripe_nr(chunk, i);
3407 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3414 static u64 calc_data_stripes(u64 type, int num_stripes)
3416 const int index = btrfs_bg_flags_to_raid_index(type);
3417 const int ncopies = btrfs_raid_array[index].ncopies;
3418 const int nparity = btrfs_raid_array[index].nparity;
3421 return num_stripes - nparity;
3423 return num_stripes / ncopies;
3426 /* [pstart, pend) */
3427 static int chunk_drange_filter(struct extent_buffer *leaf,
3428 struct btrfs_chunk *chunk,
3429 struct btrfs_balance_args *bargs)
3431 struct btrfs_stripe *stripe;
3432 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3439 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3442 type = btrfs_chunk_type(leaf, chunk);
3443 factor = calc_data_stripes(type, num_stripes);
3445 for (i = 0; i < num_stripes; i++) {
3446 stripe = btrfs_stripe_nr(chunk, i);
3447 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3450 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3451 stripe_length = btrfs_chunk_length(leaf, chunk);
3452 stripe_length = div_u64(stripe_length, factor);
3454 if (stripe_offset < bargs->pend &&
3455 stripe_offset + stripe_length > bargs->pstart)
3462 /* [vstart, vend) */
3463 static int chunk_vrange_filter(struct extent_buffer *leaf,
3464 struct btrfs_chunk *chunk,
3466 struct btrfs_balance_args *bargs)
3468 if (chunk_offset < bargs->vend &&
3469 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3470 /* at least part of the chunk is inside this vrange */
3476 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3477 struct btrfs_chunk *chunk,
3478 struct btrfs_balance_args *bargs)
3480 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3482 if (bargs->stripes_min <= num_stripes
3483 && num_stripes <= bargs->stripes_max)
3489 static int chunk_soft_convert_filter(u64 chunk_type,
3490 struct btrfs_balance_args *bargs)
3492 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3495 chunk_type = chunk_to_extended(chunk_type) &
3496 BTRFS_EXTENDED_PROFILE_MASK;
3498 if (bargs->target == chunk_type)
3504 static int should_balance_chunk(struct extent_buffer *leaf,
3505 struct btrfs_chunk *chunk, u64 chunk_offset)
3507 struct btrfs_fs_info *fs_info = leaf->fs_info;
3508 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3509 struct btrfs_balance_args *bargs = NULL;
3510 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3513 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3514 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3518 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3519 bargs = &bctl->data;
3520 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3522 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3523 bargs = &bctl->meta;
3525 /* profiles filter */
3526 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3527 chunk_profiles_filter(chunk_type, bargs)) {
3532 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3533 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3535 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3536 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3541 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3542 chunk_devid_filter(leaf, chunk, bargs)) {
3546 /* drange filter, makes sense only with devid filter */
3547 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3548 chunk_drange_filter(leaf, chunk, bargs)) {
3553 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3554 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3558 /* stripes filter */
3559 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3560 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3564 /* soft profile changing mode */
3565 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3566 chunk_soft_convert_filter(chunk_type, bargs)) {
3571 * limited by count, must be the last filter
3573 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3574 if (bargs->limit == 0)
3578 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3580 * Same logic as the 'limit' filter; the minimum cannot be
3581 * determined here because we do not have the global information
3582 * about the count of all chunks that satisfy the filters.
3584 if (bargs->limit_max == 0)
3593 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3595 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3596 struct btrfs_root *chunk_root = fs_info->chunk_root;
3598 struct btrfs_chunk *chunk;
3599 struct btrfs_path *path = NULL;
3600 struct btrfs_key key;
3601 struct btrfs_key found_key;
3602 struct extent_buffer *leaf;
3605 int enospc_errors = 0;
3606 bool counting = true;
3607 /* The single value limit and min/max limits use the same bytes in the */
3608 u64 limit_data = bctl->data.limit;
3609 u64 limit_meta = bctl->meta.limit;
3610 u64 limit_sys = bctl->sys.limit;
3614 int chunk_reserved = 0;
3616 path = btrfs_alloc_path();
3622 /* zero out stat counters */
3623 spin_lock(&fs_info->balance_lock);
3624 memset(&bctl->stat, 0, sizeof(bctl->stat));
3625 spin_unlock(&fs_info->balance_lock);
3629 * The single value limit and min/max limits use the same bytes
3632 bctl->data.limit = limit_data;
3633 bctl->meta.limit = limit_meta;
3634 bctl->sys.limit = limit_sys;
3636 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3637 key.offset = (u64)-1;
3638 key.type = BTRFS_CHUNK_ITEM_KEY;
3641 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3642 atomic_read(&fs_info->balance_cancel_req)) {
3647 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3648 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3650 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3655 * this shouldn't happen, it means the last relocate
3659 BUG(); /* FIXME break ? */
3661 ret = btrfs_previous_item(chunk_root, path, 0,
3662 BTRFS_CHUNK_ITEM_KEY);
3664 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3669 leaf = path->nodes[0];
3670 slot = path->slots[0];
3671 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3673 if (found_key.objectid != key.objectid) {
3674 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3678 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3679 chunk_type = btrfs_chunk_type(leaf, chunk);
3682 spin_lock(&fs_info->balance_lock);
3683 bctl->stat.considered++;
3684 spin_unlock(&fs_info->balance_lock);
3687 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3689 btrfs_release_path(path);
3691 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3696 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3697 spin_lock(&fs_info->balance_lock);
3698 bctl->stat.expected++;
3699 spin_unlock(&fs_info->balance_lock);
3701 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3703 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3705 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3712 * Apply limit_min filter, no need to check if the LIMITS
3713 * filter is used, limit_min is 0 by default
3715 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3716 count_data < bctl->data.limit_min)
3717 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3718 count_meta < bctl->meta.limit_min)
3719 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3720 count_sys < bctl->sys.limit_min)) {
3721 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3725 if (!chunk_reserved) {
3727 * We may be relocating the only data chunk we have,
3728 * which could potentially end up with losing data's
3729 * raid profile, so lets allocate an empty one in
3732 ret = btrfs_may_alloc_data_chunk(fs_info,
3735 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3737 } else if (ret == 1) {
3742 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3743 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3744 if (ret == -ENOSPC) {
3746 } else if (ret == -ETXTBSY) {
3748 "skipping relocation of block group %llu due to active swapfile",
3754 spin_lock(&fs_info->balance_lock);
3755 bctl->stat.completed++;
3756 spin_unlock(&fs_info->balance_lock);
3759 if (found_key.offset == 0)
3761 key.offset = found_key.offset - 1;
3765 btrfs_release_path(path);
3770 btrfs_free_path(path);
3771 if (enospc_errors) {
3772 btrfs_info(fs_info, "%d enospc errors during balance",
3782 * alloc_profile_is_valid - see if a given profile is valid and reduced
3783 * @flags: profile to validate
3784 * @extended: if true @flags is treated as an extended profile
3786 static int alloc_profile_is_valid(u64 flags, int extended)
3788 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3789 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3791 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3793 /* 1) check that all other bits are zeroed */
3797 /* 2) see if profile is reduced */
3799 return !extended; /* "0" is valid for usual profiles */
3801 return has_single_bit_set(flags);
3804 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3806 /* cancel requested || normal exit path */
3807 return atomic_read(&fs_info->balance_cancel_req) ||
3808 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3809 atomic_read(&fs_info->balance_cancel_req) == 0);
3813 * Validate target profile against allowed profiles and return true if it's OK.
3814 * Otherwise print the error message and return false.
3816 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
3817 const struct btrfs_balance_args *bargs,
3818 u64 allowed, const char *type)
3820 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3823 /* Profile is valid and does not have bits outside of the allowed set */
3824 if (alloc_profile_is_valid(bargs->target, 1) &&
3825 (bargs->target & ~allowed) == 0)
3828 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
3829 type, btrfs_bg_type_to_raid_name(bargs->target));
3834 * Fill @buf with textual description of balance filter flags @bargs, up to
3835 * @size_buf including the terminating null. The output may be trimmed if it
3836 * does not fit into the provided buffer.
3838 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3842 u32 size_bp = size_buf;
3844 u64 flags = bargs->flags;
3845 char tmp_buf[128] = {'\0'};
3850 #define CHECK_APPEND_NOARG(a) \
3852 ret = snprintf(bp, size_bp, (a)); \
3853 if (ret < 0 || ret >= size_bp) \
3854 goto out_overflow; \
3859 #define CHECK_APPEND_1ARG(a, v1) \
3861 ret = snprintf(bp, size_bp, (a), (v1)); \
3862 if (ret < 0 || ret >= size_bp) \
3863 goto out_overflow; \
3868 #define CHECK_APPEND_2ARG(a, v1, v2) \
3870 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3871 if (ret < 0 || ret >= size_bp) \
3872 goto out_overflow; \
3877 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
3878 CHECK_APPEND_1ARG("convert=%s,",
3879 btrfs_bg_type_to_raid_name(bargs->target));
3881 if (flags & BTRFS_BALANCE_ARGS_SOFT)
3882 CHECK_APPEND_NOARG("soft,");
3884 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
3885 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
3887 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
3890 if (flags & BTRFS_BALANCE_ARGS_USAGE)
3891 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
3893 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
3894 CHECK_APPEND_2ARG("usage=%u..%u,",
3895 bargs->usage_min, bargs->usage_max);
3897 if (flags & BTRFS_BALANCE_ARGS_DEVID)
3898 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
3900 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
3901 CHECK_APPEND_2ARG("drange=%llu..%llu,",
3902 bargs->pstart, bargs->pend);
3904 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
3905 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
3906 bargs->vstart, bargs->vend);
3908 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
3909 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
3911 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
3912 CHECK_APPEND_2ARG("limit=%u..%u,",
3913 bargs->limit_min, bargs->limit_max);
3915 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
3916 CHECK_APPEND_2ARG("stripes=%u..%u,",
3917 bargs->stripes_min, bargs->stripes_max);
3919 #undef CHECK_APPEND_2ARG
3920 #undef CHECK_APPEND_1ARG
3921 #undef CHECK_APPEND_NOARG
3925 if (size_bp < size_buf)
3926 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
3931 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
3933 u32 size_buf = 1024;
3934 char tmp_buf[192] = {'\0'};
3937 u32 size_bp = size_buf;
3939 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3941 buf = kzalloc(size_buf, GFP_KERNEL);
3947 #define CHECK_APPEND_1ARG(a, v1) \
3949 ret = snprintf(bp, size_bp, (a), (v1)); \
3950 if (ret < 0 || ret >= size_bp) \
3951 goto out_overflow; \
3956 if (bctl->flags & BTRFS_BALANCE_FORCE)
3957 CHECK_APPEND_1ARG("%s", "-f ");
3959 if (bctl->flags & BTRFS_BALANCE_DATA) {
3960 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
3961 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
3964 if (bctl->flags & BTRFS_BALANCE_METADATA) {
3965 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
3966 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
3969 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
3970 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
3971 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
3974 #undef CHECK_APPEND_1ARG
3978 if (size_bp < size_buf)
3979 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
3980 btrfs_info(fs_info, "balance: %s %s",
3981 (bctl->flags & BTRFS_BALANCE_RESUME) ?
3982 "resume" : "start", buf);
3988 * Should be called with balance mutexe held
3990 int btrfs_balance(struct btrfs_fs_info *fs_info,
3991 struct btrfs_balance_control *bctl,
3992 struct btrfs_ioctl_balance_args *bargs)
3994 u64 meta_target, data_target;
4000 bool reducing_redundancy;
4003 if (btrfs_fs_closing(fs_info) ||
4004 atomic_read(&fs_info->balance_pause_req) ||
4005 btrfs_should_cancel_balance(fs_info)) {
4010 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4011 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4015 * In case of mixed groups both data and meta should be picked,
4016 * and identical options should be given for both of them.
4018 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4019 if (mixed && (bctl->flags & allowed)) {
4020 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4021 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4022 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4024 "balance: mixed groups data and metadata options must be the same");
4031 * rw_devices will not change at the moment, device add/delete/replace
4032 * are excluded by EXCL_OP
4034 num_devices = fs_info->fs_devices->rw_devices;
4037 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4038 * special bit for it, to make it easier to distinguish. Thus we need
4039 * to set it manually, or balance would refuse the profile.
4041 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4042 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4043 if (num_devices >= btrfs_raid_array[i].devs_min)
4044 allowed |= btrfs_raid_array[i].bg_flag;
4046 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4047 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4048 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
4054 * Allow to reduce metadata or system integrity only if force set for
4055 * profiles with redundancy (copies, parity)
4058 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4059 if (btrfs_raid_array[i].ncopies >= 2 ||
4060 btrfs_raid_array[i].tolerated_failures >= 1)
4061 allowed |= btrfs_raid_array[i].bg_flag;
4064 seq = read_seqbegin(&fs_info->profiles_lock);
4066 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4067 (fs_info->avail_system_alloc_bits & allowed) &&
4068 !(bctl->sys.target & allowed)) ||
4069 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4070 (fs_info->avail_metadata_alloc_bits & allowed) &&
4071 !(bctl->meta.target & allowed)))
4072 reducing_redundancy = true;
4074 reducing_redundancy = false;
4076 /* if we're not converting, the target field is uninitialized */
4077 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4078 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4079 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4080 bctl->data.target : fs_info->avail_data_alloc_bits;
4081 } while (read_seqretry(&fs_info->profiles_lock, seq));
4083 if (reducing_redundancy) {
4084 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4086 "balance: force reducing metadata redundancy");
4089 "balance: reduces metadata redundancy, use --force if you want this");
4095 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4096 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4098 "balance: metadata profile %s has lower redundancy than data profile %s",
4099 btrfs_bg_type_to_raid_name(meta_target),
4100 btrfs_bg_type_to_raid_name(data_target));
4103 if (fs_info->send_in_progress) {
4104 btrfs_warn_rl(fs_info,
4105 "cannot run balance while send operations are in progress (%d in progress)",
4106 fs_info->send_in_progress);
4111 ret = insert_balance_item(fs_info, bctl);
4112 if (ret && ret != -EEXIST)
4115 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4116 BUG_ON(ret == -EEXIST);
4117 BUG_ON(fs_info->balance_ctl);
4118 spin_lock(&fs_info->balance_lock);
4119 fs_info->balance_ctl = bctl;
4120 spin_unlock(&fs_info->balance_lock);
4122 BUG_ON(ret != -EEXIST);
4123 spin_lock(&fs_info->balance_lock);
4124 update_balance_args(bctl);
4125 spin_unlock(&fs_info->balance_lock);
4128 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4129 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4130 describe_balance_start_or_resume(fs_info);
4131 mutex_unlock(&fs_info->balance_mutex);
4133 ret = __btrfs_balance(fs_info);
4135 mutex_lock(&fs_info->balance_mutex);
4136 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4137 btrfs_info(fs_info, "balance: paused");
4138 else if (ret == -ECANCELED && atomic_read(&fs_info->balance_cancel_req))
4139 btrfs_info(fs_info, "balance: canceled");
4141 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4143 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4146 memset(bargs, 0, sizeof(*bargs));
4147 btrfs_update_ioctl_balance_args(fs_info, bargs);
4150 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4151 balance_need_close(fs_info)) {
4152 reset_balance_state(fs_info);
4153 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4156 wake_up(&fs_info->balance_wait_q);
4160 if (bctl->flags & BTRFS_BALANCE_RESUME)
4161 reset_balance_state(fs_info);
4164 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4169 static int balance_kthread(void *data)
4171 struct btrfs_fs_info *fs_info = data;
4174 mutex_lock(&fs_info->balance_mutex);
4175 if (fs_info->balance_ctl)
4176 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4177 mutex_unlock(&fs_info->balance_mutex);
4182 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4184 struct task_struct *tsk;
4186 mutex_lock(&fs_info->balance_mutex);
4187 if (!fs_info->balance_ctl) {
4188 mutex_unlock(&fs_info->balance_mutex);
4191 mutex_unlock(&fs_info->balance_mutex);
4193 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4194 btrfs_info(fs_info, "balance: resume skipped");
4199 * A ro->rw remount sequence should continue with the paused balance
4200 * regardless of who pauses it, system or the user as of now, so set
4203 spin_lock(&fs_info->balance_lock);
4204 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4205 spin_unlock(&fs_info->balance_lock);
4207 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4208 return PTR_ERR_OR_ZERO(tsk);
4211 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4213 struct btrfs_balance_control *bctl;
4214 struct btrfs_balance_item *item;
4215 struct btrfs_disk_balance_args disk_bargs;
4216 struct btrfs_path *path;
4217 struct extent_buffer *leaf;
4218 struct btrfs_key key;
4221 path = btrfs_alloc_path();
4225 key.objectid = BTRFS_BALANCE_OBJECTID;
4226 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4229 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4232 if (ret > 0) { /* ret = -ENOENT; */
4237 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4243 leaf = path->nodes[0];
4244 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4246 bctl->flags = btrfs_balance_flags(leaf, item);
4247 bctl->flags |= BTRFS_BALANCE_RESUME;
4249 btrfs_balance_data(leaf, item, &disk_bargs);
4250 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4251 btrfs_balance_meta(leaf, item, &disk_bargs);
4252 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4253 btrfs_balance_sys(leaf, item, &disk_bargs);
4254 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4257 * This should never happen, as the paused balance state is recovered
4258 * during mount without any chance of other exclusive ops to collide.
4260 * This gives the exclusive op status to balance and keeps in paused
4261 * state until user intervention (cancel or umount). If the ownership
4262 * cannot be assigned, show a message but do not fail. The balance
4263 * is in a paused state and must have fs_info::balance_ctl properly
4266 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4268 "balance: cannot set exclusive op status, resume manually");
4270 mutex_lock(&fs_info->balance_mutex);
4271 BUG_ON(fs_info->balance_ctl);
4272 spin_lock(&fs_info->balance_lock);
4273 fs_info->balance_ctl = bctl;
4274 spin_unlock(&fs_info->balance_lock);
4275 mutex_unlock(&fs_info->balance_mutex);
4277 btrfs_free_path(path);
4281 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4285 mutex_lock(&fs_info->balance_mutex);
4286 if (!fs_info->balance_ctl) {
4287 mutex_unlock(&fs_info->balance_mutex);
4291 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4292 atomic_inc(&fs_info->balance_pause_req);
4293 mutex_unlock(&fs_info->balance_mutex);
4295 wait_event(fs_info->balance_wait_q,
4296 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4298 mutex_lock(&fs_info->balance_mutex);
4299 /* we are good with balance_ctl ripped off from under us */
4300 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4301 atomic_dec(&fs_info->balance_pause_req);
4306 mutex_unlock(&fs_info->balance_mutex);
4310 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4312 mutex_lock(&fs_info->balance_mutex);
4313 if (!fs_info->balance_ctl) {
4314 mutex_unlock(&fs_info->balance_mutex);
4319 * A paused balance with the item stored on disk can be resumed at
4320 * mount time if the mount is read-write. Otherwise it's still paused
4321 * and we must not allow cancelling as it deletes the item.
4323 if (sb_rdonly(fs_info->sb)) {
4324 mutex_unlock(&fs_info->balance_mutex);
4328 atomic_inc(&fs_info->balance_cancel_req);
4330 * if we are running just wait and return, balance item is
4331 * deleted in btrfs_balance in this case
4333 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4334 mutex_unlock(&fs_info->balance_mutex);
4335 wait_event(fs_info->balance_wait_q,
4336 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4337 mutex_lock(&fs_info->balance_mutex);
4339 mutex_unlock(&fs_info->balance_mutex);
4341 * Lock released to allow other waiters to continue, we'll
4342 * reexamine the status again.
4344 mutex_lock(&fs_info->balance_mutex);
4346 if (fs_info->balance_ctl) {
4347 reset_balance_state(fs_info);
4348 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4349 btrfs_info(fs_info, "balance: canceled");
4353 BUG_ON(fs_info->balance_ctl ||
4354 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4355 atomic_dec(&fs_info->balance_cancel_req);
4356 mutex_unlock(&fs_info->balance_mutex);
4360 int btrfs_uuid_scan_kthread(void *data)
4362 struct btrfs_fs_info *fs_info = data;
4363 struct btrfs_root *root = fs_info->tree_root;
4364 struct btrfs_key key;
4365 struct btrfs_path *path = NULL;
4367 struct extent_buffer *eb;
4369 struct btrfs_root_item root_item;
4371 struct btrfs_trans_handle *trans = NULL;
4372 bool closing = false;
4374 path = btrfs_alloc_path();
4381 key.type = BTRFS_ROOT_ITEM_KEY;
4385 if (btrfs_fs_closing(fs_info)) {
4389 ret = btrfs_search_forward(root, &key, path,
4390 BTRFS_OLDEST_GENERATION);
4397 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4398 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4399 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4400 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4403 eb = path->nodes[0];
4404 slot = path->slots[0];
4405 item_size = btrfs_item_size_nr(eb, slot);
4406 if (item_size < sizeof(root_item))
4409 read_extent_buffer(eb, &root_item,
4410 btrfs_item_ptr_offset(eb, slot),
4411 (int)sizeof(root_item));
4412 if (btrfs_root_refs(&root_item) == 0)
4415 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4416 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4420 btrfs_release_path(path);
4422 * 1 - subvol uuid item
4423 * 1 - received_subvol uuid item
4425 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4426 if (IS_ERR(trans)) {
4427 ret = PTR_ERR(trans);
4435 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4436 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4437 BTRFS_UUID_KEY_SUBVOL,
4440 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4446 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4447 ret = btrfs_uuid_tree_add(trans,
4448 root_item.received_uuid,
4449 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4452 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4460 ret = btrfs_end_transaction(trans);
4466 btrfs_release_path(path);
4467 if (key.offset < (u64)-1) {
4469 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4471 key.type = BTRFS_ROOT_ITEM_KEY;
4472 } else if (key.objectid < (u64)-1) {
4474 key.type = BTRFS_ROOT_ITEM_KEY;
4483 btrfs_free_path(path);
4484 if (trans && !IS_ERR(trans))
4485 btrfs_end_transaction(trans);
4487 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4489 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4490 up(&fs_info->uuid_tree_rescan_sem);
4494 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4496 struct btrfs_trans_handle *trans;
4497 struct btrfs_root *tree_root = fs_info->tree_root;
4498 struct btrfs_root *uuid_root;
4499 struct task_struct *task;
4506 trans = btrfs_start_transaction(tree_root, 2);
4508 return PTR_ERR(trans);
4510 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4511 if (IS_ERR(uuid_root)) {
4512 ret = PTR_ERR(uuid_root);
4513 btrfs_abort_transaction(trans, ret);
4514 btrfs_end_transaction(trans);
4518 fs_info->uuid_root = uuid_root;
4520 ret = btrfs_commit_transaction(trans);
4524 down(&fs_info->uuid_tree_rescan_sem);
4525 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4527 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4528 btrfs_warn(fs_info, "failed to start uuid_scan task");
4529 up(&fs_info->uuid_tree_rescan_sem);
4530 return PTR_ERR(task);
4537 * shrinking a device means finding all of the device extents past
4538 * the new size, and then following the back refs to the chunks.
4539 * The chunk relocation code actually frees the device extent
4541 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4543 struct btrfs_fs_info *fs_info = device->fs_info;
4544 struct btrfs_root *root = fs_info->dev_root;
4545 struct btrfs_trans_handle *trans;
4546 struct btrfs_dev_extent *dev_extent = NULL;
4547 struct btrfs_path *path;
4553 bool retried = false;
4554 struct extent_buffer *l;
4555 struct btrfs_key key;
4556 struct btrfs_super_block *super_copy = fs_info->super_copy;
4557 u64 old_total = btrfs_super_total_bytes(super_copy);
4558 u64 old_size = btrfs_device_get_total_bytes(device);
4562 new_size = round_down(new_size, fs_info->sectorsize);
4564 diff = round_down(old_size - new_size, fs_info->sectorsize);
4566 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4569 path = btrfs_alloc_path();
4573 path->reada = READA_BACK;
4575 trans = btrfs_start_transaction(root, 0);
4576 if (IS_ERR(trans)) {
4577 btrfs_free_path(path);
4578 return PTR_ERR(trans);
4581 mutex_lock(&fs_info->chunk_mutex);
4583 btrfs_device_set_total_bytes(device, new_size);
4584 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4585 device->fs_devices->total_rw_bytes -= diff;
4586 atomic64_sub(diff, &fs_info->free_chunk_space);
4590 * Once the device's size has been set to the new size, ensure all
4591 * in-memory chunks are synced to disk so that the loop below sees them
4592 * and relocates them accordingly.
4594 if (contains_pending_extent(device, &start, diff)) {
4595 mutex_unlock(&fs_info->chunk_mutex);
4596 ret = btrfs_commit_transaction(trans);
4600 mutex_unlock(&fs_info->chunk_mutex);
4601 btrfs_end_transaction(trans);
4605 key.objectid = device->devid;
4606 key.offset = (u64)-1;
4607 key.type = BTRFS_DEV_EXTENT_KEY;
4610 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4611 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4613 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4617 ret = btrfs_previous_item(root, path, 0, key.type);
4619 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4624 btrfs_release_path(path);
4629 slot = path->slots[0];
4630 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4632 if (key.objectid != device->devid) {
4633 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4634 btrfs_release_path(path);
4638 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4639 length = btrfs_dev_extent_length(l, dev_extent);
4641 if (key.offset + length <= new_size) {
4642 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4643 btrfs_release_path(path);
4647 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4648 btrfs_release_path(path);
4651 * We may be relocating the only data chunk we have,
4652 * which could potentially end up with losing data's
4653 * raid profile, so lets allocate an empty one in
4656 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4658 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4662 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4663 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4664 if (ret == -ENOSPC) {
4667 if (ret == -ETXTBSY) {
4669 "could not shrink block group %llu due to active swapfile",
4674 } while (key.offset-- > 0);
4676 if (failed && !retried) {
4680 } else if (failed && retried) {
4685 /* Shrinking succeeded, else we would be at "done". */
4686 trans = btrfs_start_transaction(root, 0);
4687 if (IS_ERR(trans)) {
4688 ret = PTR_ERR(trans);
4692 mutex_lock(&fs_info->chunk_mutex);
4693 btrfs_device_set_disk_total_bytes(device, new_size);
4694 if (list_empty(&device->post_commit_list))
4695 list_add_tail(&device->post_commit_list,
4696 &trans->transaction->dev_update_list);
4698 WARN_ON(diff > old_total);
4699 btrfs_set_super_total_bytes(super_copy,
4700 round_down(old_total - diff, fs_info->sectorsize));
4701 mutex_unlock(&fs_info->chunk_mutex);
4703 /* Now btrfs_update_device() will change the on-disk size. */
4704 ret = btrfs_update_device(trans, device);
4706 btrfs_abort_transaction(trans, ret);
4707 btrfs_end_transaction(trans);
4709 ret = btrfs_commit_transaction(trans);
4712 btrfs_free_path(path);
4714 mutex_lock(&fs_info->chunk_mutex);
4715 btrfs_device_set_total_bytes(device, old_size);
4716 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4717 device->fs_devices->total_rw_bytes += diff;
4718 atomic64_add(diff, &fs_info->free_chunk_space);
4719 mutex_unlock(&fs_info->chunk_mutex);
4724 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4725 struct btrfs_key *key,
4726 struct btrfs_chunk *chunk, int item_size)
4728 struct btrfs_super_block *super_copy = fs_info->super_copy;
4729 struct btrfs_disk_key disk_key;
4733 mutex_lock(&fs_info->chunk_mutex);
4734 array_size = btrfs_super_sys_array_size(super_copy);
4735 if (array_size + item_size + sizeof(disk_key)
4736 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4737 mutex_unlock(&fs_info->chunk_mutex);
4741 ptr = super_copy->sys_chunk_array + array_size;
4742 btrfs_cpu_key_to_disk(&disk_key, key);
4743 memcpy(ptr, &disk_key, sizeof(disk_key));
4744 ptr += sizeof(disk_key);
4745 memcpy(ptr, chunk, item_size);
4746 item_size += sizeof(disk_key);
4747 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4748 mutex_unlock(&fs_info->chunk_mutex);
4754 * sort the devices in descending order by max_avail, total_avail
4756 static int btrfs_cmp_device_info(const void *a, const void *b)
4758 const struct btrfs_device_info *di_a = a;
4759 const struct btrfs_device_info *di_b = b;
4761 if (di_a->max_avail > di_b->max_avail)
4763 if (di_a->max_avail < di_b->max_avail)
4765 if (di_a->total_avail > di_b->total_avail)
4767 if (di_a->total_avail < di_b->total_avail)
4772 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4774 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4777 btrfs_set_fs_incompat(info, RAID56);
4780 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
4782 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
4785 btrfs_set_fs_incompat(info, RAID1C34);
4789 * Structure used internally for __btrfs_alloc_chunk() function.
4790 * Wraps needed parameters.
4792 struct alloc_chunk_ctl {
4795 /* Total number of stripes to allocate */
4797 /* sub_stripes info for map */
4799 /* Stripes per device */
4801 /* Maximum number of devices to use */
4803 /* Minimum number of devices to use */
4805 /* ndevs has to be a multiple of this */
4807 /* Number of copies */
4809 /* Number of stripes worth of bytes to store parity information */
4811 u64 max_stripe_size;
4819 static void init_alloc_chunk_ctl_policy_regular(
4820 struct btrfs_fs_devices *fs_devices,
4821 struct alloc_chunk_ctl *ctl)
4823 u64 type = ctl->type;
4825 if (type & BTRFS_BLOCK_GROUP_DATA) {
4826 ctl->max_stripe_size = SZ_1G;
4827 ctl->max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4828 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4829 /* For larger filesystems, use larger metadata chunks */
4830 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4831 ctl->max_stripe_size = SZ_1G;
4833 ctl->max_stripe_size = SZ_256M;
4834 ctl->max_chunk_size = ctl->max_stripe_size;
4835 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4836 ctl->max_stripe_size = SZ_32M;
4837 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
4838 ctl->devs_max = min_t(int, ctl->devs_max,
4839 BTRFS_MAX_DEVS_SYS_CHUNK);
4844 /* We don't want a chunk larger than 10% of writable space */
4845 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4846 ctl->max_chunk_size);
4847 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
4850 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
4851 struct alloc_chunk_ctl *ctl)
4853 int index = btrfs_bg_flags_to_raid_index(ctl->type);
4855 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
4856 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
4857 ctl->devs_max = btrfs_raid_array[index].devs_max;
4859 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
4860 ctl->devs_min = btrfs_raid_array[index].devs_min;
4861 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
4862 ctl->ncopies = btrfs_raid_array[index].ncopies;
4863 ctl->nparity = btrfs_raid_array[index].nparity;
4866 switch (fs_devices->chunk_alloc_policy) {
4867 case BTRFS_CHUNK_ALLOC_REGULAR:
4868 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
4875 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
4876 struct alloc_chunk_ctl *ctl,
4877 struct btrfs_device_info *devices_info)
4879 struct btrfs_fs_info *info = fs_devices->fs_info;
4880 struct btrfs_device *device;
4882 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
4889 * in the first pass through the devices list, we gather information
4890 * about the available holes on each device.
4892 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4893 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4895 "BTRFS: read-only device in alloc_list\n");
4899 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4900 &device->dev_state) ||
4901 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4904 if (device->total_bytes > device->bytes_used)
4905 total_avail = device->total_bytes - device->bytes_used;
4909 /* If there is no space on this device, skip it. */
4910 if (total_avail < ctl->dev_extent_min)
4913 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
4915 if (ret && ret != -ENOSPC)
4919 max_avail = dev_extent_want;
4921 if (max_avail < ctl->dev_extent_min) {
4922 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4924 "%s: devid %llu has no free space, have=%llu want=%llu",
4925 __func__, device->devid, max_avail,
4926 ctl->dev_extent_min);
4930 if (ndevs == fs_devices->rw_devices) {
4931 WARN(1, "%s: found more than %llu devices\n",
4932 __func__, fs_devices->rw_devices);
4935 devices_info[ndevs].dev_offset = dev_offset;
4936 devices_info[ndevs].max_avail = max_avail;
4937 devices_info[ndevs].total_avail = total_avail;
4938 devices_info[ndevs].dev = device;
4944 * now sort the devices by hole size / available space
4946 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4947 btrfs_cmp_device_info, NULL);
4952 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
4953 struct btrfs_device_info *devices_info)
4955 /* Number of stripes that count for block group size */
4959 * The primary goal is to maximize the number of stripes, so use as
4960 * many devices as possible, even if the stripes are not maximum sized.
4962 * The DUP profile stores more than one stripe per device, the
4963 * max_avail is the total size so we have to adjust.
4965 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
4967 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
4969 /* This will have to be fixed for RAID1 and RAID10 over more drives */
4970 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
4973 * Use the number of data stripes to figure out how big this chunk is
4974 * really going to be in terms of logical address space, and compare
4975 * that answer with the max chunk size. If it's higher, we try to
4976 * reduce stripe_size.
4978 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
4980 * Reduce stripe_size, round it up to a 16MB boundary again and
4981 * then use it, unless it ends up being even bigger than the
4982 * previous value we had already.
4984 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
4985 data_stripes), SZ_16M),
4989 /* Align to BTRFS_STRIPE_LEN */
4990 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
4991 ctl->chunk_size = ctl->stripe_size * data_stripes;
4996 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
4997 struct alloc_chunk_ctl *ctl,
4998 struct btrfs_device_info *devices_info)
5000 struct btrfs_fs_info *info = fs_devices->fs_info;
5003 * Round down to number of usable stripes, devs_increment can be any
5004 * number so we can't use round_down() that requires power of 2, while
5005 * rounddown is safe.
5007 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5009 if (ctl->ndevs < ctl->devs_min) {
5010 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5012 "%s: not enough devices with free space: have=%d minimum required=%d",
5013 __func__, ctl->ndevs, ctl->devs_min);
5018 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5020 switch (fs_devices->chunk_alloc_policy) {
5021 case BTRFS_CHUNK_ALLOC_REGULAR:
5022 return decide_stripe_size_regular(ctl, devices_info);
5028 static int create_chunk(struct btrfs_trans_handle *trans,
5029 struct alloc_chunk_ctl *ctl,
5030 struct btrfs_device_info *devices_info)
5032 struct btrfs_fs_info *info = trans->fs_info;
5033 struct map_lookup *map = NULL;
5034 struct extent_map_tree *em_tree;
5035 struct extent_map *em;
5036 u64 start = ctl->start;
5037 u64 type = ctl->type;
5042 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5045 map->num_stripes = ctl->num_stripes;
5047 for (i = 0; i < ctl->ndevs; ++i) {
5048 for (j = 0; j < ctl->dev_stripes; ++j) {
5049 int s = i * ctl->dev_stripes + j;
5050 map->stripes[s].dev = devices_info[i].dev;
5051 map->stripes[s].physical = devices_info[i].dev_offset +
5052 j * ctl->stripe_size;
5055 map->stripe_len = BTRFS_STRIPE_LEN;
5056 map->io_align = BTRFS_STRIPE_LEN;
5057 map->io_width = BTRFS_STRIPE_LEN;
5059 map->sub_stripes = ctl->sub_stripes;
5061 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5063 em = alloc_extent_map();
5068 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5069 em->map_lookup = map;
5071 em->len = ctl->chunk_size;
5072 em->block_start = 0;
5073 em->block_len = em->len;
5074 em->orig_block_len = ctl->stripe_size;
5076 em_tree = &info->mapping_tree;
5077 write_lock(&em_tree->lock);
5078 ret = add_extent_mapping(em_tree, em, 0);
5080 write_unlock(&em_tree->lock);
5081 free_extent_map(em);
5084 write_unlock(&em_tree->lock);
5086 ret = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5088 goto error_del_extent;
5090 for (i = 0; i < map->num_stripes; i++) {
5091 struct btrfs_device *dev = map->stripes[i].dev;
5093 btrfs_device_set_bytes_used(dev,
5094 dev->bytes_used + ctl->stripe_size);
5095 if (list_empty(&dev->post_commit_list))
5096 list_add_tail(&dev->post_commit_list,
5097 &trans->transaction->dev_update_list);
5100 atomic64_sub(ctl->stripe_size * map->num_stripes,
5101 &info->free_chunk_space);
5103 free_extent_map(em);
5104 check_raid56_incompat_flag(info, type);
5105 check_raid1c34_incompat_flag(info, type);
5110 write_lock(&em_tree->lock);
5111 remove_extent_mapping(em_tree, em);
5112 write_unlock(&em_tree->lock);
5114 /* One for our allocation */
5115 free_extent_map(em);
5116 /* One for the tree reference */
5117 free_extent_map(em);
5122 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5124 struct btrfs_fs_info *info = trans->fs_info;
5125 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5126 struct btrfs_device_info *devices_info = NULL;
5127 struct alloc_chunk_ctl ctl;
5130 lockdep_assert_held(&info->chunk_mutex);
5132 if (!alloc_profile_is_valid(type, 0)) {
5137 if (list_empty(&fs_devices->alloc_list)) {
5138 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5139 btrfs_debug(info, "%s: no writable device", __func__);
5143 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5144 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5149 ctl.start = find_next_chunk(info);
5151 init_alloc_chunk_ctl(fs_devices, &ctl);
5153 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5158 ret = gather_device_info(fs_devices, &ctl, devices_info);
5162 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5166 ret = create_chunk(trans, &ctl, devices_info);
5169 kfree(devices_info);
5174 * Chunk allocation falls into two parts. The first part does work
5175 * that makes the new allocated chunk usable, but does not do any operation
5176 * that modifies the chunk tree. The second part does the work that
5177 * requires modifying the chunk tree. This division is important for the
5178 * bootstrap process of adding storage to a seed btrfs.
5180 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5181 u64 chunk_offset, u64 chunk_size)
5183 struct btrfs_fs_info *fs_info = trans->fs_info;
5184 struct btrfs_root *extent_root = fs_info->extent_root;
5185 struct btrfs_root *chunk_root = fs_info->chunk_root;
5186 struct btrfs_key key;
5187 struct btrfs_device *device;
5188 struct btrfs_chunk *chunk;
5189 struct btrfs_stripe *stripe;
5190 struct extent_map *em;
5191 struct map_lookup *map;
5198 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5202 map = em->map_lookup;
5203 item_size = btrfs_chunk_item_size(map->num_stripes);
5204 stripe_size = em->orig_block_len;
5206 chunk = kzalloc(item_size, GFP_NOFS);
5213 * Take the device list mutex to prevent races with the final phase of
5214 * a device replace operation that replaces the device object associated
5215 * with the map's stripes, because the device object's id can change
5216 * at any time during that final phase of the device replace operation
5217 * (dev-replace.c:btrfs_dev_replace_finishing()).
5219 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5220 for (i = 0; i < map->num_stripes; i++) {
5221 device = map->stripes[i].dev;
5222 dev_offset = map->stripes[i].physical;
5224 ret = btrfs_update_device(trans, device);
5227 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5228 dev_offset, stripe_size);
5233 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5237 stripe = &chunk->stripe;
5238 for (i = 0; i < map->num_stripes; i++) {
5239 device = map->stripes[i].dev;
5240 dev_offset = map->stripes[i].physical;
5242 btrfs_set_stack_stripe_devid(stripe, device->devid);
5243 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5244 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5247 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5249 btrfs_set_stack_chunk_length(chunk, chunk_size);
5250 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5251 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5252 btrfs_set_stack_chunk_type(chunk, map->type);
5253 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5254 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5255 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5256 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5257 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5259 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5260 key.type = BTRFS_CHUNK_ITEM_KEY;
5261 key.offset = chunk_offset;
5263 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5264 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5266 * TODO: Cleanup of inserted chunk root in case of
5269 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5274 free_extent_map(em);
5278 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5280 struct btrfs_fs_info *fs_info = trans->fs_info;
5284 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5285 ret = btrfs_alloc_chunk(trans, alloc_profile);
5289 alloc_profile = btrfs_system_alloc_profile(fs_info);
5290 ret = btrfs_alloc_chunk(trans, alloc_profile);
5294 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5296 const int index = btrfs_bg_flags_to_raid_index(map->type);
5298 return btrfs_raid_array[index].tolerated_failures;
5301 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5303 struct extent_map *em;
5304 struct map_lookup *map;
5309 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5313 map = em->map_lookup;
5314 for (i = 0; i < map->num_stripes; i++) {
5315 if (test_bit(BTRFS_DEV_STATE_MISSING,
5316 &map->stripes[i].dev->dev_state)) {
5320 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5321 &map->stripes[i].dev->dev_state)) {
5328 * If the number of missing devices is larger than max errors,
5329 * we can not write the data into that chunk successfully, so
5332 if (miss_ndevs > btrfs_chunk_max_errors(map))
5335 free_extent_map(em);
5339 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5341 struct extent_map *em;
5344 write_lock(&tree->lock);
5345 em = lookup_extent_mapping(tree, 0, (u64)-1);
5347 remove_extent_mapping(tree, em);
5348 write_unlock(&tree->lock);
5352 free_extent_map(em);
5353 /* once for the tree */
5354 free_extent_map(em);
5358 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5360 struct extent_map *em;
5361 struct map_lookup *map;
5364 em = btrfs_get_chunk_map(fs_info, logical, len);
5367 * We could return errors for these cases, but that could get
5368 * ugly and we'd probably do the same thing which is just not do
5369 * anything else and exit, so return 1 so the callers don't try
5370 * to use other copies.
5374 map = em->map_lookup;
5375 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5376 ret = map->num_stripes;
5377 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5378 ret = map->sub_stripes;
5379 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5381 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5383 * There could be two corrupted data stripes, we need
5384 * to loop retry in order to rebuild the correct data.
5386 * Fail a stripe at a time on every retry except the
5387 * stripe under reconstruction.
5389 ret = map->num_stripes;
5392 free_extent_map(em);
5394 down_read(&fs_info->dev_replace.rwsem);
5395 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5396 fs_info->dev_replace.tgtdev)
5398 up_read(&fs_info->dev_replace.rwsem);
5403 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5406 struct extent_map *em;
5407 struct map_lookup *map;
5408 unsigned long len = fs_info->sectorsize;
5410 em = btrfs_get_chunk_map(fs_info, logical, len);
5412 if (!WARN_ON(IS_ERR(em))) {
5413 map = em->map_lookup;
5414 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5415 len = map->stripe_len * nr_data_stripes(map);
5416 free_extent_map(em);
5421 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5423 struct extent_map *em;
5424 struct map_lookup *map;
5427 em = btrfs_get_chunk_map(fs_info, logical, len);
5429 if(!WARN_ON(IS_ERR(em))) {
5430 map = em->map_lookup;
5431 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5433 free_extent_map(em);
5438 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5439 struct map_lookup *map, int first,
5440 int dev_replace_is_ongoing)
5444 int preferred_mirror;
5446 struct btrfs_device *srcdev;
5449 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5451 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5452 num_stripes = map->sub_stripes;
5454 num_stripes = map->num_stripes;
5456 preferred_mirror = first + current->pid % num_stripes;
5458 if (dev_replace_is_ongoing &&
5459 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5460 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5461 srcdev = fs_info->dev_replace.srcdev;
5466 * try to avoid the drive that is the source drive for a
5467 * dev-replace procedure, only choose it if no other non-missing
5468 * mirror is available
5470 for (tolerance = 0; tolerance < 2; tolerance++) {
5471 if (map->stripes[preferred_mirror].dev->bdev &&
5472 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5473 return preferred_mirror;
5474 for (i = first; i < first + num_stripes; i++) {
5475 if (map->stripes[i].dev->bdev &&
5476 (tolerance || map->stripes[i].dev != srcdev))
5481 /* we couldn't find one that doesn't fail. Just return something
5482 * and the io error handling code will clean up eventually
5484 return preferred_mirror;
5487 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5488 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5495 for (i = 0; i < num_stripes - 1; i++) {
5496 /* Swap if parity is on a smaller index */
5497 if (bbio->raid_map[i] > bbio->raid_map[i + 1]) {
5498 swap(bbio->stripes[i], bbio->stripes[i + 1]);
5499 swap(bbio->raid_map[i], bbio->raid_map[i + 1]);
5506 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5508 struct btrfs_bio *bbio = kzalloc(
5509 /* the size of the btrfs_bio */
5510 sizeof(struct btrfs_bio) +
5511 /* plus the variable array for the stripes */
5512 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5513 /* plus the variable array for the tgt dev */
5514 sizeof(int) * (real_stripes) +
5516 * plus the raid_map, which includes both the tgt dev
5519 sizeof(u64) * (total_stripes),
5520 GFP_NOFS|__GFP_NOFAIL);
5522 atomic_set(&bbio->error, 0);
5523 refcount_set(&bbio->refs, 1);
5528 void btrfs_get_bbio(struct btrfs_bio *bbio)
5530 WARN_ON(!refcount_read(&bbio->refs));
5531 refcount_inc(&bbio->refs);
5534 void btrfs_put_bbio(struct btrfs_bio *bbio)
5538 if (refcount_dec_and_test(&bbio->refs))
5542 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5544 * Please note that, discard won't be sent to target device of device
5547 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5548 u64 logical, u64 *length_ret,
5549 struct btrfs_bio **bbio_ret)
5551 struct extent_map *em;
5552 struct map_lookup *map;
5553 struct btrfs_bio *bbio;
5554 u64 length = *length_ret;
5558 u64 stripe_end_offset;
5565 u32 sub_stripes = 0;
5566 u64 stripes_per_dev = 0;
5567 u32 remaining_stripes = 0;
5568 u32 last_stripe = 0;
5572 /* discard always return a bbio */
5575 em = btrfs_get_chunk_map(fs_info, logical, length);
5579 map = em->map_lookup;
5580 /* we don't discard raid56 yet */
5581 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5586 offset = logical - em->start;
5587 length = min_t(u64, em->start + em->len - logical, length);
5588 *length_ret = length;
5590 stripe_len = map->stripe_len;
5592 * stripe_nr counts the total number of stripes we have to stride
5593 * to get to this block
5595 stripe_nr = div64_u64(offset, stripe_len);
5597 /* stripe_offset is the offset of this block in its stripe */
5598 stripe_offset = offset - stripe_nr * stripe_len;
5600 stripe_nr_end = round_up(offset + length, map->stripe_len);
5601 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5602 stripe_cnt = stripe_nr_end - stripe_nr;
5603 stripe_end_offset = stripe_nr_end * map->stripe_len -
5606 * after this, stripe_nr is the number of stripes on this
5607 * device we have to walk to find the data, and stripe_index is
5608 * the number of our device in the stripe array
5612 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5613 BTRFS_BLOCK_GROUP_RAID10)) {
5614 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5617 sub_stripes = map->sub_stripes;
5619 factor = map->num_stripes / sub_stripes;
5620 num_stripes = min_t(u64, map->num_stripes,
5621 sub_stripes * stripe_cnt);
5622 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5623 stripe_index *= sub_stripes;
5624 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5625 &remaining_stripes);
5626 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5627 last_stripe *= sub_stripes;
5628 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5629 BTRFS_BLOCK_GROUP_DUP)) {
5630 num_stripes = map->num_stripes;
5632 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5636 bbio = alloc_btrfs_bio(num_stripes, 0);
5642 for (i = 0; i < num_stripes; i++) {
5643 bbio->stripes[i].physical =
5644 map->stripes[stripe_index].physical +
5645 stripe_offset + stripe_nr * map->stripe_len;
5646 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5648 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5649 BTRFS_BLOCK_GROUP_RAID10)) {
5650 bbio->stripes[i].length = stripes_per_dev *
5653 if (i / sub_stripes < remaining_stripes)
5654 bbio->stripes[i].length +=
5658 * Special for the first stripe and
5661 * |-------|...|-------|
5665 if (i < sub_stripes)
5666 bbio->stripes[i].length -=
5669 if (stripe_index >= last_stripe &&
5670 stripe_index <= (last_stripe +
5672 bbio->stripes[i].length -=
5675 if (i == sub_stripes - 1)
5678 bbio->stripes[i].length = length;
5682 if (stripe_index == map->num_stripes) {
5689 bbio->map_type = map->type;
5690 bbio->num_stripes = num_stripes;
5692 free_extent_map(em);
5697 * In dev-replace case, for repair case (that's the only case where the mirror
5698 * is selected explicitly when calling btrfs_map_block), blocks left of the
5699 * left cursor can also be read from the target drive.
5701 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5703 * For READ, it also needs to be supported using the same mirror number.
5705 * If the requested block is not left of the left cursor, EIO is returned. This
5706 * can happen because btrfs_num_copies() returns one more in the dev-replace
5709 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5710 u64 logical, u64 length,
5711 u64 srcdev_devid, int *mirror_num,
5714 struct btrfs_bio *bbio = NULL;
5716 int index_srcdev = 0;
5718 u64 physical_of_found = 0;
5722 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5723 logical, &length, &bbio, 0, 0);
5725 ASSERT(bbio == NULL);
5729 num_stripes = bbio->num_stripes;
5730 if (*mirror_num > num_stripes) {
5732 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5733 * that means that the requested area is not left of the left
5736 btrfs_put_bbio(bbio);
5741 * process the rest of the function using the mirror_num of the source
5742 * drive. Therefore look it up first. At the end, patch the device
5743 * pointer to the one of the target drive.
5745 for (i = 0; i < num_stripes; i++) {
5746 if (bbio->stripes[i].dev->devid != srcdev_devid)
5750 * In case of DUP, in order to keep it simple, only add the
5751 * mirror with the lowest physical address
5754 physical_of_found <= bbio->stripes[i].physical)
5759 physical_of_found = bbio->stripes[i].physical;
5762 btrfs_put_bbio(bbio);
5768 *mirror_num = index_srcdev + 1;
5769 *physical = physical_of_found;
5773 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5774 struct btrfs_bio **bbio_ret,
5775 struct btrfs_dev_replace *dev_replace,
5776 int *num_stripes_ret, int *max_errors_ret)
5778 struct btrfs_bio *bbio = *bbio_ret;
5779 u64 srcdev_devid = dev_replace->srcdev->devid;
5780 int tgtdev_indexes = 0;
5781 int num_stripes = *num_stripes_ret;
5782 int max_errors = *max_errors_ret;
5785 if (op == BTRFS_MAP_WRITE) {
5786 int index_where_to_add;
5789 * duplicate the write operations while the dev replace
5790 * procedure is running. Since the copying of the old disk to
5791 * the new disk takes place at run time while the filesystem is
5792 * mounted writable, the regular write operations to the old
5793 * disk have to be duplicated to go to the new disk as well.
5795 * Note that device->missing is handled by the caller, and that
5796 * the write to the old disk is already set up in the stripes
5799 index_where_to_add = num_stripes;
5800 for (i = 0; i < num_stripes; i++) {
5801 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5802 /* write to new disk, too */
5803 struct btrfs_bio_stripe *new =
5804 bbio->stripes + index_where_to_add;
5805 struct btrfs_bio_stripe *old =
5808 new->physical = old->physical;
5809 new->length = old->length;
5810 new->dev = dev_replace->tgtdev;
5811 bbio->tgtdev_map[i] = index_where_to_add;
5812 index_where_to_add++;
5817 num_stripes = index_where_to_add;
5818 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5819 int index_srcdev = 0;
5821 u64 physical_of_found = 0;
5824 * During the dev-replace procedure, the target drive can also
5825 * be used to read data in case it is needed to repair a corrupt
5826 * block elsewhere. This is possible if the requested area is
5827 * left of the left cursor. In this area, the target drive is a
5828 * full copy of the source drive.
5830 for (i = 0; i < num_stripes; i++) {
5831 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5833 * In case of DUP, in order to keep it simple,
5834 * only add the mirror with the lowest physical
5838 physical_of_found <=
5839 bbio->stripes[i].physical)
5843 physical_of_found = bbio->stripes[i].physical;
5847 struct btrfs_bio_stripe *tgtdev_stripe =
5848 bbio->stripes + num_stripes;
5850 tgtdev_stripe->physical = physical_of_found;
5851 tgtdev_stripe->length =
5852 bbio->stripes[index_srcdev].length;
5853 tgtdev_stripe->dev = dev_replace->tgtdev;
5854 bbio->tgtdev_map[index_srcdev] = num_stripes;
5861 *num_stripes_ret = num_stripes;
5862 *max_errors_ret = max_errors;
5863 bbio->num_tgtdevs = tgtdev_indexes;
5867 static bool need_full_stripe(enum btrfs_map_op op)
5869 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5873 * btrfs_get_io_geometry - calculates the geomery of a particular (address, len)
5874 * tuple. This information is used to calculate how big a
5875 * particular bio can get before it straddles a stripe.
5877 * @fs_info - the filesystem
5878 * @logical - address that we want to figure out the geometry of
5879 * @len - the length of IO we are going to perform, starting at @logical
5880 * @op - type of operation - write or read
5881 * @io_geom - pointer used to return values
5883 * Returns < 0 in case a chunk for the given logical address cannot be found,
5884 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
5886 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5887 u64 logical, u64 len, struct btrfs_io_geometry *io_geom)
5889 struct extent_map *em;
5890 struct map_lookup *map;
5895 u64 raid56_full_stripe_start = (u64)-1;
5899 ASSERT(op != BTRFS_MAP_DISCARD);
5901 em = btrfs_get_chunk_map(fs_info, logical, len);
5905 map = em->map_lookup;
5906 /* Offset of this logical address in the chunk */
5907 offset = logical - em->start;
5908 /* Len of a stripe in a chunk */
5909 stripe_len = map->stripe_len;
5910 /* Stripe wher this block falls in */
5911 stripe_nr = div64_u64(offset, stripe_len);
5912 /* Offset of stripe in the chunk */
5913 stripe_offset = stripe_nr * stripe_len;
5914 if (offset < stripe_offset) {
5916 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
5917 stripe_offset, offset, em->start, logical, stripe_len);
5922 /* stripe_offset is the offset of this block in its stripe */
5923 stripe_offset = offset - stripe_offset;
5924 data_stripes = nr_data_stripes(map);
5926 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5927 u64 max_len = stripe_len - stripe_offset;
5930 * In case of raid56, we need to know the stripe aligned start
5932 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5933 unsigned long full_stripe_len = stripe_len * data_stripes;
5934 raid56_full_stripe_start = offset;
5937 * Allow a write of a full stripe, but make sure we
5938 * don't allow straddling of stripes
5940 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5942 raid56_full_stripe_start *= full_stripe_len;
5945 * For writes to RAID[56], allow a full stripeset across
5946 * all disks. For other RAID types and for RAID[56]
5947 * reads, just allow a single stripe (on a single disk).
5949 if (op == BTRFS_MAP_WRITE) {
5950 max_len = stripe_len * data_stripes -
5951 (offset - raid56_full_stripe_start);
5954 len = min_t(u64, em->len - offset, max_len);
5956 len = em->len - offset;
5960 io_geom->offset = offset;
5961 io_geom->stripe_len = stripe_len;
5962 io_geom->stripe_nr = stripe_nr;
5963 io_geom->stripe_offset = stripe_offset;
5964 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
5968 free_extent_map(em);
5972 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5973 enum btrfs_map_op op,
5974 u64 logical, u64 *length,
5975 struct btrfs_bio **bbio_ret,
5976 int mirror_num, int need_raid_map)
5978 struct extent_map *em;
5979 struct map_lookup *map;
5989 int tgtdev_indexes = 0;
5990 struct btrfs_bio *bbio = NULL;
5991 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5992 int dev_replace_is_ongoing = 0;
5993 int num_alloc_stripes;
5994 int patch_the_first_stripe_for_dev_replace = 0;
5995 u64 physical_to_patch_in_first_stripe = 0;
5996 u64 raid56_full_stripe_start = (u64)-1;
5997 struct btrfs_io_geometry geom;
6000 ASSERT(op != BTRFS_MAP_DISCARD);
6002 ret = btrfs_get_io_geometry(fs_info, op, logical, *length, &geom);
6006 em = btrfs_get_chunk_map(fs_info, logical, *length);
6007 ASSERT(!IS_ERR(em));
6008 map = em->map_lookup;
6011 stripe_len = geom.stripe_len;
6012 stripe_nr = geom.stripe_nr;
6013 stripe_offset = geom.stripe_offset;
6014 raid56_full_stripe_start = geom.raid56_stripe_offset;
6015 data_stripes = nr_data_stripes(map);
6017 down_read(&dev_replace->rwsem);
6018 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6020 * Hold the semaphore for read during the whole operation, write is
6021 * requested at commit time but must wait.
6023 if (!dev_replace_is_ongoing)
6024 up_read(&dev_replace->rwsem);
6026 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6027 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6028 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6029 dev_replace->srcdev->devid,
6031 &physical_to_patch_in_first_stripe);
6035 patch_the_first_stripe_for_dev_replace = 1;
6036 } else if (mirror_num > map->num_stripes) {
6042 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6043 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6045 if (!need_full_stripe(op))
6047 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6048 if (need_full_stripe(op))
6049 num_stripes = map->num_stripes;
6050 else if (mirror_num)
6051 stripe_index = mirror_num - 1;
6053 stripe_index = find_live_mirror(fs_info, map, 0,
6054 dev_replace_is_ongoing);
6055 mirror_num = stripe_index + 1;
6058 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6059 if (need_full_stripe(op)) {
6060 num_stripes = map->num_stripes;
6061 } else if (mirror_num) {
6062 stripe_index = mirror_num - 1;
6067 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6068 u32 factor = map->num_stripes / map->sub_stripes;
6070 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6071 stripe_index *= map->sub_stripes;
6073 if (need_full_stripe(op))
6074 num_stripes = map->sub_stripes;
6075 else if (mirror_num)
6076 stripe_index += mirror_num - 1;
6078 int old_stripe_index = stripe_index;
6079 stripe_index = find_live_mirror(fs_info, map,
6081 dev_replace_is_ongoing);
6082 mirror_num = stripe_index - old_stripe_index + 1;
6085 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6086 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6087 /* push stripe_nr back to the start of the full stripe */
6088 stripe_nr = div64_u64(raid56_full_stripe_start,
6089 stripe_len * data_stripes);
6091 /* RAID[56] write or recovery. Return all stripes */
6092 num_stripes = map->num_stripes;
6093 max_errors = nr_parity_stripes(map);
6095 *length = map->stripe_len;
6100 * Mirror #0 or #1 means the original data block.
6101 * Mirror #2 is RAID5 parity block.
6102 * Mirror #3 is RAID6 Q block.
6104 stripe_nr = div_u64_rem(stripe_nr,
6105 data_stripes, &stripe_index);
6107 stripe_index = data_stripes + mirror_num - 2;
6109 /* We distribute the parity blocks across stripes */
6110 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6112 if (!need_full_stripe(op) && mirror_num <= 1)
6117 * after this, stripe_nr is the number of stripes on this
6118 * device we have to walk to find the data, and stripe_index is
6119 * the number of our device in the stripe array
6121 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6123 mirror_num = stripe_index + 1;
6125 if (stripe_index >= map->num_stripes) {
6127 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6128 stripe_index, map->num_stripes);
6133 num_alloc_stripes = num_stripes;
6134 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6135 if (op == BTRFS_MAP_WRITE)
6136 num_alloc_stripes <<= 1;
6137 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6138 num_alloc_stripes++;
6139 tgtdev_indexes = num_stripes;
6142 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6147 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
6148 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
6150 /* build raid_map */
6151 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6152 (need_full_stripe(op) || mirror_num > 1)) {
6156 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6157 sizeof(struct btrfs_bio_stripe) *
6159 sizeof(int) * tgtdev_indexes);
6161 /* Work out the disk rotation on this stripe-set */
6162 div_u64_rem(stripe_nr, num_stripes, &rot);
6164 /* Fill in the logical address of each stripe */
6165 tmp = stripe_nr * data_stripes;
6166 for (i = 0; i < data_stripes; i++)
6167 bbio->raid_map[(i+rot) % num_stripes] =
6168 em->start + (tmp + i) * map->stripe_len;
6170 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6171 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6172 bbio->raid_map[(i+rot+1) % num_stripes] =
6177 for (i = 0; i < num_stripes; i++) {
6178 bbio->stripes[i].physical =
6179 map->stripes[stripe_index].physical +
6181 stripe_nr * map->stripe_len;
6182 bbio->stripes[i].dev =
6183 map->stripes[stripe_index].dev;
6187 if (need_full_stripe(op))
6188 max_errors = btrfs_chunk_max_errors(map);
6191 sort_parity_stripes(bbio, num_stripes);
6193 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6194 need_full_stripe(op)) {
6195 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6200 bbio->map_type = map->type;
6201 bbio->num_stripes = num_stripes;
6202 bbio->max_errors = max_errors;
6203 bbio->mirror_num = mirror_num;
6206 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6207 * mirror_num == num_stripes + 1 && dev_replace target drive is
6208 * available as a mirror
6210 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6211 WARN_ON(num_stripes > 1);
6212 bbio->stripes[0].dev = dev_replace->tgtdev;
6213 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6214 bbio->mirror_num = map->num_stripes + 1;
6217 if (dev_replace_is_ongoing) {
6218 lockdep_assert_held(&dev_replace->rwsem);
6219 /* Unlock and let waiting writers proceed */
6220 up_read(&dev_replace->rwsem);
6222 free_extent_map(em);
6226 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6227 u64 logical, u64 *length,
6228 struct btrfs_bio **bbio_ret, int mirror_num)
6230 if (op == BTRFS_MAP_DISCARD)
6231 return __btrfs_map_block_for_discard(fs_info, logical,
6234 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6238 /* For Scrub/replace */
6239 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6240 u64 logical, u64 *length,
6241 struct btrfs_bio **bbio_ret)
6243 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6246 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6248 bio->bi_private = bbio->private;
6249 bio->bi_end_io = bbio->end_io;
6252 btrfs_put_bbio(bbio);
6255 static void btrfs_end_bio(struct bio *bio)
6257 struct btrfs_bio *bbio = bio->bi_private;
6258 int is_orig_bio = 0;
6260 if (bio->bi_status) {
6261 atomic_inc(&bbio->error);
6262 if (bio->bi_status == BLK_STS_IOERR ||
6263 bio->bi_status == BLK_STS_TARGET) {
6264 unsigned int stripe_index =
6265 btrfs_io_bio(bio)->stripe_index;
6266 struct btrfs_device *dev;
6268 BUG_ON(stripe_index >= bbio->num_stripes);
6269 dev = bbio->stripes[stripe_index].dev;
6271 if (bio_op(bio) == REQ_OP_WRITE)
6272 btrfs_dev_stat_inc_and_print(dev,
6273 BTRFS_DEV_STAT_WRITE_ERRS);
6274 else if (!(bio->bi_opf & REQ_RAHEAD))
6275 btrfs_dev_stat_inc_and_print(dev,
6276 BTRFS_DEV_STAT_READ_ERRS);
6277 if (bio->bi_opf & REQ_PREFLUSH)
6278 btrfs_dev_stat_inc_and_print(dev,
6279 BTRFS_DEV_STAT_FLUSH_ERRS);
6284 if (bio == bbio->orig_bio)
6287 btrfs_bio_counter_dec(bbio->fs_info);
6289 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6292 bio = bbio->orig_bio;
6295 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6296 /* only send an error to the higher layers if it is
6297 * beyond the tolerance of the btrfs bio
6299 if (atomic_read(&bbio->error) > bbio->max_errors) {
6300 bio->bi_status = BLK_STS_IOERR;
6303 * this bio is actually up to date, we didn't
6304 * go over the max number of errors
6306 bio->bi_status = BLK_STS_OK;
6309 btrfs_end_bbio(bbio, bio);
6310 } else if (!is_orig_bio) {
6315 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6316 u64 physical, int dev_nr)
6318 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6319 struct btrfs_fs_info *fs_info = bbio->fs_info;
6321 bio->bi_private = bbio;
6322 btrfs_io_bio(bio)->stripe_index = dev_nr;
6323 bio->bi_end_io = btrfs_end_bio;
6324 bio->bi_iter.bi_sector = physical >> 9;
6325 btrfs_debug_in_rcu(fs_info,
6326 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6327 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6328 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6329 dev->devid, bio->bi_iter.bi_size);
6330 bio_set_dev(bio, dev->bdev);
6332 btrfs_bio_counter_inc_noblocked(fs_info);
6334 btrfsic_submit_bio(bio);
6337 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6339 atomic_inc(&bbio->error);
6340 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6341 /* Should be the original bio. */
6342 WARN_ON(bio != bbio->orig_bio);
6344 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6345 bio->bi_iter.bi_sector = logical >> 9;
6346 if (atomic_read(&bbio->error) > bbio->max_errors)
6347 bio->bi_status = BLK_STS_IOERR;
6349 bio->bi_status = BLK_STS_OK;
6350 btrfs_end_bbio(bbio, bio);
6354 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6357 struct btrfs_device *dev;
6358 struct bio *first_bio = bio;
6359 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6365 struct btrfs_bio *bbio = NULL;
6367 length = bio->bi_iter.bi_size;
6368 map_length = length;
6370 btrfs_bio_counter_inc_blocked(fs_info);
6371 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6372 &map_length, &bbio, mirror_num, 1);
6374 btrfs_bio_counter_dec(fs_info);
6375 return errno_to_blk_status(ret);
6378 total_devs = bbio->num_stripes;
6379 bbio->orig_bio = first_bio;
6380 bbio->private = first_bio->bi_private;
6381 bbio->end_io = first_bio->bi_end_io;
6382 bbio->fs_info = fs_info;
6383 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6385 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6386 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6387 /* In this case, map_length has been set to the length of
6388 a single stripe; not the whole write */
6389 if (bio_op(bio) == REQ_OP_WRITE) {
6390 ret = raid56_parity_write(fs_info, bio, bbio,
6393 ret = raid56_parity_recover(fs_info, bio, bbio,
6394 map_length, mirror_num, 1);
6397 btrfs_bio_counter_dec(fs_info);
6398 return errno_to_blk_status(ret);
6401 if (map_length < length) {
6403 "mapping failed logical %llu bio len %llu len %llu",
6404 logical, length, map_length);
6408 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6409 dev = bbio->stripes[dev_nr].dev;
6410 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6412 (bio_op(first_bio) == REQ_OP_WRITE &&
6413 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6414 bbio_error(bbio, first_bio, logical);
6418 if (dev_nr < total_devs - 1)
6419 bio = btrfs_bio_clone(first_bio);
6423 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6426 btrfs_bio_counter_dec(fs_info);
6431 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6434 * If devid and uuid are both specified, the match must be exact, otherwise
6435 * only devid is used.
6437 * If @seed is true, traverse through the seed devices.
6439 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6440 u64 devid, u8 *uuid, u8 *fsid,
6443 struct btrfs_device *device;
6445 while (fs_devices) {
6447 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6448 list_for_each_entry(device, &fs_devices->devices,
6450 if (device->devid == devid &&
6451 (!uuid || memcmp(device->uuid, uuid,
6452 BTRFS_UUID_SIZE) == 0))
6457 fs_devices = fs_devices->seed;
6464 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6465 u64 devid, u8 *dev_uuid)
6467 struct btrfs_device *device;
6469 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6473 list_add(&device->dev_list, &fs_devices->devices);
6474 device->fs_devices = fs_devices;
6475 fs_devices->num_devices++;
6477 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6478 fs_devices->missing_devices++;
6484 * btrfs_alloc_device - allocate struct btrfs_device
6485 * @fs_info: used only for generating a new devid, can be NULL if
6486 * devid is provided (i.e. @devid != NULL).
6487 * @devid: a pointer to devid for this device. If NULL a new devid
6489 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6492 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6493 * on error. Returned struct is not linked onto any lists and must be
6494 * destroyed with btrfs_free_device.
6496 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6500 struct btrfs_device *dev;
6503 if (WARN_ON(!devid && !fs_info))
6504 return ERR_PTR(-EINVAL);
6506 dev = __alloc_device();
6515 ret = find_next_devid(fs_info, &tmp);
6517 btrfs_free_device(dev);
6518 return ERR_PTR(ret);
6524 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6526 generate_random_uuid(dev->uuid);
6531 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6532 u64 devid, u8 *uuid, bool error)
6535 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6538 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6542 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6544 int index = btrfs_bg_flags_to_raid_index(type);
6545 int ncopies = btrfs_raid_array[index].ncopies;
6546 const int nparity = btrfs_raid_array[index].nparity;
6550 data_stripes = num_stripes - nparity;
6552 data_stripes = num_stripes / ncopies;
6554 return div_u64(chunk_len, data_stripes);
6557 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6558 struct btrfs_chunk *chunk)
6560 struct btrfs_fs_info *fs_info = leaf->fs_info;
6561 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6562 struct map_lookup *map;
6563 struct extent_map *em;
6567 u8 uuid[BTRFS_UUID_SIZE];
6572 logical = key->offset;
6573 length = btrfs_chunk_length(leaf, chunk);
6574 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6577 * Only need to verify chunk item if we're reading from sys chunk array,
6578 * as chunk item in tree block is already verified by tree-checker.
6580 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6581 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6586 read_lock(&map_tree->lock);
6587 em = lookup_extent_mapping(map_tree, logical, 1);
6588 read_unlock(&map_tree->lock);
6590 /* already mapped? */
6591 if (em && em->start <= logical && em->start + em->len > logical) {
6592 free_extent_map(em);
6595 free_extent_map(em);
6598 em = alloc_extent_map();
6601 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6603 free_extent_map(em);
6607 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6608 em->map_lookup = map;
6609 em->start = logical;
6612 em->block_start = 0;
6613 em->block_len = em->len;
6615 map->num_stripes = num_stripes;
6616 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6617 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6618 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6619 map->type = btrfs_chunk_type(leaf, chunk);
6620 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6621 map->verified_stripes = 0;
6622 em->orig_block_len = calc_stripe_length(map->type, em->len,
6624 for (i = 0; i < num_stripes; i++) {
6625 map->stripes[i].physical =
6626 btrfs_stripe_offset_nr(leaf, chunk, i);
6627 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6628 read_extent_buffer(leaf, uuid, (unsigned long)
6629 btrfs_stripe_dev_uuid_nr(chunk, i),
6631 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6632 devid, uuid, NULL, true);
6633 if (!map->stripes[i].dev &&
6634 !btrfs_test_opt(fs_info, DEGRADED)) {
6635 free_extent_map(em);
6636 btrfs_report_missing_device(fs_info, devid, uuid, true);
6639 if (!map->stripes[i].dev) {
6640 map->stripes[i].dev =
6641 add_missing_dev(fs_info->fs_devices, devid,
6643 if (IS_ERR(map->stripes[i].dev)) {
6644 free_extent_map(em);
6646 "failed to init missing dev %llu: %ld",
6647 devid, PTR_ERR(map->stripes[i].dev));
6648 return PTR_ERR(map->stripes[i].dev);
6650 btrfs_report_missing_device(fs_info, devid, uuid, false);
6652 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6653 &(map->stripes[i].dev->dev_state));
6657 write_lock(&map_tree->lock);
6658 ret = add_extent_mapping(map_tree, em, 0);
6659 write_unlock(&map_tree->lock);
6662 "failed to add chunk map, start=%llu len=%llu: %d",
6663 em->start, em->len, ret);
6665 free_extent_map(em);
6670 static void fill_device_from_item(struct extent_buffer *leaf,
6671 struct btrfs_dev_item *dev_item,
6672 struct btrfs_device *device)
6676 device->devid = btrfs_device_id(leaf, dev_item);
6677 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6678 device->total_bytes = device->disk_total_bytes;
6679 device->commit_total_bytes = device->disk_total_bytes;
6680 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6681 device->commit_bytes_used = device->bytes_used;
6682 device->type = btrfs_device_type(leaf, dev_item);
6683 device->io_align = btrfs_device_io_align(leaf, dev_item);
6684 device->io_width = btrfs_device_io_width(leaf, dev_item);
6685 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6686 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6687 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6689 ptr = btrfs_device_uuid(dev_item);
6690 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6693 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6696 struct btrfs_fs_devices *fs_devices;
6699 lockdep_assert_held(&uuid_mutex);
6702 fs_devices = fs_info->fs_devices->seed;
6703 while (fs_devices) {
6704 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6707 fs_devices = fs_devices->seed;
6710 fs_devices = find_fsid(fsid, NULL);
6712 if (!btrfs_test_opt(fs_info, DEGRADED))
6713 return ERR_PTR(-ENOENT);
6715 fs_devices = alloc_fs_devices(fsid, NULL);
6716 if (IS_ERR(fs_devices))
6719 fs_devices->seeding = true;
6720 fs_devices->opened = 1;
6724 fs_devices = clone_fs_devices(fs_devices);
6725 if (IS_ERR(fs_devices))
6728 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6730 free_fs_devices(fs_devices);
6731 fs_devices = ERR_PTR(ret);
6735 if (!fs_devices->seeding) {
6736 close_fs_devices(fs_devices);
6737 free_fs_devices(fs_devices);
6738 fs_devices = ERR_PTR(-EINVAL);
6742 fs_devices->seed = fs_info->fs_devices->seed;
6743 fs_info->fs_devices->seed = fs_devices;
6748 static int read_one_dev(struct extent_buffer *leaf,
6749 struct btrfs_dev_item *dev_item)
6751 struct btrfs_fs_info *fs_info = leaf->fs_info;
6752 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6753 struct btrfs_device *device;
6756 u8 fs_uuid[BTRFS_FSID_SIZE];
6757 u8 dev_uuid[BTRFS_UUID_SIZE];
6759 devid = btrfs_device_id(leaf, dev_item);
6760 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6762 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6765 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6766 fs_devices = open_seed_devices(fs_info, fs_uuid);
6767 if (IS_ERR(fs_devices))
6768 return PTR_ERR(fs_devices);
6771 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6774 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6775 btrfs_report_missing_device(fs_info, devid,
6780 device = add_missing_dev(fs_devices, devid, dev_uuid);
6781 if (IS_ERR(device)) {
6783 "failed to add missing dev %llu: %ld",
6784 devid, PTR_ERR(device));
6785 return PTR_ERR(device);
6787 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6789 if (!device->bdev) {
6790 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6791 btrfs_report_missing_device(fs_info,
6792 devid, dev_uuid, true);
6795 btrfs_report_missing_device(fs_info, devid,
6799 if (!device->bdev &&
6800 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6802 * this happens when a device that was properly setup
6803 * in the device info lists suddenly goes bad.
6804 * device->bdev is NULL, and so we have to set
6805 * device->missing to one here
6807 device->fs_devices->missing_devices++;
6808 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6811 /* Move the device to its own fs_devices */
6812 if (device->fs_devices != fs_devices) {
6813 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6814 &device->dev_state));
6816 list_move(&device->dev_list, &fs_devices->devices);
6817 device->fs_devices->num_devices--;
6818 fs_devices->num_devices++;
6820 device->fs_devices->missing_devices--;
6821 fs_devices->missing_devices++;
6823 device->fs_devices = fs_devices;
6827 if (device->fs_devices != fs_info->fs_devices) {
6828 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6829 if (device->generation !=
6830 btrfs_device_generation(leaf, dev_item))
6834 fill_device_from_item(leaf, dev_item, device);
6835 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6836 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6837 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6838 device->fs_devices->total_rw_bytes += device->total_bytes;
6839 atomic64_add(device->total_bytes - device->bytes_used,
6840 &fs_info->free_chunk_space);
6846 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6848 struct btrfs_root *root = fs_info->tree_root;
6849 struct btrfs_super_block *super_copy = fs_info->super_copy;
6850 struct extent_buffer *sb;
6851 struct btrfs_disk_key *disk_key;
6852 struct btrfs_chunk *chunk;
6854 unsigned long sb_array_offset;
6861 struct btrfs_key key;
6863 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6865 * This will create extent buffer of nodesize, superblock size is
6866 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6867 * overallocate but we can keep it as-is, only the first page is used.
6869 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6872 set_extent_buffer_uptodate(sb);
6873 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6875 * The sb extent buffer is artificial and just used to read the system array.
6876 * set_extent_buffer_uptodate() call does not properly mark all it's
6877 * pages up-to-date when the page is larger: extent does not cover the
6878 * whole page and consequently check_page_uptodate does not find all
6879 * the page's extents up-to-date (the hole beyond sb),
6880 * write_extent_buffer then triggers a WARN_ON.
6882 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6883 * but sb spans only this function. Add an explicit SetPageUptodate call
6884 * to silence the warning eg. on PowerPC 64.
6886 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6887 SetPageUptodate(sb->pages[0]);
6889 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6890 array_size = btrfs_super_sys_array_size(super_copy);
6892 array_ptr = super_copy->sys_chunk_array;
6893 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6896 while (cur_offset < array_size) {
6897 disk_key = (struct btrfs_disk_key *)array_ptr;
6898 len = sizeof(*disk_key);
6899 if (cur_offset + len > array_size)
6900 goto out_short_read;
6902 btrfs_disk_key_to_cpu(&key, disk_key);
6905 sb_array_offset += len;
6908 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
6910 "unexpected item type %u in sys_array at offset %u",
6911 (u32)key.type, cur_offset);
6916 chunk = (struct btrfs_chunk *)sb_array_offset;
6918 * At least one btrfs_chunk with one stripe must be present,
6919 * exact stripe count check comes afterwards
6921 len = btrfs_chunk_item_size(1);
6922 if (cur_offset + len > array_size)
6923 goto out_short_read;
6925 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6928 "invalid number of stripes %u in sys_array at offset %u",
6929 num_stripes, cur_offset);
6934 type = btrfs_chunk_type(sb, chunk);
6935 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6937 "invalid chunk type %llu in sys_array at offset %u",
6943 len = btrfs_chunk_item_size(num_stripes);
6944 if (cur_offset + len > array_size)
6945 goto out_short_read;
6947 ret = read_one_chunk(&key, sb, chunk);
6952 sb_array_offset += len;
6955 clear_extent_buffer_uptodate(sb);
6956 free_extent_buffer_stale(sb);
6960 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6962 clear_extent_buffer_uptodate(sb);
6963 free_extent_buffer_stale(sb);
6968 * Check if all chunks in the fs are OK for read-write degraded mount
6970 * If the @failing_dev is specified, it's accounted as missing.
6972 * Return true if all chunks meet the minimal RW mount requirements.
6973 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6975 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6976 struct btrfs_device *failing_dev)
6978 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6979 struct extent_map *em;
6983 read_lock(&map_tree->lock);
6984 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
6985 read_unlock(&map_tree->lock);
6986 /* No chunk at all? Return false anyway */
6992 struct map_lookup *map;
6997 map = em->map_lookup;
6999 btrfs_get_num_tolerated_disk_barrier_failures(
7001 for (i = 0; i < map->num_stripes; i++) {
7002 struct btrfs_device *dev = map->stripes[i].dev;
7004 if (!dev || !dev->bdev ||
7005 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7006 dev->last_flush_error)
7008 else if (failing_dev && failing_dev == dev)
7011 if (missing > max_tolerated) {
7014 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7015 em->start, missing, max_tolerated);
7016 free_extent_map(em);
7020 next_start = extent_map_end(em);
7021 free_extent_map(em);
7023 read_lock(&map_tree->lock);
7024 em = lookup_extent_mapping(map_tree, next_start,
7025 (u64)(-1) - next_start);
7026 read_unlock(&map_tree->lock);
7032 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7034 struct btrfs_root *root = fs_info->chunk_root;
7035 struct btrfs_path *path;
7036 struct extent_buffer *leaf;
7037 struct btrfs_key key;
7038 struct btrfs_key found_key;
7043 path = btrfs_alloc_path();
7048 * uuid_mutex is needed only if we are mounting a sprout FS
7049 * otherwise we don't need it.
7051 mutex_lock(&uuid_mutex);
7052 mutex_lock(&fs_info->chunk_mutex);
7055 * It is possible for mount and umount to race in such a way that
7056 * we execute this code path, but open_fs_devices failed to clear
7057 * total_rw_bytes. We certainly want it cleared before reading the
7058 * device items, so clear it here.
7060 fs_info->fs_devices->total_rw_bytes = 0;
7063 * Read all device items, and then all the chunk items. All
7064 * device items are found before any chunk item (their object id
7065 * is smaller than the lowest possible object id for a chunk
7066 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7068 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7071 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7075 leaf = path->nodes[0];
7076 slot = path->slots[0];
7077 if (slot >= btrfs_header_nritems(leaf)) {
7078 ret = btrfs_next_leaf(root, path);
7085 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7086 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7087 struct btrfs_dev_item *dev_item;
7088 dev_item = btrfs_item_ptr(leaf, slot,
7089 struct btrfs_dev_item);
7090 ret = read_one_dev(leaf, dev_item);
7094 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7095 struct btrfs_chunk *chunk;
7096 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7097 ret = read_one_chunk(&found_key, leaf, chunk);
7105 * After loading chunk tree, we've got all device information,
7106 * do another round of validation checks.
7108 if (total_dev != fs_info->fs_devices->total_devices) {
7110 "super_num_devices %llu mismatch with num_devices %llu found here",
7111 btrfs_super_num_devices(fs_info->super_copy),
7116 if (btrfs_super_total_bytes(fs_info->super_copy) <
7117 fs_info->fs_devices->total_rw_bytes) {
7119 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7120 btrfs_super_total_bytes(fs_info->super_copy),
7121 fs_info->fs_devices->total_rw_bytes);
7127 mutex_unlock(&fs_info->chunk_mutex);
7128 mutex_unlock(&uuid_mutex);
7130 btrfs_free_path(path);
7134 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7136 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7137 struct btrfs_device *device;
7139 while (fs_devices) {
7140 mutex_lock(&fs_devices->device_list_mutex);
7141 list_for_each_entry(device, &fs_devices->devices, dev_list)
7142 device->fs_info = fs_info;
7143 mutex_unlock(&fs_devices->device_list_mutex);
7145 fs_devices = fs_devices->seed;
7149 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7150 const struct btrfs_dev_stats_item *ptr,
7155 read_extent_buffer(eb, &val,
7156 offsetof(struct btrfs_dev_stats_item, values) +
7157 ((unsigned long)ptr) + (index * sizeof(u64)),
7162 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7163 struct btrfs_dev_stats_item *ptr,
7166 write_extent_buffer(eb, &val,
7167 offsetof(struct btrfs_dev_stats_item, values) +
7168 ((unsigned long)ptr) + (index * sizeof(u64)),
7172 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7174 struct btrfs_key key;
7175 struct btrfs_root *dev_root = fs_info->dev_root;
7176 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7177 struct extent_buffer *eb;
7180 struct btrfs_device *device;
7181 struct btrfs_path *path = NULL;
7184 path = btrfs_alloc_path();
7188 mutex_lock(&fs_devices->device_list_mutex);
7189 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7191 struct btrfs_dev_stats_item *ptr;
7193 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7194 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7195 key.offset = device->devid;
7196 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7198 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7199 btrfs_dev_stat_set(device, i, 0);
7200 device->dev_stats_valid = 1;
7201 btrfs_release_path(path);
7204 slot = path->slots[0];
7205 eb = path->nodes[0];
7206 item_size = btrfs_item_size_nr(eb, slot);
7208 ptr = btrfs_item_ptr(eb, slot,
7209 struct btrfs_dev_stats_item);
7211 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7212 if (item_size >= (1 + i) * sizeof(__le64))
7213 btrfs_dev_stat_set(device, i,
7214 btrfs_dev_stats_value(eb, ptr, i));
7216 btrfs_dev_stat_set(device, i, 0);
7219 device->dev_stats_valid = 1;
7220 btrfs_dev_stat_print_on_load(device);
7221 btrfs_release_path(path);
7223 mutex_unlock(&fs_devices->device_list_mutex);
7225 btrfs_free_path(path);
7226 return ret < 0 ? ret : 0;
7229 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7230 struct btrfs_device *device)
7232 struct btrfs_fs_info *fs_info = trans->fs_info;
7233 struct btrfs_root *dev_root = fs_info->dev_root;
7234 struct btrfs_path *path;
7235 struct btrfs_key key;
7236 struct extent_buffer *eb;
7237 struct btrfs_dev_stats_item *ptr;
7241 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7242 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7243 key.offset = device->devid;
7245 path = btrfs_alloc_path();
7248 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7250 btrfs_warn_in_rcu(fs_info,
7251 "error %d while searching for dev_stats item for device %s",
7252 ret, rcu_str_deref(device->name));
7257 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7258 /* need to delete old one and insert a new one */
7259 ret = btrfs_del_item(trans, dev_root, path);
7261 btrfs_warn_in_rcu(fs_info,
7262 "delete too small dev_stats item for device %s failed %d",
7263 rcu_str_deref(device->name), ret);
7270 /* need to insert a new item */
7271 btrfs_release_path(path);
7272 ret = btrfs_insert_empty_item(trans, dev_root, path,
7273 &key, sizeof(*ptr));
7275 btrfs_warn_in_rcu(fs_info,
7276 "insert dev_stats item for device %s failed %d",
7277 rcu_str_deref(device->name), ret);
7282 eb = path->nodes[0];
7283 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7284 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7285 btrfs_set_dev_stats_value(eb, ptr, i,
7286 btrfs_dev_stat_read(device, i));
7287 btrfs_mark_buffer_dirty(eb);
7290 btrfs_free_path(path);
7295 * called from commit_transaction. Writes all changed device stats to disk.
7297 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7299 struct btrfs_fs_info *fs_info = trans->fs_info;
7300 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7301 struct btrfs_device *device;
7305 mutex_lock(&fs_devices->device_list_mutex);
7306 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7307 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7308 if (!device->dev_stats_valid || stats_cnt == 0)
7313 * There is a LOAD-LOAD control dependency between the value of
7314 * dev_stats_ccnt and updating the on-disk values which requires
7315 * reading the in-memory counters. Such control dependencies
7316 * require explicit read memory barriers.
7318 * This memory barriers pairs with smp_mb__before_atomic in
7319 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7320 * barrier implied by atomic_xchg in
7321 * btrfs_dev_stats_read_and_reset
7325 ret = update_dev_stat_item(trans, device);
7327 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7329 mutex_unlock(&fs_devices->device_list_mutex);
7334 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7336 btrfs_dev_stat_inc(dev, index);
7337 btrfs_dev_stat_print_on_error(dev);
7340 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7342 if (!dev->dev_stats_valid)
7344 btrfs_err_rl_in_rcu(dev->fs_info,
7345 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7346 rcu_str_deref(dev->name),
7347 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7348 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7349 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7350 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7351 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7354 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7358 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7359 if (btrfs_dev_stat_read(dev, i) != 0)
7361 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7362 return; /* all values == 0, suppress message */
7364 btrfs_info_in_rcu(dev->fs_info,
7365 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7366 rcu_str_deref(dev->name),
7367 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7368 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7369 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7370 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7371 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7374 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7375 struct btrfs_ioctl_get_dev_stats *stats)
7377 struct btrfs_device *dev;
7378 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7381 mutex_lock(&fs_devices->device_list_mutex);
7382 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7384 mutex_unlock(&fs_devices->device_list_mutex);
7387 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7389 } else if (!dev->dev_stats_valid) {
7390 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7392 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7393 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7394 if (stats->nr_items > i)
7396 btrfs_dev_stat_read_and_reset(dev, i);
7398 btrfs_dev_stat_set(dev, i, 0);
7400 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7401 current->comm, task_pid_nr(current));
7403 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7404 if (stats->nr_items > i)
7405 stats->values[i] = btrfs_dev_stat_read(dev, i);
7407 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7408 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7413 * Update the size and bytes used for each device where it changed. This is
7414 * delayed since we would otherwise get errors while writing out the
7417 * Must be invoked during transaction commit.
7419 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7421 struct btrfs_device *curr, *next;
7423 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7425 if (list_empty(&trans->dev_update_list))
7429 * We don't need the device_list_mutex here. This list is owned by the
7430 * transaction and the transaction must complete before the device is
7433 mutex_lock(&trans->fs_info->chunk_mutex);
7434 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7436 list_del_init(&curr->post_commit_list);
7437 curr->commit_total_bytes = curr->disk_total_bytes;
7438 curr->commit_bytes_used = curr->bytes_used;
7440 mutex_unlock(&trans->fs_info->chunk_mutex);
7443 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7445 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7446 while (fs_devices) {
7447 fs_devices->fs_info = fs_info;
7448 fs_devices = fs_devices->seed;
7452 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7454 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7455 while (fs_devices) {
7456 fs_devices->fs_info = NULL;
7457 fs_devices = fs_devices->seed;
7462 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7464 int btrfs_bg_type_to_factor(u64 flags)
7466 const int index = btrfs_bg_flags_to_raid_index(flags);
7468 return btrfs_raid_array[index].ncopies;
7473 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7474 u64 chunk_offset, u64 devid,
7475 u64 physical_offset, u64 physical_len)
7477 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7478 struct extent_map *em;
7479 struct map_lookup *map;
7480 struct btrfs_device *dev;
7486 read_lock(&em_tree->lock);
7487 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7488 read_unlock(&em_tree->lock);
7492 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7493 physical_offset, devid);
7498 map = em->map_lookup;
7499 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7500 if (physical_len != stripe_len) {
7502 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7503 physical_offset, devid, em->start, physical_len,
7509 for (i = 0; i < map->num_stripes; i++) {
7510 if (map->stripes[i].dev->devid == devid &&
7511 map->stripes[i].physical == physical_offset) {
7513 if (map->verified_stripes >= map->num_stripes) {
7515 "too many dev extents for chunk %llu found",
7520 map->verified_stripes++;
7526 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7527 physical_offset, devid);
7531 /* Make sure no dev extent is beyond device bondary */
7532 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7534 btrfs_err(fs_info, "failed to find devid %llu", devid);
7539 /* It's possible this device is a dummy for seed device */
7540 if (dev->disk_total_bytes == 0) {
7541 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7544 btrfs_err(fs_info, "failed to find seed devid %llu",
7551 if (physical_offset + physical_len > dev->disk_total_bytes) {
7553 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7554 devid, physical_offset, physical_len,
7555 dev->disk_total_bytes);
7560 free_extent_map(em);
7564 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7566 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7567 struct extent_map *em;
7568 struct rb_node *node;
7571 read_lock(&em_tree->lock);
7572 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7573 em = rb_entry(node, struct extent_map, rb_node);
7574 if (em->map_lookup->num_stripes !=
7575 em->map_lookup->verified_stripes) {
7577 "chunk %llu has missing dev extent, have %d expect %d",
7578 em->start, em->map_lookup->verified_stripes,
7579 em->map_lookup->num_stripes);
7585 read_unlock(&em_tree->lock);
7590 * Ensure that all dev extents are mapped to correct chunk, otherwise
7591 * later chunk allocation/free would cause unexpected behavior.
7593 * NOTE: This will iterate through the whole device tree, which should be of
7594 * the same size level as the chunk tree. This slightly increases mount time.
7596 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7598 struct btrfs_path *path;
7599 struct btrfs_root *root = fs_info->dev_root;
7600 struct btrfs_key key;
7602 u64 prev_dev_ext_end = 0;
7606 key.type = BTRFS_DEV_EXTENT_KEY;
7609 path = btrfs_alloc_path();
7613 path->reada = READA_FORWARD;
7614 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7618 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7619 ret = btrfs_next_item(root, path);
7622 /* No dev extents at all? Not good */
7629 struct extent_buffer *leaf = path->nodes[0];
7630 struct btrfs_dev_extent *dext;
7631 int slot = path->slots[0];
7633 u64 physical_offset;
7637 btrfs_item_key_to_cpu(leaf, &key, slot);
7638 if (key.type != BTRFS_DEV_EXTENT_KEY)
7640 devid = key.objectid;
7641 physical_offset = key.offset;
7643 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7644 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7645 physical_len = btrfs_dev_extent_length(leaf, dext);
7647 /* Check if this dev extent overlaps with the previous one */
7648 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7650 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7651 devid, physical_offset, prev_dev_ext_end);
7656 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7657 physical_offset, physical_len);
7661 prev_dev_ext_end = physical_offset + physical_len;
7663 ret = btrfs_next_item(root, path);
7672 /* Ensure all chunks have corresponding dev extents */
7673 ret = verify_chunk_dev_extent_mapping(fs_info);
7675 btrfs_free_path(path);
7680 * Check whether the given block group or device is pinned by any inode being
7681 * used as a swapfile.
7683 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7685 struct btrfs_swapfile_pin *sp;
7686 struct rb_node *node;
7688 spin_lock(&fs_info->swapfile_pins_lock);
7689 node = fs_info->swapfile_pins.rb_node;
7691 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7693 node = node->rb_left;
7694 else if (ptr > sp->ptr)
7695 node = node->rb_right;
7699 spin_unlock(&fs_info->swapfile_pins_lock);
7700 return node != NULL;