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 in general
249 * but in mount context it could be used to exclude list modifications by eg.
252 * btrfs_device::name - renames (write side), read is RCU
254 * fs_devices::device_list_mutex (per-fs, with RCU)
255 * ------------------------------------------------
256 * protects updates to fs_devices::devices, ie. adding and deleting
258 * simple list traversal with read-only actions can be done with RCU protection
260 * may be used to exclude some operations from running concurrently without any
261 * modifications to the list (see write_all_supers)
263 * Is not required at mount and close times, because our device list is
264 * protected by the uuid_mutex at that point.
268 * protects balance structures (status, state) and context accessed from
269 * several places (internally, ioctl)
273 * protects chunks, adding or removing during allocation, trim or when a new
274 * device is added/removed. Additionally it also protects post_commit_list of
275 * individual devices, since they can be added to the transaction's
276 * post_commit_list only with chunk_mutex held.
280 * a big lock that is held by the cleaner thread and prevents running subvolume
281 * cleaning together with relocation or delayed iputs
293 * Exclusive operations, BTRFS_FS_EXCL_OP
294 * ======================================
296 * Maintains the exclusivity of the following operations that apply to the
297 * whole filesystem and cannot run in parallel.
302 * - Device replace (*)
305 * The device operations (as above) can be in one of the following states:
311 * Only device operations marked with (*) can go into the Paused state for the
314 * - ioctl (only Balance can be Paused through ioctl)
315 * - filesystem remounted as read-only
316 * - filesystem unmounted and mounted as read-only
317 * - system power-cycle and filesystem mounted as read-only
318 * - filesystem or device errors leading to forced read-only
320 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
321 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
322 * A device operation in Paused or Running state can be canceled or resumed
323 * either by ioctl (Balance only) or when remounted as read-write.
324 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
328 DEFINE_MUTEX(uuid_mutex);
329 static LIST_HEAD(fs_uuids);
330 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
336 * alloc_fs_devices - allocate struct btrfs_fs_devices
337 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
338 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
340 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
341 * The returned struct is not linked onto any lists and can be destroyed with
342 * kfree() right away.
344 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
345 const u8 *metadata_fsid)
347 struct btrfs_fs_devices *fs_devs;
349 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
351 return ERR_PTR(-ENOMEM);
353 mutex_init(&fs_devs->device_list_mutex);
355 INIT_LIST_HEAD(&fs_devs->devices);
356 INIT_LIST_HEAD(&fs_devs->alloc_list);
357 INIT_LIST_HEAD(&fs_devs->fs_list);
359 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
362 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
364 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
369 void btrfs_free_device(struct btrfs_device *device)
371 WARN_ON(!list_empty(&device->post_commit_list));
372 rcu_string_free(device->name);
373 extent_io_tree_release(&device->alloc_state);
374 bio_put(device->flush_bio);
378 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
380 struct btrfs_device *device;
381 WARN_ON(fs_devices->opened);
382 while (!list_empty(&fs_devices->devices)) {
383 device = list_entry(fs_devices->devices.next,
384 struct btrfs_device, dev_list);
385 list_del(&device->dev_list);
386 btrfs_free_device(device);
391 void __exit btrfs_cleanup_fs_uuids(void)
393 struct btrfs_fs_devices *fs_devices;
395 while (!list_empty(&fs_uuids)) {
396 fs_devices = list_entry(fs_uuids.next,
397 struct btrfs_fs_devices, fs_list);
398 list_del(&fs_devices->fs_list);
399 free_fs_devices(fs_devices);
404 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
405 * Returned struct is not linked onto any lists and must be destroyed using
408 static struct btrfs_device *__alloc_device(void)
410 struct btrfs_device *dev;
412 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
414 return ERR_PTR(-ENOMEM);
417 * Preallocate a bio that's always going to be used for flushing device
418 * barriers and matches the device lifespan
420 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
421 if (!dev->flush_bio) {
423 return ERR_PTR(-ENOMEM);
426 INIT_LIST_HEAD(&dev->dev_list);
427 INIT_LIST_HEAD(&dev->dev_alloc_list);
428 INIT_LIST_HEAD(&dev->post_commit_list);
430 atomic_set(&dev->reada_in_flight, 0);
431 atomic_set(&dev->dev_stats_ccnt, 0);
432 btrfs_device_data_ordered_init(dev);
433 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
434 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
435 extent_io_tree_init(NULL, &dev->alloc_state, 0, NULL);
440 static noinline struct btrfs_fs_devices *find_fsid(
441 const u8 *fsid, const u8 *metadata_fsid)
443 struct btrfs_fs_devices *fs_devices;
447 /* Handle non-split brain cases */
448 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
450 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
451 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
452 BTRFS_FSID_SIZE) == 0)
455 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
462 static struct btrfs_fs_devices *find_fsid_with_metadata_uuid(
463 struct btrfs_super_block *disk_super)
466 struct btrfs_fs_devices *fs_devices;
469 * Handle scanned device having completed its fsid change but
470 * belonging to a fs_devices that was created by first scanning
471 * a device which didn't have its fsid/metadata_uuid changed
472 * at all and the CHANGING_FSID_V2 flag set.
474 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
475 if (fs_devices->fsid_change &&
476 memcmp(disk_super->metadata_uuid, fs_devices->fsid,
477 BTRFS_FSID_SIZE) == 0 &&
478 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
479 BTRFS_FSID_SIZE) == 0) {
484 * Handle scanned device having completed its fsid change but
485 * belonging to a fs_devices that was created by a device that
486 * has an outdated pair of fsid/metadata_uuid and
487 * CHANGING_FSID_V2 flag set.
489 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
490 if (fs_devices->fsid_change &&
491 memcmp(fs_devices->metadata_uuid,
492 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
493 memcmp(disk_super->metadata_uuid, fs_devices->metadata_uuid,
494 BTRFS_FSID_SIZE) == 0) {
499 return find_fsid(disk_super->fsid, disk_super->metadata_uuid);
504 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
505 int flush, struct block_device **bdev,
506 struct btrfs_super_block **disk_super)
510 *bdev = blkdev_get_by_path(device_path, flags, holder);
513 ret = PTR_ERR(*bdev);
518 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
519 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
521 blkdev_put(*bdev, flags);
524 invalidate_bdev(*bdev);
525 *disk_super = btrfs_read_dev_super(*bdev);
526 if (IS_ERR(*disk_super)) {
527 ret = PTR_ERR(*disk_super);
528 blkdev_put(*bdev, flags);
539 static bool device_path_matched(const char *path, struct btrfs_device *device)
544 found = strcmp(rcu_str_deref(device->name), path);
551 * Search and remove all stale (devices which are not mounted) devices.
552 * When both inputs are NULL, it will search and release all stale devices.
553 * path: Optional. When provided will it release all unmounted devices
554 * matching this path only.
555 * skip_dev: Optional. Will skip this device when searching for the stale
557 * Return: 0 for success or if @path is NULL.
558 * -EBUSY if @path is a mounted device.
559 * -ENOENT if @path does not match any device in the list.
561 static int btrfs_free_stale_devices(const char *path,
562 struct btrfs_device *skip_device)
564 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
565 struct btrfs_device *device, *tmp_device;
571 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
573 mutex_lock(&fs_devices->device_list_mutex);
574 list_for_each_entry_safe(device, tmp_device,
575 &fs_devices->devices, dev_list) {
576 if (skip_device && skip_device == device)
578 if (path && !device->name)
580 if (path && !device_path_matched(path, device))
582 if (fs_devices->opened) {
583 /* for an already deleted device return 0 */
584 if (path && ret != 0)
589 /* delete the stale device */
590 fs_devices->num_devices--;
591 list_del(&device->dev_list);
592 btrfs_free_device(device);
595 if (fs_devices->num_devices == 0)
598 mutex_unlock(&fs_devices->device_list_mutex);
600 if (fs_devices->num_devices == 0) {
601 btrfs_sysfs_remove_fsid(fs_devices);
602 list_del(&fs_devices->fs_list);
603 free_fs_devices(fs_devices);
611 * This is only used on mount, and we are protected from competing things
612 * messing with our fs_devices by the uuid_mutex, thus we do not need the
613 * fs_devices->device_list_mutex here.
615 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
616 struct btrfs_device *device, fmode_t flags,
619 struct request_queue *q;
620 struct block_device *bdev;
621 struct btrfs_super_block *disk_super;
630 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
635 devid = btrfs_stack_device_id(&disk_super->dev_item);
636 if (devid != device->devid)
637 goto error_free_page;
639 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
640 goto error_free_page;
642 device->generation = btrfs_super_generation(disk_super);
644 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
645 if (btrfs_super_incompat_flags(disk_super) &
646 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
648 "BTRFS: Invalid seeding and uuid-changed device detected\n");
649 goto error_free_page;
652 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
653 fs_devices->seeding = true;
655 if (bdev_read_only(bdev))
656 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
658 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
661 q = bdev_get_queue(bdev);
662 if (!blk_queue_nonrot(q))
663 fs_devices->rotating = true;
666 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
667 device->mode = flags;
669 fs_devices->open_devices++;
670 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
671 device->devid != BTRFS_DEV_REPLACE_DEVID) {
672 fs_devices->rw_devices++;
673 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
675 btrfs_release_disk_super(disk_super);
680 btrfs_release_disk_super(disk_super);
681 blkdev_put(bdev, flags);
687 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
688 * being created with a disk that has already completed its fsid change. Such
689 * disk can belong to an fs which has its FSID changed or to one which doesn't.
690 * Handle both cases here.
692 static struct btrfs_fs_devices *find_fsid_inprogress(
693 struct btrfs_super_block *disk_super)
695 struct btrfs_fs_devices *fs_devices;
697 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
698 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
699 BTRFS_FSID_SIZE) != 0 &&
700 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
701 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
706 return find_fsid(disk_super->fsid, NULL);
710 static struct btrfs_fs_devices *find_fsid_changed(
711 struct btrfs_super_block *disk_super)
713 struct btrfs_fs_devices *fs_devices;
716 * Handles the case where scanned device is part of an fs that had
717 * multiple successful changes of FSID but curently device didn't
718 * observe it. Meaning our fsid will be different than theirs. We need
719 * to handle two subcases :
720 * 1 - The fs still continues to have different METADATA/FSID uuids.
721 * 2 - The fs is switched back to its original FSID (METADATA/FSID
724 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
726 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
727 BTRFS_FSID_SIZE) != 0 &&
728 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
729 BTRFS_FSID_SIZE) == 0 &&
730 memcmp(fs_devices->fsid, disk_super->fsid,
731 BTRFS_FSID_SIZE) != 0)
734 /* Unchanged UUIDs */
735 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
736 BTRFS_FSID_SIZE) == 0 &&
737 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
738 BTRFS_FSID_SIZE) == 0)
745 static struct btrfs_fs_devices *find_fsid_reverted_metadata(
746 struct btrfs_super_block *disk_super)
748 struct btrfs_fs_devices *fs_devices;
751 * Handle the case where the scanned device is part of an fs whose last
752 * metadata UUID change reverted it to the original FSID. At the same
753 * time * fs_devices was first created by another constitutent device
754 * which didn't fully observe the operation. This results in an
755 * btrfs_fs_devices created with metadata/fsid different AND
756 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
757 * fs_devices equal to the FSID of the disk.
759 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
760 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
761 BTRFS_FSID_SIZE) != 0 &&
762 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
763 BTRFS_FSID_SIZE) == 0 &&
764 fs_devices->fsid_change)
771 * Add new device to list of registered devices
774 * device pointer which was just added or updated when successful
775 * error pointer when failed
777 static noinline struct btrfs_device *device_list_add(const char *path,
778 struct btrfs_super_block *disk_super,
779 bool *new_device_added)
781 struct btrfs_device *device;
782 struct btrfs_fs_devices *fs_devices = NULL;
783 struct rcu_string *name;
784 u64 found_transid = btrfs_super_generation(disk_super);
785 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
786 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
787 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
788 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
789 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
791 if (fsid_change_in_progress) {
792 if (!has_metadata_uuid)
793 fs_devices = find_fsid_inprogress(disk_super);
795 fs_devices = find_fsid_changed(disk_super);
796 } else if (has_metadata_uuid) {
797 fs_devices = find_fsid_with_metadata_uuid(disk_super);
799 fs_devices = find_fsid_reverted_metadata(disk_super);
801 fs_devices = find_fsid(disk_super->fsid, NULL);
806 if (has_metadata_uuid)
807 fs_devices = alloc_fs_devices(disk_super->fsid,
808 disk_super->metadata_uuid);
810 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
812 if (IS_ERR(fs_devices))
813 return ERR_CAST(fs_devices);
815 fs_devices->fsid_change = fsid_change_in_progress;
817 mutex_lock(&fs_devices->device_list_mutex);
818 list_add(&fs_devices->fs_list, &fs_uuids);
822 mutex_lock(&fs_devices->device_list_mutex);
823 device = btrfs_find_device(fs_devices, devid,
824 disk_super->dev_item.uuid, NULL, false);
827 * If this disk has been pulled into an fs devices created by
828 * a device which had the CHANGING_FSID_V2 flag then replace the
829 * metadata_uuid/fsid values of the fs_devices.
831 if (fs_devices->fsid_change &&
832 found_transid > fs_devices->latest_generation) {
833 memcpy(fs_devices->fsid, disk_super->fsid,
836 if (has_metadata_uuid)
837 memcpy(fs_devices->metadata_uuid,
838 disk_super->metadata_uuid,
841 memcpy(fs_devices->metadata_uuid,
842 disk_super->fsid, BTRFS_FSID_SIZE);
844 fs_devices->fsid_change = false;
849 if (fs_devices->opened) {
850 mutex_unlock(&fs_devices->device_list_mutex);
851 return ERR_PTR(-EBUSY);
854 device = btrfs_alloc_device(NULL, &devid,
855 disk_super->dev_item.uuid);
856 if (IS_ERR(device)) {
857 mutex_unlock(&fs_devices->device_list_mutex);
858 /* we can safely leave the fs_devices entry around */
862 name = rcu_string_strdup(path, GFP_NOFS);
864 btrfs_free_device(device);
865 mutex_unlock(&fs_devices->device_list_mutex);
866 return ERR_PTR(-ENOMEM);
868 rcu_assign_pointer(device->name, name);
870 list_add_rcu(&device->dev_list, &fs_devices->devices);
871 fs_devices->num_devices++;
873 device->fs_devices = fs_devices;
874 *new_device_added = true;
876 if (disk_super->label[0])
878 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
879 disk_super->label, devid, found_transid, path,
880 current->comm, task_pid_nr(current));
883 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
884 disk_super->fsid, devid, found_transid, path,
885 current->comm, task_pid_nr(current));
887 } else if (!device->name || strcmp(device->name->str, path)) {
889 * When FS is already mounted.
890 * 1. If you are here and if the device->name is NULL that
891 * means this device was missing at time of FS mount.
892 * 2. If you are here and if the device->name is different
893 * from 'path' that means either
894 * a. The same device disappeared and reappeared with
896 * b. The missing-disk-which-was-replaced, has
899 * We must allow 1 and 2a above. But 2b would be a spurious
902 * Further in case of 1 and 2a above, the disk at 'path'
903 * would have missed some transaction when it was away and
904 * in case of 2a the stale bdev has to be updated as well.
905 * 2b must not be allowed at all time.
909 * For now, we do allow update to btrfs_fs_device through the
910 * btrfs dev scan cli after FS has been mounted. We're still
911 * tracking a problem where systems fail mount by subvolume id
912 * when we reject replacement on a mounted FS.
914 if (!fs_devices->opened && found_transid < device->generation) {
916 * That is if the FS is _not_ mounted and if you
917 * are here, that means there is more than one
918 * disk with same uuid and devid.We keep the one
919 * with larger generation number or the last-in if
920 * generation are equal.
922 mutex_unlock(&fs_devices->device_list_mutex);
923 return ERR_PTR(-EEXIST);
927 * We are going to replace the device path for a given devid,
928 * make sure it's the same device if the device is mounted
931 struct block_device *path_bdev;
933 path_bdev = lookup_bdev(path);
934 if (IS_ERR(path_bdev)) {
935 mutex_unlock(&fs_devices->device_list_mutex);
936 return ERR_CAST(path_bdev);
939 if (device->bdev != path_bdev) {
941 mutex_unlock(&fs_devices->device_list_mutex);
942 btrfs_warn_in_rcu(device->fs_info,
943 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
944 disk_super->fsid, devid,
945 rcu_str_deref(device->name), path);
946 return ERR_PTR(-EEXIST);
949 btrfs_info_in_rcu(device->fs_info,
950 "device fsid %pU devid %llu moved old:%s new:%s",
951 disk_super->fsid, devid,
952 rcu_str_deref(device->name), path);
955 name = rcu_string_strdup(path, GFP_NOFS);
957 mutex_unlock(&fs_devices->device_list_mutex);
958 return ERR_PTR(-ENOMEM);
960 rcu_string_free(device->name);
961 rcu_assign_pointer(device->name, name);
962 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
963 fs_devices->missing_devices--;
964 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
969 * Unmount does not free the btrfs_device struct but would zero
970 * generation along with most of the other members. So just update
971 * it back. We need it to pick the disk with largest generation
974 if (!fs_devices->opened) {
975 device->generation = found_transid;
976 fs_devices->latest_generation = max_t(u64, found_transid,
977 fs_devices->latest_generation);
980 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
982 mutex_unlock(&fs_devices->device_list_mutex);
986 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
988 struct btrfs_fs_devices *fs_devices;
989 struct btrfs_device *device;
990 struct btrfs_device *orig_dev;
993 fs_devices = alloc_fs_devices(orig->fsid, NULL);
994 if (IS_ERR(fs_devices))
997 mutex_lock(&orig->device_list_mutex);
998 fs_devices->total_devices = orig->total_devices;
1000 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1001 struct rcu_string *name;
1003 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1005 if (IS_ERR(device)) {
1006 ret = PTR_ERR(device);
1011 * This is ok to do without rcu read locked because we hold the
1012 * uuid mutex so nothing we touch in here is going to disappear.
1014 if (orig_dev->name) {
1015 name = rcu_string_strdup(orig_dev->name->str,
1018 btrfs_free_device(device);
1022 rcu_assign_pointer(device->name, name);
1025 list_add(&device->dev_list, &fs_devices->devices);
1026 device->fs_devices = fs_devices;
1027 fs_devices->num_devices++;
1029 mutex_unlock(&orig->device_list_mutex);
1032 mutex_unlock(&orig->device_list_mutex);
1033 free_fs_devices(fs_devices);
1034 return ERR_PTR(ret);
1038 * After we have read the system tree and know devids belonging to
1039 * this filesystem, remove the device which does not belong there.
1041 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1043 struct btrfs_device *device, *next;
1044 struct btrfs_device *latest_dev = NULL;
1046 mutex_lock(&uuid_mutex);
1048 /* This is the initialized path, it is safe to release the devices. */
1049 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1050 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1051 &device->dev_state)) {
1052 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1053 &device->dev_state) &&
1054 !test_bit(BTRFS_DEV_STATE_MISSING,
1055 &device->dev_state) &&
1057 device->generation > latest_dev->generation)) {
1058 latest_dev = device;
1063 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1065 * In the first step, keep the device which has
1066 * the correct fsid and the devid that is used
1067 * for the dev_replace procedure.
1068 * In the second step, the dev_replace state is
1069 * read from the device tree and it is known
1070 * whether the procedure is really active or
1071 * not, which means whether this device is
1072 * used or whether it should be removed.
1074 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1075 &device->dev_state)) {
1080 blkdev_put(device->bdev, device->mode);
1081 device->bdev = NULL;
1082 fs_devices->open_devices--;
1084 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1085 list_del_init(&device->dev_alloc_list);
1086 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1087 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1088 &device->dev_state))
1089 fs_devices->rw_devices--;
1091 list_del_init(&device->dev_list);
1092 fs_devices->num_devices--;
1093 btrfs_free_device(device);
1096 if (fs_devices->seed) {
1097 fs_devices = fs_devices->seed;
1101 fs_devices->latest_bdev = latest_dev->bdev;
1103 mutex_unlock(&uuid_mutex);
1106 static void btrfs_close_bdev(struct btrfs_device *device)
1111 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1112 sync_blockdev(device->bdev);
1113 invalidate_bdev(device->bdev);
1116 blkdev_put(device->bdev, device->mode);
1119 static void btrfs_close_one_device(struct btrfs_device *device)
1121 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1123 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1124 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1125 list_del_init(&device->dev_alloc_list);
1126 fs_devices->rw_devices--;
1129 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1130 fs_devices->missing_devices--;
1132 btrfs_close_bdev(device);
1134 fs_devices->open_devices--;
1135 device->bdev = NULL;
1137 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1139 device->fs_info = NULL;
1140 atomic_set(&device->dev_stats_ccnt, 0);
1141 extent_io_tree_release(&device->alloc_state);
1143 /* Verify the device is back in a pristine state */
1144 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1145 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1146 ASSERT(list_empty(&device->dev_alloc_list));
1147 ASSERT(list_empty(&device->post_commit_list));
1148 ASSERT(atomic_read(&device->reada_in_flight) == 0);
1151 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1153 struct btrfs_device *device, *tmp;
1155 if (--fs_devices->opened > 0)
1158 mutex_lock(&fs_devices->device_list_mutex);
1159 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1160 btrfs_close_one_device(device);
1162 mutex_unlock(&fs_devices->device_list_mutex);
1164 WARN_ON(fs_devices->open_devices);
1165 WARN_ON(fs_devices->rw_devices);
1166 fs_devices->opened = 0;
1167 fs_devices->seeding = false;
1172 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1174 struct btrfs_fs_devices *seed_devices = NULL;
1177 mutex_lock(&uuid_mutex);
1178 ret = close_fs_devices(fs_devices);
1179 if (!fs_devices->opened) {
1180 seed_devices = fs_devices->seed;
1181 fs_devices->seed = NULL;
1183 mutex_unlock(&uuid_mutex);
1185 while (seed_devices) {
1186 fs_devices = seed_devices;
1187 seed_devices = fs_devices->seed;
1188 close_fs_devices(fs_devices);
1189 free_fs_devices(fs_devices);
1194 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1195 fmode_t flags, void *holder)
1197 struct btrfs_device *device;
1198 struct btrfs_device *latest_dev = NULL;
1200 flags |= FMODE_EXCL;
1202 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1203 /* Just open everything we can; ignore failures here */
1204 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1208 device->generation > latest_dev->generation)
1209 latest_dev = device;
1211 if (fs_devices->open_devices == 0)
1214 fs_devices->opened = 1;
1215 fs_devices->latest_bdev = latest_dev->bdev;
1216 fs_devices->total_rw_bytes = 0;
1217 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1222 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1224 struct btrfs_device *dev1, *dev2;
1226 dev1 = list_entry(a, struct btrfs_device, dev_list);
1227 dev2 = list_entry(b, struct btrfs_device, dev_list);
1229 if (dev1->devid < dev2->devid)
1231 else if (dev1->devid > dev2->devid)
1236 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1237 fmode_t flags, void *holder)
1241 lockdep_assert_held(&uuid_mutex);
1243 * The device_list_mutex cannot be taken here in case opening the
1244 * underlying device takes further locks like bd_mutex.
1246 * We also don't need the lock here as this is called during mount and
1247 * exclusion is provided by uuid_mutex
1250 if (fs_devices->opened) {
1251 fs_devices->opened++;
1254 list_sort(NULL, &fs_devices->devices, devid_cmp);
1255 ret = open_fs_devices(fs_devices, flags, holder);
1261 void btrfs_release_disk_super(struct btrfs_super_block *super)
1263 struct page *page = virt_to_page(super);
1268 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1271 struct btrfs_super_block *disk_super;
1276 /* make sure our super fits in the device */
1277 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1278 return ERR_PTR(-EINVAL);
1280 /* make sure our super fits in the page */
1281 if (sizeof(*disk_super) > PAGE_SIZE)
1282 return ERR_PTR(-EINVAL);
1284 /* make sure our super doesn't straddle pages on disk */
1285 index = bytenr >> PAGE_SHIFT;
1286 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1287 return ERR_PTR(-EINVAL);
1289 /* pull in the page with our super */
1290 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1293 return ERR_CAST(page);
1295 p = page_address(page);
1297 /* align our pointer to the offset of the super block */
1298 disk_super = p + offset_in_page(bytenr);
1300 if (btrfs_super_bytenr(disk_super) != bytenr ||
1301 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1302 btrfs_release_disk_super(p);
1303 return ERR_PTR(-EINVAL);
1306 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1307 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1312 int btrfs_forget_devices(const char *path)
1316 mutex_lock(&uuid_mutex);
1317 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1318 mutex_unlock(&uuid_mutex);
1324 * Look for a btrfs signature on a device. This may be called out of the mount path
1325 * and we are not allowed to call set_blocksize during the scan. The superblock
1326 * is read via pagecache
1328 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1331 struct btrfs_super_block *disk_super;
1332 bool new_device_added = false;
1333 struct btrfs_device *device = NULL;
1334 struct block_device *bdev;
1337 lockdep_assert_held(&uuid_mutex);
1340 * we would like to check all the supers, but that would make
1341 * a btrfs mount succeed after a mkfs from a different FS.
1342 * So, we need to add a special mount option to scan for
1343 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1345 bytenr = btrfs_sb_offset(0);
1346 flags |= FMODE_EXCL;
1348 bdev = blkdev_get_by_path(path, flags, holder);
1350 return ERR_CAST(bdev);
1352 disk_super = btrfs_read_disk_super(bdev, bytenr);
1353 if (IS_ERR(disk_super)) {
1354 device = ERR_CAST(disk_super);
1355 goto error_bdev_put;
1358 device = device_list_add(path, disk_super, &new_device_added);
1359 if (!IS_ERR(device)) {
1360 if (new_device_added)
1361 btrfs_free_stale_devices(path, device);
1364 btrfs_release_disk_super(disk_super);
1367 blkdev_put(bdev, flags);
1373 * Try to find a chunk that intersects [start, start + len] range and when one
1374 * such is found, record the end of it in *start
1376 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1379 u64 physical_start, physical_end;
1381 lockdep_assert_held(&device->fs_info->chunk_mutex);
1383 if (!find_first_extent_bit(&device->alloc_state, *start,
1384 &physical_start, &physical_end,
1385 CHUNK_ALLOCATED, NULL)) {
1387 if (in_range(physical_start, *start, len) ||
1388 in_range(*start, physical_start,
1389 physical_end - physical_start)) {
1390 *start = physical_end + 1;
1397 static u64 dev_extent_search_start(struct btrfs_device *device, u64 start)
1399 switch (device->fs_devices->chunk_alloc_policy) {
1400 case BTRFS_CHUNK_ALLOC_REGULAR:
1402 * We don't want to overwrite the superblock on the drive nor
1403 * any area used by the boot loader (grub for example), so we
1404 * make sure to start at an offset of at least 1MB.
1406 return max_t(u64, start, SZ_1M);
1413 * dev_extent_hole_check - check if specified hole is suitable for allocation
1414 * @device: the device which we have the hole
1415 * @hole_start: starting position of the hole
1416 * @hole_size: the size of the hole
1417 * @num_bytes: the size of the free space that we need
1419 * This function may modify @hole_start and @hole_end to reflect the suitable
1420 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1422 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1423 u64 *hole_size, u64 num_bytes)
1425 bool changed = false;
1426 u64 hole_end = *hole_start + *hole_size;
1429 * Check before we set max_hole_start, otherwise we could end up
1430 * sending back this offset anyway.
1432 if (contains_pending_extent(device, hole_start, *hole_size)) {
1433 if (hole_end >= *hole_start)
1434 *hole_size = hole_end - *hole_start;
1440 switch (device->fs_devices->chunk_alloc_policy) {
1441 case BTRFS_CHUNK_ALLOC_REGULAR:
1442 /* No extra check */
1452 * find_free_dev_extent_start - find free space in the specified device
1453 * @device: the device which we search the free space in
1454 * @num_bytes: the size of the free space that we need
1455 * @search_start: the position from which to begin the search
1456 * @start: store the start of the free space.
1457 * @len: the size of the free space. that we find, or the size
1458 * of the max free space if we don't find suitable free space
1460 * this uses a pretty simple search, the expectation is that it is
1461 * called very infrequently and that a given device has a small number
1464 * @start is used to store the start of the free space if we find. But if we
1465 * don't find suitable free space, it will be used to store the start position
1466 * of the max free space.
1468 * @len is used to store the size of the free space that we find.
1469 * But if we don't find suitable free space, it is used to store the size of
1470 * the max free space.
1472 * NOTE: This function will search *commit* root of device tree, and does extra
1473 * check to ensure dev extents are not double allocated.
1474 * This makes the function safe to allocate dev extents but may not report
1475 * correct usable device space, as device extent freed in current transaction
1476 * is not reported as avaiable.
1478 static int find_free_dev_extent_start(struct btrfs_device *device,
1479 u64 num_bytes, u64 search_start, u64 *start,
1482 struct btrfs_fs_info *fs_info = device->fs_info;
1483 struct btrfs_root *root = fs_info->dev_root;
1484 struct btrfs_key key;
1485 struct btrfs_dev_extent *dev_extent;
1486 struct btrfs_path *path;
1491 u64 search_end = device->total_bytes;
1494 struct extent_buffer *l;
1496 search_start = dev_extent_search_start(device, search_start);
1498 path = btrfs_alloc_path();
1502 max_hole_start = search_start;
1506 if (search_start >= search_end ||
1507 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1512 path->reada = READA_FORWARD;
1513 path->search_commit_root = 1;
1514 path->skip_locking = 1;
1516 key.objectid = device->devid;
1517 key.offset = search_start;
1518 key.type = BTRFS_DEV_EXTENT_KEY;
1520 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1524 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1531 slot = path->slots[0];
1532 if (slot >= btrfs_header_nritems(l)) {
1533 ret = btrfs_next_leaf(root, path);
1541 btrfs_item_key_to_cpu(l, &key, slot);
1543 if (key.objectid < device->devid)
1546 if (key.objectid > device->devid)
1549 if (key.type != BTRFS_DEV_EXTENT_KEY)
1552 if (key.offset > search_start) {
1553 hole_size = key.offset - search_start;
1554 dev_extent_hole_check(device, &search_start, &hole_size,
1557 if (hole_size > max_hole_size) {
1558 max_hole_start = search_start;
1559 max_hole_size = hole_size;
1563 * If this free space is greater than which we need,
1564 * it must be the max free space that we have found
1565 * until now, so max_hole_start must point to the start
1566 * of this free space and the length of this free space
1567 * is stored in max_hole_size. Thus, we return
1568 * max_hole_start and max_hole_size and go back to the
1571 if (hole_size >= num_bytes) {
1577 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1578 extent_end = key.offset + btrfs_dev_extent_length(l,
1580 if (extent_end > search_start)
1581 search_start = extent_end;
1588 * At this point, search_start should be the end of
1589 * allocated dev extents, and when shrinking the device,
1590 * search_end may be smaller than search_start.
1592 if (search_end > search_start) {
1593 hole_size = search_end - search_start;
1594 if (dev_extent_hole_check(device, &search_start, &hole_size,
1596 btrfs_release_path(path);
1600 if (hole_size > max_hole_size) {
1601 max_hole_start = search_start;
1602 max_hole_size = hole_size;
1607 if (max_hole_size < num_bytes)
1613 btrfs_free_path(path);
1614 *start = max_hole_start;
1616 *len = max_hole_size;
1620 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1621 u64 *start, u64 *len)
1623 /* FIXME use last free of some kind */
1624 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1627 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1628 struct btrfs_device *device,
1629 u64 start, u64 *dev_extent_len)
1631 struct btrfs_fs_info *fs_info = device->fs_info;
1632 struct btrfs_root *root = fs_info->dev_root;
1634 struct btrfs_path *path;
1635 struct btrfs_key key;
1636 struct btrfs_key found_key;
1637 struct extent_buffer *leaf = NULL;
1638 struct btrfs_dev_extent *extent = NULL;
1640 path = btrfs_alloc_path();
1644 key.objectid = device->devid;
1646 key.type = BTRFS_DEV_EXTENT_KEY;
1648 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1650 ret = btrfs_previous_item(root, path, key.objectid,
1651 BTRFS_DEV_EXTENT_KEY);
1654 leaf = path->nodes[0];
1655 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1656 extent = btrfs_item_ptr(leaf, path->slots[0],
1657 struct btrfs_dev_extent);
1658 BUG_ON(found_key.offset > start || found_key.offset +
1659 btrfs_dev_extent_length(leaf, extent) < start);
1661 btrfs_release_path(path);
1663 } else if (ret == 0) {
1664 leaf = path->nodes[0];
1665 extent = btrfs_item_ptr(leaf, path->slots[0],
1666 struct btrfs_dev_extent);
1668 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1672 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1674 ret = btrfs_del_item(trans, root, path);
1676 btrfs_handle_fs_error(fs_info, ret,
1677 "Failed to remove dev extent item");
1679 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1682 btrfs_free_path(path);
1686 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1687 struct btrfs_device *device,
1688 u64 chunk_offset, u64 start, u64 num_bytes)
1691 struct btrfs_path *path;
1692 struct btrfs_fs_info *fs_info = device->fs_info;
1693 struct btrfs_root *root = fs_info->dev_root;
1694 struct btrfs_dev_extent *extent;
1695 struct extent_buffer *leaf;
1696 struct btrfs_key key;
1698 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1699 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1700 path = btrfs_alloc_path();
1704 key.objectid = device->devid;
1706 key.type = BTRFS_DEV_EXTENT_KEY;
1707 ret = btrfs_insert_empty_item(trans, root, path, &key,
1712 leaf = path->nodes[0];
1713 extent = btrfs_item_ptr(leaf, path->slots[0],
1714 struct btrfs_dev_extent);
1715 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1716 BTRFS_CHUNK_TREE_OBJECTID);
1717 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1718 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1719 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1721 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1722 btrfs_mark_buffer_dirty(leaf);
1724 btrfs_free_path(path);
1728 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1730 struct extent_map_tree *em_tree;
1731 struct extent_map *em;
1735 em_tree = &fs_info->mapping_tree;
1736 read_lock(&em_tree->lock);
1737 n = rb_last(&em_tree->map.rb_root);
1739 em = rb_entry(n, struct extent_map, rb_node);
1740 ret = em->start + em->len;
1742 read_unlock(&em_tree->lock);
1747 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1751 struct btrfs_key key;
1752 struct btrfs_key found_key;
1753 struct btrfs_path *path;
1755 path = btrfs_alloc_path();
1759 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1760 key.type = BTRFS_DEV_ITEM_KEY;
1761 key.offset = (u64)-1;
1763 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1769 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1774 ret = btrfs_previous_item(fs_info->chunk_root, path,
1775 BTRFS_DEV_ITEMS_OBJECTID,
1776 BTRFS_DEV_ITEM_KEY);
1780 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1782 *devid_ret = found_key.offset + 1;
1786 btrfs_free_path(path);
1791 * the device information is stored in the chunk root
1792 * the btrfs_device struct should be fully filled in
1794 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1795 struct btrfs_device *device)
1798 struct btrfs_path *path;
1799 struct btrfs_dev_item *dev_item;
1800 struct extent_buffer *leaf;
1801 struct btrfs_key key;
1804 path = btrfs_alloc_path();
1808 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1809 key.type = BTRFS_DEV_ITEM_KEY;
1810 key.offset = device->devid;
1812 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1813 &key, sizeof(*dev_item));
1817 leaf = path->nodes[0];
1818 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1820 btrfs_set_device_id(leaf, dev_item, device->devid);
1821 btrfs_set_device_generation(leaf, dev_item, 0);
1822 btrfs_set_device_type(leaf, dev_item, device->type);
1823 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1824 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1825 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1826 btrfs_set_device_total_bytes(leaf, dev_item,
1827 btrfs_device_get_disk_total_bytes(device));
1828 btrfs_set_device_bytes_used(leaf, dev_item,
1829 btrfs_device_get_bytes_used(device));
1830 btrfs_set_device_group(leaf, dev_item, 0);
1831 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1832 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1833 btrfs_set_device_start_offset(leaf, dev_item, 0);
1835 ptr = btrfs_device_uuid(dev_item);
1836 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1837 ptr = btrfs_device_fsid(dev_item);
1838 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1839 ptr, BTRFS_FSID_SIZE);
1840 btrfs_mark_buffer_dirty(leaf);
1844 btrfs_free_path(path);
1849 * Function to update ctime/mtime for a given device path.
1850 * Mainly used for ctime/mtime based probe like libblkid.
1852 static void update_dev_time(const char *path_name)
1856 filp = filp_open(path_name, O_RDWR, 0);
1859 file_update_time(filp);
1860 filp_close(filp, NULL);
1863 static int btrfs_rm_dev_item(struct btrfs_device *device)
1865 struct btrfs_root *root = device->fs_info->chunk_root;
1867 struct btrfs_path *path;
1868 struct btrfs_key key;
1869 struct btrfs_trans_handle *trans;
1871 path = btrfs_alloc_path();
1875 trans = btrfs_start_transaction(root, 0);
1876 if (IS_ERR(trans)) {
1877 btrfs_free_path(path);
1878 return PTR_ERR(trans);
1880 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1881 key.type = BTRFS_DEV_ITEM_KEY;
1882 key.offset = device->devid;
1884 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1888 btrfs_abort_transaction(trans, ret);
1889 btrfs_end_transaction(trans);
1893 ret = btrfs_del_item(trans, root, path);
1895 btrfs_abort_transaction(trans, ret);
1896 btrfs_end_transaction(trans);
1900 btrfs_free_path(path);
1902 ret = btrfs_commit_transaction(trans);
1907 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1908 * filesystem. It's up to the caller to adjust that number regarding eg. device
1911 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1919 seq = read_seqbegin(&fs_info->profiles_lock);
1921 all_avail = fs_info->avail_data_alloc_bits |
1922 fs_info->avail_system_alloc_bits |
1923 fs_info->avail_metadata_alloc_bits;
1924 } while (read_seqretry(&fs_info->profiles_lock, seq));
1926 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1927 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1930 if (num_devices < btrfs_raid_array[i].devs_min) {
1931 int ret = btrfs_raid_array[i].mindev_error;
1941 static struct btrfs_device * btrfs_find_next_active_device(
1942 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1944 struct btrfs_device *next_device;
1946 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1947 if (next_device != device &&
1948 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1949 && next_device->bdev)
1957 * Helper function to check if the given device is part of s_bdev / latest_bdev
1958 * and replace it with the provided or the next active device, in the context
1959 * where this function called, there should be always be another device (or
1960 * this_dev) which is active.
1962 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
1963 struct btrfs_device *this_dev)
1965 struct btrfs_fs_info *fs_info = device->fs_info;
1966 struct btrfs_device *next_device;
1969 next_device = this_dev;
1971 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1973 ASSERT(next_device);
1975 if (fs_info->sb->s_bdev &&
1976 (fs_info->sb->s_bdev == device->bdev))
1977 fs_info->sb->s_bdev = next_device->bdev;
1979 if (fs_info->fs_devices->latest_bdev == device->bdev)
1980 fs_info->fs_devices->latest_bdev = next_device->bdev;
1984 * Return btrfs_fs_devices::num_devices excluding the device that's being
1985 * currently replaced.
1987 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1989 u64 num_devices = fs_info->fs_devices->num_devices;
1991 down_read(&fs_info->dev_replace.rwsem);
1992 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1993 ASSERT(num_devices > 1);
1996 up_read(&fs_info->dev_replace.rwsem);
2001 static void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2002 struct block_device *bdev,
2003 const char *device_path)
2005 struct btrfs_super_block *disk_super;
2011 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2015 disk_super = btrfs_read_dev_one_super(bdev, copy_num);
2016 if (IS_ERR(disk_super))
2019 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
2021 page = virt_to_page(disk_super);
2022 set_page_dirty(page);
2024 /* write_on_page() unlocks the page */
2025 ret = write_one_page(page);
2028 "error clearing superblock number %d (%d)",
2030 btrfs_release_disk_super(disk_super);
2034 /* Notify udev that device has changed */
2035 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2037 /* Update ctime/mtime for device path for libblkid */
2038 update_dev_time(device_path);
2041 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2044 struct btrfs_device *device;
2045 struct btrfs_fs_devices *cur_devices;
2046 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2050 mutex_lock(&uuid_mutex);
2052 num_devices = btrfs_num_devices(fs_info);
2054 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2058 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2060 if (IS_ERR(device)) {
2061 if (PTR_ERR(device) == -ENOENT &&
2062 strcmp(device_path, "missing") == 0)
2063 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2065 ret = PTR_ERR(device);
2069 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2070 btrfs_warn_in_rcu(fs_info,
2071 "cannot remove device %s (devid %llu) due to active swapfile",
2072 rcu_str_deref(device->name), device->devid);
2077 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2078 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2082 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2083 fs_info->fs_devices->rw_devices == 1) {
2084 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2088 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2089 mutex_lock(&fs_info->chunk_mutex);
2090 list_del_init(&device->dev_alloc_list);
2091 device->fs_devices->rw_devices--;
2092 mutex_unlock(&fs_info->chunk_mutex);
2095 mutex_unlock(&uuid_mutex);
2096 ret = btrfs_shrink_device(device, 0);
2097 mutex_lock(&uuid_mutex);
2102 * TODO: the superblock still includes this device in its num_devices
2103 * counter although write_all_supers() is not locked out. This
2104 * could give a filesystem state which requires a degraded mount.
2106 ret = btrfs_rm_dev_item(device);
2110 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2111 btrfs_scrub_cancel_dev(device);
2114 * the device list mutex makes sure that we don't change
2115 * the device list while someone else is writing out all
2116 * the device supers. Whoever is writing all supers, should
2117 * lock the device list mutex before getting the number of
2118 * devices in the super block (super_copy). Conversely,
2119 * whoever updates the number of devices in the super block
2120 * (super_copy) should hold the device list mutex.
2124 * In normal cases the cur_devices == fs_devices. But in case
2125 * of deleting a seed device, the cur_devices should point to
2126 * its own fs_devices listed under the fs_devices->seed.
2128 cur_devices = device->fs_devices;
2129 mutex_lock(&fs_devices->device_list_mutex);
2130 list_del_rcu(&device->dev_list);
2132 cur_devices->num_devices--;
2133 cur_devices->total_devices--;
2134 /* Update total_devices of the parent fs_devices if it's seed */
2135 if (cur_devices != fs_devices)
2136 fs_devices->total_devices--;
2138 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2139 cur_devices->missing_devices--;
2141 btrfs_assign_next_active_device(device, NULL);
2144 cur_devices->open_devices--;
2145 /* remove sysfs entry */
2146 btrfs_sysfs_remove_devices_dir(fs_devices, device);
2149 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2150 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2151 mutex_unlock(&fs_devices->device_list_mutex);
2154 * at this point, the device is zero sized and detached from
2155 * the devices list. All that's left is to zero out the old
2156 * supers and free the device.
2158 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2159 btrfs_scratch_superblocks(fs_info, device->bdev,
2162 btrfs_close_bdev(device);
2164 btrfs_free_device(device);
2166 if (cur_devices->open_devices == 0) {
2167 while (fs_devices) {
2168 if (fs_devices->seed == cur_devices) {
2169 fs_devices->seed = cur_devices->seed;
2172 fs_devices = fs_devices->seed;
2174 cur_devices->seed = NULL;
2175 close_fs_devices(cur_devices);
2176 free_fs_devices(cur_devices);
2180 mutex_unlock(&uuid_mutex);
2184 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2185 mutex_lock(&fs_info->chunk_mutex);
2186 list_add(&device->dev_alloc_list,
2187 &fs_devices->alloc_list);
2188 device->fs_devices->rw_devices++;
2189 mutex_unlock(&fs_info->chunk_mutex);
2194 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2196 struct btrfs_fs_devices *fs_devices;
2198 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2201 * in case of fs with no seed, srcdev->fs_devices will point
2202 * to fs_devices of fs_info. However when the dev being replaced is
2203 * a seed dev it will point to the seed's local fs_devices. In short
2204 * srcdev will have its correct fs_devices in both the cases.
2206 fs_devices = srcdev->fs_devices;
2208 list_del_rcu(&srcdev->dev_list);
2209 list_del(&srcdev->dev_alloc_list);
2210 fs_devices->num_devices--;
2211 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2212 fs_devices->missing_devices--;
2214 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2215 fs_devices->rw_devices--;
2218 fs_devices->open_devices--;
2221 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2223 struct btrfs_fs_info *fs_info = srcdev->fs_info;
2224 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2226 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2227 /* zero out the old super if it is writable */
2228 btrfs_scratch_superblocks(fs_info, srcdev->bdev,
2232 btrfs_close_bdev(srcdev);
2234 btrfs_free_device(srcdev);
2236 /* if this is no devs we rather delete the fs_devices */
2237 if (!fs_devices->num_devices) {
2238 struct btrfs_fs_devices *tmp_fs_devices;
2241 * On a mounted FS, num_devices can't be zero unless it's a
2242 * seed. In case of a seed device being replaced, the replace
2243 * target added to the sprout FS, so there will be no more
2244 * device left under the seed FS.
2246 ASSERT(fs_devices->seeding);
2248 tmp_fs_devices = fs_info->fs_devices;
2249 while (tmp_fs_devices) {
2250 if (tmp_fs_devices->seed == fs_devices) {
2251 tmp_fs_devices->seed = fs_devices->seed;
2254 tmp_fs_devices = tmp_fs_devices->seed;
2256 fs_devices->seed = NULL;
2257 close_fs_devices(fs_devices);
2258 free_fs_devices(fs_devices);
2262 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2264 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2266 mutex_lock(&fs_devices->device_list_mutex);
2268 btrfs_sysfs_remove_devices_dir(fs_devices, tgtdev);
2271 fs_devices->open_devices--;
2273 fs_devices->num_devices--;
2275 btrfs_assign_next_active_device(tgtdev, NULL);
2277 list_del_rcu(&tgtdev->dev_list);
2279 mutex_unlock(&fs_devices->device_list_mutex);
2282 * The update_dev_time() with in btrfs_scratch_superblocks()
2283 * may lead to a call to btrfs_show_devname() which will try
2284 * to hold device_list_mutex. And here this device
2285 * is already out of device list, so we don't have to hold
2286 * the device_list_mutex lock.
2288 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2291 btrfs_close_bdev(tgtdev);
2293 btrfs_free_device(tgtdev);
2296 static struct btrfs_device *btrfs_find_device_by_path(
2297 struct btrfs_fs_info *fs_info, const char *device_path)
2300 struct btrfs_super_block *disk_super;
2303 struct block_device *bdev;
2304 struct btrfs_device *device;
2306 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2307 fs_info->bdev_holder, 0, &bdev, &disk_super);
2309 return ERR_PTR(ret);
2311 devid = btrfs_stack_device_id(&disk_super->dev_item);
2312 dev_uuid = disk_super->dev_item.uuid;
2313 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2314 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2315 disk_super->metadata_uuid, true);
2317 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2318 disk_super->fsid, true);
2320 btrfs_release_disk_super(disk_super);
2322 device = ERR_PTR(-ENOENT);
2323 blkdev_put(bdev, FMODE_READ);
2328 * Lookup a device given by device id, or the path if the id is 0.
2330 struct btrfs_device *btrfs_find_device_by_devspec(
2331 struct btrfs_fs_info *fs_info, u64 devid,
2332 const char *device_path)
2334 struct btrfs_device *device;
2337 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2340 return ERR_PTR(-ENOENT);
2344 if (!device_path || !device_path[0])
2345 return ERR_PTR(-EINVAL);
2347 if (strcmp(device_path, "missing") == 0) {
2348 /* Find first missing device */
2349 list_for_each_entry(device, &fs_info->fs_devices->devices,
2351 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2352 &device->dev_state) && !device->bdev)
2355 return ERR_PTR(-ENOENT);
2358 return btrfs_find_device_by_path(fs_info, device_path);
2362 * does all the dirty work required for changing file system's UUID.
2364 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2366 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2367 struct btrfs_fs_devices *old_devices;
2368 struct btrfs_fs_devices *seed_devices;
2369 struct btrfs_super_block *disk_super = fs_info->super_copy;
2370 struct btrfs_device *device;
2373 lockdep_assert_held(&uuid_mutex);
2374 if (!fs_devices->seeding)
2377 seed_devices = alloc_fs_devices(NULL, NULL);
2378 if (IS_ERR(seed_devices))
2379 return PTR_ERR(seed_devices);
2381 old_devices = clone_fs_devices(fs_devices);
2382 if (IS_ERR(old_devices)) {
2383 kfree(seed_devices);
2384 return PTR_ERR(old_devices);
2387 list_add(&old_devices->fs_list, &fs_uuids);
2389 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2390 seed_devices->opened = 1;
2391 INIT_LIST_HEAD(&seed_devices->devices);
2392 INIT_LIST_HEAD(&seed_devices->alloc_list);
2393 mutex_init(&seed_devices->device_list_mutex);
2395 mutex_lock(&fs_devices->device_list_mutex);
2396 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2398 list_for_each_entry(device, &seed_devices->devices, dev_list)
2399 device->fs_devices = seed_devices;
2401 mutex_lock(&fs_info->chunk_mutex);
2402 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2403 mutex_unlock(&fs_info->chunk_mutex);
2405 fs_devices->seeding = false;
2406 fs_devices->num_devices = 0;
2407 fs_devices->open_devices = 0;
2408 fs_devices->missing_devices = 0;
2409 fs_devices->rotating = false;
2410 fs_devices->seed = seed_devices;
2412 generate_random_uuid(fs_devices->fsid);
2413 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2414 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2415 mutex_unlock(&fs_devices->device_list_mutex);
2417 super_flags = btrfs_super_flags(disk_super) &
2418 ~BTRFS_SUPER_FLAG_SEEDING;
2419 btrfs_set_super_flags(disk_super, super_flags);
2425 * Store the expected generation for seed devices in device items.
2427 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2429 struct btrfs_fs_info *fs_info = trans->fs_info;
2430 struct btrfs_root *root = fs_info->chunk_root;
2431 struct btrfs_path *path;
2432 struct extent_buffer *leaf;
2433 struct btrfs_dev_item *dev_item;
2434 struct btrfs_device *device;
2435 struct btrfs_key key;
2436 u8 fs_uuid[BTRFS_FSID_SIZE];
2437 u8 dev_uuid[BTRFS_UUID_SIZE];
2441 path = btrfs_alloc_path();
2445 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2447 key.type = BTRFS_DEV_ITEM_KEY;
2450 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2454 leaf = path->nodes[0];
2456 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2457 ret = btrfs_next_leaf(root, path);
2462 leaf = path->nodes[0];
2463 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2464 btrfs_release_path(path);
2468 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2469 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2470 key.type != BTRFS_DEV_ITEM_KEY)
2473 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2474 struct btrfs_dev_item);
2475 devid = btrfs_device_id(leaf, dev_item);
2476 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2478 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2480 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2482 BUG_ON(!device); /* Logic error */
2484 if (device->fs_devices->seeding) {
2485 btrfs_set_device_generation(leaf, dev_item,
2486 device->generation);
2487 btrfs_mark_buffer_dirty(leaf);
2495 btrfs_free_path(path);
2499 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2501 struct btrfs_root *root = fs_info->dev_root;
2502 struct request_queue *q;
2503 struct btrfs_trans_handle *trans;
2504 struct btrfs_device *device;
2505 struct block_device *bdev;
2506 struct super_block *sb = fs_info->sb;
2507 struct rcu_string *name;
2508 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2509 u64 orig_super_total_bytes;
2510 u64 orig_super_num_devices;
2511 int seeding_dev = 0;
2513 bool unlocked = false;
2515 if (sb_rdonly(sb) && !fs_devices->seeding)
2518 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2519 fs_info->bdev_holder);
2521 return PTR_ERR(bdev);
2523 if (fs_devices->seeding) {
2525 down_write(&sb->s_umount);
2526 mutex_lock(&uuid_mutex);
2529 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2531 mutex_lock(&fs_devices->device_list_mutex);
2532 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2533 if (device->bdev == bdev) {
2536 &fs_devices->device_list_mutex);
2540 mutex_unlock(&fs_devices->device_list_mutex);
2542 device = btrfs_alloc_device(fs_info, NULL, NULL);
2543 if (IS_ERR(device)) {
2544 /* we can safely leave the fs_devices entry around */
2545 ret = PTR_ERR(device);
2549 name = rcu_string_strdup(device_path, GFP_KERNEL);
2552 goto error_free_device;
2554 rcu_assign_pointer(device->name, name);
2556 trans = btrfs_start_transaction(root, 0);
2557 if (IS_ERR(trans)) {
2558 ret = PTR_ERR(trans);
2559 goto error_free_device;
2562 q = bdev_get_queue(bdev);
2563 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2564 device->generation = trans->transid;
2565 device->io_width = fs_info->sectorsize;
2566 device->io_align = fs_info->sectorsize;
2567 device->sector_size = fs_info->sectorsize;
2568 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2569 fs_info->sectorsize);
2570 device->disk_total_bytes = device->total_bytes;
2571 device->commit_total_bytes = device->total_bytes;
2572 device->fs_info = fs_info;
2573 device->bdev = bdev;
2574 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2575 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2576 device->mode = FMODE_EXCL;
2577 device->dev_stats_valid = 1;
2578 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2581 sb->s_flags &= ~SB_RDONLY;
2582 ret = btrfs_prepare_sprout(fs_info);
2584 btrfs_abort_transaction(trans, ret);
2589 device->fs_devices = fs_devices;
2591 mutex_lock(&fs_devices->device_list_mutex);
2592 mutex_lock(&fs_info->chunk_mutex);
2593 list_add_rcu(&device->dev_list, &fs_devices->devices);
2594 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2595 fs_devices->num_devices++;
2596 fs_devices->open_devices++;
2597 fs_devices->rw_devices++;
2598 fs_devices->total_devices++;
2599 fs_devices->total_rw_bytes += device->total_bytes;
2601 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2603 if (!blk_queue_nonrot(q))
2604 fs_devices->rotating = true;
2606 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2607 btrfs_set_super_total_bytes(fs_info->super_copy,
2608 round_down(orig_super_total_bytes + device->total_bytes,
2609 fs_info->sectorsize));
2611 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2612 btrfs_set_super_num_devices(fs_info->super_copy,
2613 orig_super_num_devices + 1);
2615 /* add sysfs device entry */
2616 btrfs_sysfs_add_devices_dir(fs_devices, device);
2619 * we've got more storage, clear any full flags on the space
2622 btrfs_clear_space_info_full(fs_info);
2624 mutex_unlock(&fs_info->chunk_mutex);
2625 mutex_unlock(&fs_devices->device_list_mutex);
2628 mutex_lock(&fs_info->chunk_mutex);
2629 ret = init_first_rw_device(trans);
2630 mutex_unlock(&fs_info->chunk_mutex);
2632 btrfs_abort_transaction(trans, ret);
2637 ret = btrfs_add_dev_item(trans, device);
2639 btrfs_abort_transaction(trans, ret);
2644 ret = btrfs_finish_sprout(trans);
2646 btrfs_abort_transaction(trans, ret);
2650 btrfs_sysfs_update_sprout_fsid(fs_devices,
2651 fs_info->fs_devices->fsid);
2654 ret = btrfs_commit_transaction(trans);
2657 mutex_unlock(&uuid_mutex);
2658 up_write(&sb->s_umount);
2661 if (ret) /* transaction commit */
2664 ret = btrfs_relocate_sys_chunks(fs_info);
2666 btrfs_handle_fs_error(fs_info, ret,
2667 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2668 trans = btrfs_attach_transaction(root);
2669 if (IS_ERR(trans)) {
2670 if (PTR_ERR(trans) == -ENOENT)
2672 ret = PTR_ERR(trans);
2676 ret = btrfs_commit_transaction(trans);
2680 * Now that we have written a new super block to this device, check all
2681 * other fs_devices list if device_path alienates any other scanned
2683 * We can ignore the return value as it typically returns -EINVAL and
2684 * only succeeds if the device was an alien.
2686 btrfs_forget_devices(device_path);
2688 /* Update ctime/mtime for blkid or udev */
2689 update_dev_time(device_path);
2694 btrfs_sysfs_remove_devices_dir(fs_devices, device);
2695 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2696 mutex_lock(&fs_info->chunk_mutex);
2697 list_del_rcu(&device->dev_list);
2698 list_del(&device->dev_alloc_list);
2699 fs_info->fs_devices->num_devices--;
2700 fs_info->fs_devices->open_devices--;
2701 fs_info->fs_devices->rw_devices--;
2702 fs_info->fs_devices->total_devices--;
2703 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2704 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2705 btrfs_set_super_total_bytes(fs_info->super_copy,
2706 orig_super_total_bytes);
2707 btrfs_set_super_num_devices(fs_info->super_copy,
2708 orig_super_num_devices);
2709 mutex_unlock(&fs_info->chunk_mutex);
2710 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2713 sb->s_flags |= SB_RDONLY;
2715 btrfs_end_transaction(trans);
2717 btrfs_free_device(device);
2719 blkdev_put(bdev, FMODE_EXCL);
2720 if (seeding_dev && !unlocked) {
2721 mutex_unlock(&uuid_mutex);
2722 up_write(&sb->s_umount);
2727 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2728 struct btrfs_device *device)
2731 struct btrfs_path *path;
2732 struct btrfs_root *root = device->fs_info->chunk_root;
2733 struct btrfs_dev_item *dev_item;
2734 struct extent_buffer *leaf;
2735 struct btrfs_key key;
2737 path = btrfs_alloc_path();
2741 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2742 key.type = BTRFS_DEV_ITEM_KEY;
2743 key.offset = device->devid;
2745 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2754 leaf = path->nodes[0];
2755 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2757 btrfs_set_device_id(leaf, dev_item, device->devid);
2758 btrfs_set_device_type(leaf, dev_item, device->type);
2759 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2760 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2761 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2762 btrfs_set_device_total_bytes(leaf, dev_item,
2763 btrfs_device_get_disk_total_bytes(device));
2764 btrfs_set_device_bytes_used(leaf, dev_item,
2765 btrfs_device_get_bytes_used(device));
2766 btrfs_mark_buffer_dirty(leaf);
2769 btrfs_free_path(path);
2773 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2774 struct btrfs_device *device, u64 new_size)
2776 struct btrfs_fs_info *fs_info = device->fs_info;
2777 struct btrfs_super_block *super_copy = fs_info->super_copy;
2781 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2784 new_size = round_down(new_size, fs_info->sectorsize);
2786 mutex_lock(&fs_info->chunk_mutex);
2787 old_total = btrfs_super_total_bytes(super_copy);
2788 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2790 if (new_size <= device->total_bytes ||
2791 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2792 mutex_unlock(&fs_info->chunk_mutex);
2796 btrfs_set_super_total_bytes(super_copy,
2797 round_down(old_total + diff, fs_info->sectorsize));
2798 device->fs_devices->total_rw_bytes += diff;
2800 btrfs_device_set_total_bytes(device, new_size);
2801 btrfs_device_set_disk_total_bytes(device, new_size);
2802 btrfs_clear_space_info_full(device->fs_info);
2803 if (list_empty(&device->post_commit_list))
2804 list_add_tail(&device->post_commit_list,
2805 &trans->transaction->dev_update_list);
2806 mutex_unlock(&fs_info->chunk_mutex);
2808 return btrfs_update_device(trans, device);
2811 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2813 struct btrfs_fs_info *fs_info = trans->fs_info;
2814 struct btrfs_root *root = fs_info->chunk_root;
2816 struct btrfs_path *path;
2817 struct btrfs_key key;
2819 path = btrfs_alloc_path();
2823 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2824 key.offset = chunk_offset;
2825 key.type = BTRFS_CHUNK_ITEM_KEY;
2827 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2830 else if (ret > 0) { /* Logic error or corruption */
2831 btrfs_handle_fs_error(fs_info, -ENOENT,
2832 "Failed lookup while freeing chunk.");
2837 ret = btrfs_del_item(trans, root, path);
2839 btrfs_handle_fs_error(fs_info, ret,
2840 "Failed to delete chunk item.");
2842 btrfs_free_path(path);
2846 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2848 struct btrfs_super_block *super_copy = fs_info->super_copy;
2849 struct btrfs_disk_key *disk_key;
2850 struct btrfs_chunk *chunk;
2857 struct btrfs_key key;
2859 mutex_lock(&fs_info->chunk_mutex);
2860 array_size = btrfs_super_sys_array_size(super_copy);
2862 ptr = super_copy->sys_chunk_array;
2865 while (cur < array_size) {
2866 disk_key = (struct btrfs_disk_key *)ptr;
2867 btrfs_disk_key_to_cpu(&key, disk_key);
2869 len = sizeof(*disk_key);
2871 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2872 chunk = (struct btrfs_chunk *)(ptr + len);
2873 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2874 len += btrfs_chunk_item_size(num_stripes);
2879 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2880 key.offset == chunk_offset) {
2881 memmove(ptr, ptr + len, array_size - (cur + len));
2883 btrfs_set_super_sys_array_size(super_copy, array_size);
2889 mutex_unlock(&fs_info->chunk_mutex);
2894 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2895 * @logical: Logical block offset in bytes.
2896 * @length: Length of extent in bytes.
2898 * Return: Chunk mapping or ERR_PTR.
2900 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2901 u64 logical, u64 length)
2903 struct extent_map_tree *em_tree;
2904 struct extent_map *em;
2906 em_tree = &fs_info->mapping_tree;
2907 read_lock(&em_tree->lock);
2908 em = lookup_extent_mapping(em_tree, logical, length);
2909 read_unlock(&em_tree->lock);
2912 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2914 return ERR_PTR(-EINVAL);
2917 if (em->start > logical || em->start + em->len < logical) {
2919 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2920 logical, length, em->start, em->start + em->len);
2921 free_extent_map(em);
2922 return ERR_PTR(-EINVAL);
2925 /* callers are responsible for dropping em's ref. */
2929 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2931 struct btrfs_fs_info *fs_info = trans->fs_info;
2932 struct extent_map *em;
2933 struct map_lookup *map;
2934 u64 dev_extent_len = 0;
2936 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2938 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2941 * This is a logic error, but we don't want to just rely on the
2942 * user having built with ASSERT enabled, so if ASSERT doesn't
2943 * do anything we still error out.
2948 map = em->map_lookup;
2949 mutex_lock(&fs_info->chunk_mutex);
2950 check_system_chunk(trans, map->type);
2951 mutex_unlock(&fs_info->chunk_mutex);
2954 * Take the device list mutex to prevent races with the final phase of
2955 * a device replace operation that replaces the device object associated
2956 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2958 mutex_lock(&fs_devices->device_list_mutex);
2959 for (i = 0; i < map->num_stripes; i++) {
2960 struct btrfs_device *device = map->stripes[i].dev;
2961 ret = btrfs_free_dev_extent(trans, device,
2962 map->stripes[i].physical,
2965 mutex_unlock(&fs_devices->device_list_mutex);
2966 btrfs_abort_transaction(trans, ret);
2970 if (device->bytes_used > 0) {
2971 mutex_lock(&fs_info->chunk_mutex);
2972 btrfs_device_set_bytes_used(device,
2973 device->bytes_used - dev_extent_len);
2974 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2975 btrfs_clear_space_info_full(fs_info);
2976 mutex_unlock(&fs_info->chunk_mutex);
2979 ret = btrfs_update_device(trans, device);
2981 mutex_unlock(&fs_devices->device_list_mutex);
2982 btrfs_abort_transaction(trans, ret);
2986 mutex_unlock(&fs_devices->device_list_mutex);
2988 ret = btrfs_free_chunk(trans, chunk_offset);
2990 btrfs_abort_transaction(trans, ret);
2994 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2996 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2997 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2999 btrfs_abort_transaction(trans, ret);
3004 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3006 btrfs_abort_transaction(trans, ret);
3012 free_extent_map(em);
3016 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3018 struct btrfs_root *root = fs_info->chunk_root;
3019 struct btrfs_trans_handle *trans;
3020 struct btrfs_block_group *block_group;
3024 * Prevent races with automatic removal of unused block groups.
3025 * After we relocate and before we remove the chunk with offset
3026 * chunk_offset, automatic removal of the block group can kick in,
3027 * resulting in a failure when calling btrfs_remove_chunk() below.
3029 * Make sure to acquire this mutex before doing a tree search (dev
3030 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3031 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3032 * we release the path used to search the chunk/dev tree and before
3033 * the current task acquires this mutex and calls us.
3035 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3037 /* step one, relocate all the extents inside this chunk */
3038 btrfs_scrub_pause(fs_info);
3039 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3040 btrfs_scrub_continue(fs_info);
3044 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3047 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3048 btrfs_put_block_group(block_group);
3050 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3052 if (IS_ERR(trans)) {
3053 ret = PTR_ERR(trans);
3054 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3059 * step two, delete the device extents and the
3060 * chunk tree entries
3062 ret = btrfs_remove_chunk(trans, chunk_offset);
3063 btrfs_end_transaction(trans);
3067 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3069 struct btrfs_root *chunk_root = fs_info->chunk_root;
3070 struct btrfs_path *path;
3071 struct extent_buffer *leaf;
3072 struct btrfs_chunk *chunk;
3073 struct btrfs_key key;
3074 struct btrfs_key found_key;
3076 bool retried = false;
3080 path = btrfs_alloc_path();
3085 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3086 key.offset = (u64)-1;
3087 key.type = BTRFS_CHUNK_ITEM_KEY;
3090 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3091 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3093 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3096 BUG_ON(ret == 0); /* Corruption */
3098 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3101 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3107 leaf = path->nodes[0];
3108 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3110 chunk = btrfs_item_ptr(leaf, path->slots[0],
3111 struct btrfs_chunk);
3112 chunk_type = btrfs_chunk_type(leaf, chunk);
3113 btrfs_release_path(path);
3115 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3116 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3122 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3124 if (found_key.offset == 0)
3126 key.offset = found_key.offset - 1;
3129 if (failed && !retried) {
3133 } else if (WARN_ON(failed && retried)) {
3137 btrfs_free_path(path);
3142 * return 1 : allocate a data chunk successfully,
3143 * return <0: errors during allocating a data chunk,
3144 * return 0 : no need to allocate a data chunk.
3146 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3149 struct btrfs_block_group *cache;
3153 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3155 chunk_type = cache->flags;
3156 btrfs_put_block_group(cache);
3158 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3161 spin_lock(&fs_info->data_sinfo->lock);
3162 bytes_used = fs_info->data_sinfo->bytes_used;
3163 spin_unlock(&fs_info->data_sinfo->lock);
3166 struct btrfs_trans_handle *trans;
3169 trans = btrfs_join_transaction(fs_info->tree_root);
3171 return PTR_ERR(trans);
3173 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3174 btrfs_end_transaction(trans);
3183 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3184 struct btrfs_balance_control *bctl)
3186 struct btrfs_root *root = fs_info->tree_root;
3187 struct btrfs_trans_handle *trans;
3188 struct btrfs_balance_item *item;
3189 struct btrfs_disk_balance_args disk_bargs;
3190 struct btrfs_path *path;
3191 struct extent_buffer *leaf;
3192 struct btrfs_key key;
3195 path = btrfs_alloc_path();
3199 trans = btrfs_start_transaction(root, 0);
3200 if (IS_ERR(trans)) {
3201 btrfs_free_path(path);
3202 return PTR_ERR(trans);
3205 key.objectid = BTRFS_BALANCE_OBJECTID;
3206 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3209 ret = btrfs_insert_empty_item(trans, root, path, &key,
3214 leaf = path->nodes[0];
3215 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3217 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3219 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3220 btrfs_set_balance_data(leaf, item, &disk_bargs);
3221 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3222 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3223 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3224 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3226 btrfs_set_balance_flags(leaf, item, bctl->flags);
3228 btrfs_mark_buffer_dirty(leaf);
3230 btrfs_free_path(path);
3231 err = btrfs_commit_transaction(trans);
3237 static int del_balance_item(struct btrfs_fs_info *fs_info)
3239 struct btrfs_root *root = fs_info->tree_root;
3240 struct btrfs_trans_handle *trans;
3241 struct btrfs_path *path;
3242 struct btrfs_key key;
3245 path = btrfs_alloc_path();
3249 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3250 if (IS_ERR(trans)) {
3251 btrfs_free_path(path);
3252 return PTR_ERR(trans);
3255 key.objectid = BTRFS_BALANCE_OBJECTID;
3256 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3259 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3267 ret = btrfs_del_item(trans, root, path);
3269 btrfs_free_path(path);
3270 err = btrfs_commit_transaction(trans);
3277 * This is a heuristic used to reduce the number of chunks balanced on
3278 * resume after balance was interrupted.
3280 static void update_balance_args(struct btrfs_balance_control *bctl)
3283 * Turn on soft mode for chunk types that were being converted.
3285 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3286 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3287 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3288 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3289 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3290 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3293 * Turn on usage filter if is not already used. The idea is
3294 * that chunks that we have already balanced should be
3295 * reasonably full. Don't do it for chunks that are being
3296 * converted - that will keep us from relocating unconverted
3297 * (albeit full) chunks.
3299 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3300 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3301 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3302 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3303 bctl->data.usage = 90;
3305 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3306 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3307 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3308 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3309 bctl->sys.usage = 90;
3311 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3312 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3313 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3314 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3315 bctl->meta.usage = 90;
3320 * Clear the balance status in fs_info and delete the balance item from disk.
3322 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3324 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3327 BUG_ON(!fs_info->balance_ctl);
3329 spin_lock(&fs_info->balance_lock);
3330 fs_info->balance_ctl = NULL;
3331 spin_unlock(&fs_info->balance_lock);
3334 ret = del_balance_item(fs_info);
3336 btrfs_handle_fs_error(fs_info, ret, NULL);
3340 * Balance filters. Return 1 if chunk should be filtered out
3341 * (should not be balanced).
3343 static int chunk_profiles_filter(u64 chunk_type,
3344 struct btrfs_balance_args *bargs)
3346 chunk_type = chunk_to_extended(chunk_type) &
3347 BTRFS_EXTENDED_PROFILE_MASK;
3349 if (bargs->profiles & chunk_type)
3355 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3356 struct btrfs_balance_args *bargs)
3358 struct btrfs_block_group *cache;
3360 u64 user_thresh_min;
3361 u64 user_thresh_max;
3364 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3365 chunk_used = cache->used;
3367 if (bargs->usage_min == 0)
3368 user_thresh_min = 0;
3370 user_thresh_min = div_factor_fine(cache->length,
3373 if (bargs->usage_max == 0)
3374 user_thresh_max = 1;
3375 else if (bargs->usage_max > 100)
3376 user_thresh_max = cache->length;
3378 user_thresh_max = div_factor_fine(cache->length,
3381 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3384 btrfs_put_block_group(cache);
3388 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3389 u64 chunk_offset, struct btrfs_balance_args *bargs)
3391 struct btrfs_block_group *cache;
3392 u64 chunk_used, user_thresh;
3395 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3396 chunk_used = cache->used;
3398 if (bargs->usage_min == 0)
3400 else if (bargs->usage > 100)
3401 user_thresh = cache->length;
3403 user_thresh = div_factor_fine(cache->length, bargs->usage);
3405 if (chunk_used < user_thresh)
3408 btrfs_put_block_group(cache);
3412 static int chunk_devid_filter(struct extent_buffer *leaf,
3413 struct btrfs_chunk *chunk,
3414 struct btrfs_balance_args *bargs)
3416 struct btrfs_stripe *stripe;
3417 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3420 for (i = 0; i < num_stripes; i++) {
3421 stripe = btrfs_stripe_nr(chunk, i);
3422 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3429 static u64 calc_data_stripes(u64 type, int num_stripes)
3431 const int index = btrfs_bg_flags_to_raid_index(type);
3432 const int ncopies = btrfs_raid_array[index].ncopies;
3433 const int nparity = btrfs_raid_array[index].nparity;
3436 return num_stripes - nparity;
3438 return num_stripes / ncopies;
3441 /* [pstart, pend) */
3442 static int chunk_drange_filter(struct extent_buffer *leaf,
3443 struct btrfs_chunk *chunk,
3444 struct btrfs_balance_args *bargs)
3446 struct btrfs_stripe *stripe;
3447 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3454 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3457 type = btrfs_chunk_type(leaf, chunk);
3458 factor = calc_data_stripes(type, num_stripes);
3460 for (i = 0; i < num_stripes; i++) {
3461 stripe = btrfs_stripe_nr(chunk, i);
3462 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3465 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3466 stripe_length = btrfs_chunk_length(leaf, chunk);
3467 stripe_length = div_u64(stripe_length, factor);
3469 if (stripe_offset < bargs->pend &&
3470 stripe_offset + stripe_length > bargs->pstart)
3477 /* [vstart, vend) */
3478 static int chunk_vrange_filter(struct extent_buffer *leaf,
3479 struct btrfs_chunk *chunk,
3481 struct btrfs_balance_args *bargs)
3483 if (chunk_offset < bargs->vend &&
3484 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3485 /* at least part of the chunk is inside this vrange */
3491 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3492 struct btrfs_chunk *chunk,
3493 struct btrfs_balance_args *bargs)
3495 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3497 if (bargs->stripes_min <= num_stripes
3498 && num_stripes <= bargs->stripes_max)
3504 static int chunk_soft_convert_filter(u64 chunk_type,
3505 struct btrfs_balance_args *bargs)
3507 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3510 chunk_type = chunk_to_extended(chunk_type) &
3511 BTRFS_EXTENDED_PROFILE_MASK;
3513 if (bargs->target == chunk_type)
3519 static int should_balance_chunk(struct extent_buffer *leaf,
3520 struct btrfs_chunk *chunk, u64 chunk_offset)
3522 struct btrfs_fs_info *fs_info = leaf->fs_info;
3523 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3524 struct btrfs_balance_args *bargs = NULL;
3525 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3528 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3529 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3533 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3534 bargs = &bctl->data;
3535 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3537 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3538 bargs = &bctl->meta;
3540 /* profiles filter */
3541 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3542 chunk_profiles_filter(chunk_type, bargs)) {
3547 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3548 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3550 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3551 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3556 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3557 chunk_devid_filter(leaf, chunk, bargs)) {
3561 /* drange filter, makes sense only with devid filter */
3562 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3563 chunk_drange_filter(leaf, chunk, bargs)) {
3568 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3569 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3573 /* stripes filter */
3574 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3575 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3579 /* soft profile changing mode */
3580 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3581 chunk_soft_convert_filter(chunk_type, bargs)) {
3586 * limited by count, must be the last filter
3588 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3589 if (bargs->limit == 0)
3593 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3595 * Same logic as the 'limit' filter; the minimum cannot be
3596 * determined here because we do not have the global information
3597 * about the count of all chunks that satisfy the filters.
3599 if (bargs->limit_max == 0)
3608 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3610 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3611 struct btrfs_root *chunk_root = fs_info->chunk_root;
3613 struct btrfs_chunk *chunk;
3614 struct btrfs_path *path = NULL;
3615 struct btrfs_key key;
3616 struct btrfs_key found_key;
3617 struct extent_buffer *leaf;
3620 int enospc_errors = 0;
3621 bool counting = true;
3622 /* The single value limit and min/max limits use the same bytes in the */
3623 u64 limit_data = bctl->data.limit;
3624 u64 limit_meta = bctl->meta.limit;
3625 u64 limit_sys = bctl->sys.limit;
3629 int chunk_reserved = 0;
3631 path = btrfs_alloc_path();
3637 /* zero out stat counters */
3638 spin_lock(&fs_info->balance_lock);
3639 memset(&bctl->stat, 0, sizeof(bctl->stat));
3640 spin_unlock(&fs_info->balance_lock);
3644 * The single value limit and min/max limits use the same bytes
3647 bctl->data.limit = limit_data;
3648 bctl->meta.limit = limit_meta;
3649 bctl->sys.limit = limit_sys;
3651 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3652 key.offset = (u64)-1;
3653 key.type = BTRFS_CHUNK_ITEM_KEY;
3656 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3657 atomic_read(&fs_info->balance_cancel_req)) {
3662 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3663 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3665 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3670 * this shouldn't happen, it means the last relocate
3674 BUG(); /* FIXME break ? */
3676 ret = btrfs_previous_item(chunk_root, path, 0,
3677 BTRFS_CHUNK_ITEM_KEY);
3679 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3684 leaf = path->nodes[0];
3685 slot = path->slots[0];
3686 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3688 if (found_key.objectid != key.objectid) {
3689 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3693 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3694 chunk_type = btrfs_chunk_type(leaf, chunk);
3697 spin_lock(&fs_info->balance_lock);
3698 bctl->stat.considered++;
3699 spin_unlock(&fs_info->balance_lock);
3702 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3704 btrfs_release_path(path);
3706 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3711 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3712 spin_lock(&fs_info->balance_lock);
3713 bctl->stat.expected++;
3714 spin_unlock(&fs_info->balance_lock);
3716 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3718 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3720 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3727 * Apply limit_min filter, no need to check if the LIMITS
3728 * filter is used, limit_min is 0 by default
3730 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3731 count_data < bctl->data.limit_min)
3732 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3733 count_meta < bctl->meta.limit_min)
3734 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3735 count_sys < bctl->sys.limit_min)) {
3736 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3740 if (!chunk_reserved) {
3742 * We may be relocating the only data chunk we have,
3743 * which could potentially end up with losing data's
3744 * raid profile, so lets allocate an empty one in
3747 ret = btrfs_may_alloc_data_chunk(fs_info,
3750 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3752 } else if (ret == 1) {
3757 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3758 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3759 if (ret == -ENOSPC) {
3761 } else if (ret == -ETXTBSY) {
3763 "skipping relocation of block group %llu due to active swapfile",
3769 spin_lock(&fs_info->balance_lock);
3770 bctl->stat.completed++;
3771 spin_unlock(&fs_info->balance_lock);
3774 if (found_key.offset == 0)
3776 key.offset = found_key.offset - 1;
3780 btrfs_release_path(path);
3785 btrfs_free_path(path);
3786 if (enospc_errors) {
3787 btrfs_info(fs_info, "%d enospc errors during balance",
3797 * alloc_profile_is_valid - see if a given profile is valid and reduced
3798 * @flags: profile to validate
3799 * @extended: if true @flags is treated as an extended profile
3801 static int alloc_profile_is_valid(u64 flags, int extended)
3803 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3804 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3806 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3808 /* 1) check that all other bits are zeroed */
3812 /* 2) see if profile is reduced */
3814 return !extended; /* "0" is valid for usual profiles */
3816 return has_single_bit_set(flags);
3819 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3821 /* cancel requested || normal exit path */
3822 return atomic_read(&fs_info->balance_cancel_req) ||
3823 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3824 atomic_read(&fs_info->balance_cancel_req) == 0);
3828 * Validate target profile against allowed profiles and return true if it's OK.
3829 * Otherwise print the error message and return false.
3831 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
3832 const struct btrfs_balance_args *bargs,
3833 u64 allowed, const char *type)
3835 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3838 /* Profile is valid and does not have bits outside of the allowed set */
3839 if (alloc_profile_is_valid(bargs->target, 1) &&
3840 (bargs->target & ~allowed) == 0)
3843 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
3844 type, btrfs_bg_type_to_raid_name(bargs->target));
3849 * Fill @buf with textual description of balance filter flags @bargs, up to
3850 * @size_buf including the terminating null. The output may be trimmed if it
3851 * does not fit into the provided buffer.
3853 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3857 u32 size_bp = size_buf;
3859 u64 flags = bargs->flags;
3860 char tmp_buf[128] = {'\0'};
3865 #define CHECK_APPEND_NOARG(a) \
3867 ret = snprintf(bp, size_bp, (a)); \
3868 if (ret < 0 || ret >= size_bp) \
3869 goto out_overflow; \
3874 #define CHECK_APPEND_1ARG(a, v1) \
3876 ret = snprintf(bp, size_bp, (a), (v1)); \
3877 if (ret < 0 || ret >= size_bp) \
3878 goto out_overflow; \
3883 #define CHECK_APPEND_2ARG(a, v1, v2) \
3885 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3886 if (ret < 0 || ret >= size_bp) \
3887 goto out_overflow; \
3892 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
3893 CHECK_APPEND_1ARG("convert=%s,",
3894 btrfs_bg_type_to_raid_name(bargs->target));
3896 if (flags & BTRFS_BALANCE_ARGS_SOFT)
3897 CHECK_APPEND_NOARG("soft,");
3899 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
3900 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
3902 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
3905 if (flags & BTRFS_BALANCE_ARGS_USAGE)
3906 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
3908 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
3909 CHECK_APPEND_2ARG("usage=%u..%u,",
3910 bargs->usage_min, bargs->usage_max);
3912 if (flags & BTRFS_BALANCE_ARGS_DEVID)
3913 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
3915 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
3916 CHECK_APPEND_2ARG("drange=%llu..%llu,",
3917 bargs->pstart, bargs->pend);
3919 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
3920 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
3921 bargs->vstart, bargs->vend);
3923 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
3924 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
3926 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
3927 CHECK_APPEND_2ARG("limit=%u..%u,",
3928 bargs->limit_min, bargs->limit_max);
3930 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
3931 CHECK_APPEND_2ARG("stripes=%u..%u,",
3932 bargs->stripes_min, bargs->stripes_max);
3934 #undef CHECK_APPEND_2ARG
3935 #undef CHECK_APPEND_1ARG
3936 #undef CHECK_APPEND_NOARG
3940 if (size_bp < size_buf)
3941 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
3946 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
3948 u32 size_buf = 1024;
3949 char tmp_buf[192] = {'\0'};
3952 u32 size_bp = size_buf;
3954 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3956 buf = kzalloc(size_buf, GFP_KERNEL);
3962 #define CHECK_APPEND_1ARG(a, v1) \
3964 ret = snprintf(bp, size_bp, (a), (v1)); \
3965 if (ret < 0 || ret >= size_bp) \
3966 goto out_overflow; \
3971 if (bctl->flags & BTRFS_BALANCE_FORCE)
3972 CHECK_APPEND_1ARG("%s", "-f ");
3974 if (bctl->flags & BTRFS_BALANCE_DATA) {
3975 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
3976 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
3979 if (bctl->flags & BTRFS_BALANCE_METADATA) {
3980 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
3981 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
3984 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
3985 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
3986 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
3989 #undef CHECK_APPEND_1ARG
3993 if (size_bp < size_buf)
3994 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
3995 btrfs_info(fs_info, "balance: %s %s",
3996 (bctl->flags & BTRFS_BALANCE_RESUME) ?
3997 "resume" : "start", buf);
4003 * Should be called with balance mutexe held
4005 int btrfs_balance(struct btrfs_fs_info *fs_info,
4006 struct btrfs_balance_control *bctl,
4007 struct btrfs_ioctl_balance_args *bargs)
4009 u64 meta_target, data_target;
4015 bool reducing_redundancy;
4018 if (btrfs_fs_closing(fs_info) ||
4019 atomic_read(&fs_info->balance_pause_req) ||
4020 btrfs_should_cancel_balance(fs_info)) {
4025 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4026 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4030 * In case of mixed groups both data and meta should be picked,
4031 * and identical options should be given for both of them.
4033 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4034 if (mixed && (bctl->flags & allowed)) {
4035 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4036 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4037 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4039 "balance: mixed groups data and metadata options must be the same");
4046 * rw_devices will not change at the moment, device add/delete/replace
4047 * are excluded by EXCL_OP
4049 num_devices = fs_info->fs_devices->rw_devices;
4052 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4053 * special bit for it, to make it easier to distinguish. Thus we need
4054 * to set it manually, or balance would refuse the profile.
4056 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4057 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4058 if (num_devices >= btrfs_raid_array[i].devs_min)
4059 allowed |= btrfs_raid_array[i].bg_flag;
4061 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4062 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4063 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
4069 * Allow to reduce metadata or system integrity only if force set for
4070 * profiles with redundancy (copies, parity)
4073 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4074 if (btrfs_raid_array[i].ncopies >= 2 ||
4075 btrfs_raid_array[i].tolerated_failures >= 1)
4076 allowed |= btrfs_raid_array[i].bg_flag;
4079 seq = read_seqbegin(&fs_info->profiles_lock);
4081 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4082 (fs_info->avail_system_alloc_bits & allowed) &&
4083 !(bctl->sys.target & allowed)) ||
4084 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4085 (fs_info->avail_metadata_alloc_bits & allowed) &&
4086 !(bctl->meta.target & allowed)))
4087 reducing_redundancy = true;
4089 reducing_redundancy = false;
4091 /* if we're not converting, the target field is uninitialized */
4092 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4093 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4094 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4095 bctl->data.target : fs_info->avail_data_alloc_bits;
4096 } while (read_seqretry(&fs_info->profiles_lock, seq));
4098 if (reducing_redundancy) {
4099 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4101 "balance: force reducing metadata redundancy");
4104 "balance: reduces metadata redundancy, use --force if you want this");
4110 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4111 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4113 "balance: metadata profile %s has lower redundancy than data profile %s",
4114 btrfs_bg_type_to_raid_name(meta_target),
4115 btrfs_bg_type_to_raid_name(data_target));
4118 if (fs_info->send_in_progress) {
4119 btrfs_warn_rl(fs_info,
4120 "cannot run balance while send operations are in progress (%d in progress)",
4121 fs_info->send_in_progress);
4126 ret = insert_balance_item(fs_info, bctl);
4127 if (ret && ret != -EEXIST)
4130 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4131 BUG_ON(ret == -EEXIST);
4132 BUG_ON(fs_info->balance_ctl);
4133 spin_lock(&fs_info->balance_lock);
4134 fs_info->balance_ctl = bctl;
4135 spin_unlock(&fs_info->balance_lock);
4137 BUG_ON(ret != -EEXIST);
4138 spin_lock(&fs_info->balance_lock);
4139 update_balance_args(bctl);
4140 spin_unlock(&fs_info->balance_lock);
4143 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4144 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4145 describe_balance_start_or_resume(fs_info);
4146 mutex_unlock(&fs_info->balance_mutex);
4148 ret = __btrfs_balance(fs_info);
4150 mutex_lock(&fs_info->balance_mutex);
4151 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4152 btrfs_info(fs_info, "balance: paused");
4154 * Balance can be canceled by:
4156 * - Regular cancel request
4157 * Then ret == -ECANCELED and balance_cancel_req > 0
4159 * - Fatal signal to "btrfs" process
4160 * Either the signal caught by wait_reserve_ticket() and callers
4161 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4163 * Either way, in this case balance_cancel_req = 0, and
4164 * ret == -EINTR or ret == -ECANCELED.
4166 * So here we only check the return value to catch canceled balance.
4168 else if (ret == -ECANCELED || ret == -EINTR)
4169 btrfs_info(fs_info, "balance: canceled");
4171 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4173 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4176 memset(bargs, 0, sizeof(*bargs));
4177 btrfs_update_ioctl_balance_args(fs_info, bargs);
4180 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4181 balance_need_close(fs_info)) {
4182 reset_balance_state(fs_info);
4183 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4186 wake_up(&fs_info->balance_wait_q);
4190 if (bctl->flags & BTRFS_BALANCE_RESUME)
4191 reset_balance_state(fs_info);
4194 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4199 static int balance_kthread(void *data)
4201 struct btrfs_fs_info *fs_info = data;
4204 mutex_lock(&fs_info->balance_mutex);
4205 if (fs_info->balance_ctl)
4206 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4207 mutex_unlock(&fs_info->balance_mutex);
4212 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4214 struct task_struct *tsk;
4216 mutex_lock(&fs_info->balance_mutex);
4217 if (!fs_info->balance_ctl) {
4218 mutex_unlock(&fs_info->balance_mutex);
4221 mutex_unlock(&fs_info->balance_mutex);
4223 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4224 btrfs_info(fs_info, "balance: resume skipped");
4229 * A ro->rw remount sequence should continue with the paused balance
4230 * regardless of who pauses it, system or the user as of now, so set
4233 spin_lock(&fs_info->balance_lock);
4234 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4235 spin_unlock(&fs_info->balance_lock);
4237 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4238 return PTR_ERR_OR_ZERO(tsk);
4241 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4243 struct btrfs_balance_control *bctl;
4244 struct btrfs_balance_item *item;
4245 struct btrfs_disk_balance_args disk_bargs;
4246 struct btrfs_path *path;
4247 struct extent_buffer *leaf;
4248 struct btrfs_key key;
4251 path = btrfs_alloc_path();
4255 key.objectid = BTRFS_BALANCE_OBJECTID;
4256 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4259 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4262 if (ret > 0) { /* ret = -ENOENT; */
4267 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4273 leaf = path->nodes[0];
4274 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4276 bctl->flags = btrfs_balance_flags(leaf, item);
4277 bctl->flags |= BTRFS_BALANCE_RESUME;
4279 btrfs_balance_data(leaf, item, &disk_bargs);
4280 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4281 btrfs_balance_meta(leaf, item, &disk_bargs);
4282 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4283 btrfs_balance_sys(leaf, item, &disk_bargs);
4284 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4287 * This should never happen, as the paused balance state is recovered
4288 * during mount without any chance of other exclusive ops to collide.
4290 * This gives the exclusive op status to balance and keeps in paused
4291 * state until user intervention (cancel or umount). If the ownership
4292 * cannot be assigned, show a message but do not fail. The balance
4293 * is in a paused state and must have fs_info::balance_ctl properly
4296 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4298 "balance: cannot set exclusive op status, resume manually");
4300 mutex_lock(&fs_info->balance_mutex);
4301 BUG_ON(fs_info->balance_ctl);
4302 spin_lock(&fs_info->balance_lock);
4303 fs_info->balance_ctl = bctl;
4304 spin_unlock(&fs_info->balance_lock);
4305 mutex_unlock(&fs_info->balance_mutex);
4307 btrfs_free_path(path);
4311 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4315 mutex_lock(&fs_info->balance_mutex);
4316 if (!fs_info->balance_ctl) {
4317 mutex_unlock(&fs_info->balance_mutex);
4321 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4322 atomic_inc(&fs_info->balance_pause_req);
4323 mutex_unlock(&fs_info->balance_mutex);
4325 wait_event(fs_info->balance_wait_q,
4326 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4328 mutex_lock(&fs_info->balance_mutex);
4329 /* we are good with balance_ctl ripped off from under us */
4330 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4331 atomic_dec(&fs_info->balance_pause_req);
4336 mutex_unlock(&fs_info->balance_mutex);
4340 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4342 mutex_lock(&fs_info->balance_mutex);
4343 if (!fs_info->balance_ctl) {
4344 mutex_unlock(&fs_info->balance_mutex);
4349 * A paused balance with the item stored on disk can be resumed at
4350 * mount time if the mount is read-write. Otherwise it's still paused
4351 * and we must not allow cancelling as it deletes the item.
4353 if (sb_rdonly(fs_info->sb)) {
4354 mutex_unlock(&fs_info->balance_mutex);
4358 atomic_inc(&fs_info->balance_cancel_req);
4360 * if we are running just wait and return, balance item is
4361 * deleted in btrfs_balance in this case
4363 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4364 mutex_unlock(&fs_info->balance_mutex);
4365 wait_event(fs_info->balance_wait_q,
4366 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4367 mutex_lock(&fs_info->balance_mutex);
4369 mutex_unlock(&fs_info->balance_mutex);
4371 * Lock released to allow other waiters to continue, we'll
4372 * reexamine the status again.
4374 mutex_lock(&fs_info->balance_mutex);
4376 if (fs_info->balance_ctl) {
4377 reset_balance_state(fs_info);
4378 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4379 btrfs_info(fs_info, "balance: canceled");
4383 BUG_ON(fs_info->balance_ctl ||
4384 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4385 atomic_dec(&fs_info->balance_cancel_req);
4386 mutex_unlock(&fs_info->balance_mutex);
4390 int btrfs_uuid_scan_kthread(void *data)
4392 struct btrfs_fs_info *fs_info = data;
4393 struct btrfs_root *root = fs_info->tree_root;
4394 struct btrfs_key key;
4395 struct btrfs_path *path = NULL;
4397 struct extent_buffer *eb;
4399 struct btrfs_root_item root_item;
4401 struct btrfs_trans_handle *trans = NULL;
4402 bool closing = false;
4404 path = btrfs_alloc_path();
4411 key.type = BTRFS_ROOT_ITEM_KEY;
4415 if (btrfs_fs_closing(fs_info)) {
4419 ret = btrfs_search_forward(root, &key, path,
4420 BTRFS_OLDEST_GENERATION);
4427 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4428 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4429 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4430 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4433 eb = path->nodes[0];
4434 slot = path->slots[0];
4435 item_size = btrfs_item_size_nr(eb, slot);
4436 if (item_size < sizeof(root_item))
4439 read_extent_buffer(eb, &root_item,
4440 btrfs_item_ptr_offset(eb, slot),
4441 (int)sizeof(root_item));
4442 if (btrfs_root_refs(&root_item) == 0)
4445 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4446 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4450 btrfs_release_path(path);
4452 * 1 - subvol uuid item
4453 * 1 - received_subvol uuid item
4455 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4456 if (IS_ERR(trans)) {
4457 ret = PTR_ERR(trans);
4465 btrfs_release_path(path);
4466 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4467 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4468 BTRFS_UUID_KEY_SUBVOL,
4471 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4477 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4478 ret = btrfs_uuid_tree_add(trans,
4479 root_item.received_uuid,
4480 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4483 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4490 btrfs_release_path(path);
4492 ret = btrfs_end_transaction(trans);
4498 if (key.offset < (u64)-1) {
4500 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4502 key.type = BTRFS_ROOT_ITEM_KEY;
4503 } else if (key.objectid < (u64)-1) {
4505 key.type = BTRFS_ROOT_ITEM_KEY;
4514 btrfs_free_path(path);
4515 if (trans && !IS_ERR(trans))
4516 btrfs_end_transaction(trans);
4518 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4520 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4521 up(&fs_info->uuid_tree_rescan_sem);
4525 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4527 struct btrfs_trans_handle *trans;
4528 struct btrfs_root *tree_root = fs_info->tree_root;
4529 struct btrfs_root *uuid_root;
4530 struct task_struct *task;
4537 trans = btrfs_start_transaction(tree_root, 2);
4539 return PTR_ERR(trans);
4541 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4542 if (IS_ERR(uuid_root)) {
4543 ret = PTR_ERR(uuid_root);
4544 btrfs_abort_transaction(trans, ret);
4545 btrfs_end_transaction(trans);
4549 fs_info->uuid_root = uuid_root;
4551 ret = btrfs_commit_transaction(trans);
4555 down(&fs_info->uuid_tree_rescan_sem);
4556 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4558 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4559 btrfs_warn(fs_info, "failed to start uuid_scan task");
4560 up(&fs_info->uuid_tree_rescan_sem);
4561 return PTR_ERR(task);
4568 * shrinking a device means finding all of the device extents past
4569 * the new size, and then following the back refs to the chunks.
4570 * The chunk relocation code actually frees the device extent
4572 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4574 struct btrfs_fs_info *fs_info = device->fs_info;
4575 struct btrfs_root *root = fs_info->dev_root;
4576 struct btrfs_trans_handle *trans;
4577 struct btrfs_dev_extent *dev_extent = NULL;
4578 struct btrfs_path *path;
4584 bool retried = false;
4585 struct extent_buffer *l;
4586 struct btrfs_key key;
4587 struct btrfs_super_block *super_copy = fs_info->super_copy;
4588 u64 old_total = btrfs_super_total_bytes(super_copy);
4589 u64 old_size = btrfs_device_get_total_bytes(device);
4593 new_size = round_down(new_size, fs_info->sectorsize);
4595 diff = round_down(old_size - new_size, fs_info->sectorsize);
4597 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4600 path = btrfs_alloc_path();
4604 path->reada = READA_BACK;
4606 trans = btrfs_start_transaction(root, 0);
4607 if (IS_ERR(trans)) {
4608 btrfs_free_path(path);
4609 return PTR_ERR(trans);
4612 mutex_lock(&fs_info->chunk_mutex);
4614 btrfs_device_set_total_bytes(device, new_size);
4615 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4616 device->fs_devices->total_rw_bytes -= diff;
4617 atomic64_sub(diff, &fs_info->free_chunk_space);
4621 * Once the device's size has been set to the new size, ensure all
4622 * in-memory chunks are synced to disk so that the loop below sees them
4623 * and relocates them accordingly.
4625 if (contains_pending_extent(device, &start, diff)) {
4626 mutex_unlock(&fs_info->chunk_mutex);
4627 ret = btrfs_commit_transaction(trans);
4631 mutex_unlock(&fs_info->chunk_mutex);
4632 btrfs_end_transaction(trans);
4636 key.objectid = device->devid;
4637 key.offset = (u64)-1;
4638 key.type = BTRFS_DEV_EXTENT_KEY;
4641 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4642 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4644 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4648 ret = btrfs_previous_item(root, path, 0, key.type);
4650 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4655 btrfs_release_path(path);
4660 slot = path->slots[0];
4661 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4663 if (key.objectid != device->devid) {
4664 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4665 btrfs_release_path(path);
4669 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4670 length = btrfs_dev_extent_length(l, dev_extent);
4672 if (key.offset + length <= new_size) {
4673 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4674 btrfs_release_path(path);
4678 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4679 btrfs_release_path(path);
4682 * We may be relocating the only data chunk we have,
4683 * which could potentially end up with losing data's
4684 * raid profile, so lets allocate an empty one in
4687 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4689 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4693 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4694 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4695 if (ret == -ENOSPC) {
4698 if (ret == -ETXTBSY) {
4700 "could not shrink block group %llu due to active swapfile",
4705 } while (key.offset-- > 0);
4707 if (failed && !retried) {
4711 } else if (failed && retried) {
4716 /* Shrinking succeeded, else we would be at "done". */
4717 trans = btrfs_start_transaction(root, 0);
4718 if (IS_ERR(trans)) {
4719 ret = PTR_ERR(trans);
4723 mutex_lock(&fs_info->chunk_mutex);
4724 /* Clear all state bits beyond the shrunk device size */
4725 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4728 btrfs_device_set_disk_total_bytes(device, new_size);
4729 if (list_empty(&device->post_commit_list))
4730 list_add_tail(&device->post_commit_list,
4731 &trans->transaction->dev_update_list);
4733 WARN_ON(diff > old_total);
4734 btrfs_set_super_total_bytes(super_copy,
4735 round_down(old_total - diff, fs_info->sectorsize));
4736 mutex_unlock(&fs_info->chunk_mutex);
4738 /* Now btrfs_update_device() will change the on-disk size. */
4739 ret = btrfs_update_device(trans, device);
4741 btrfs_abort_transaction(trans, ret);
4742 btrfs_end_transaction(trans);
4744 ret = btrfs_commit_transaction(trans);
4747 btrfs_free_path(path);
4749 mutex_lock(&fs_info->chunk_mutex);
4750 btrfs_device_set_total_bytes(device, old_size);
4751 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4752 device->fs_devices->total_rw_bytes += diff;
4753 atomic64_add(diff, &fs_info->free_chunk_space);
4754 mutex_unlock(&fs_info->chunk_mutex);
4759 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4760 struct btrfs_key *key,
4761 struct btrfs_chunk *chunk, int item_size)
4763 struct btrfs_super_block *super_copy = fs_info->super_copy;
4764 struct btrfs_disk_key disk_key;
4768 mutex_lock(&fs_info->chunk_mutex);
4769 array_size = btrfs_super_sys_array_size(super_copy);
4770 if (array_size + item_size + sizeof(disk_key)
4771 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4772 mutex_unlock(&fs_info->chunk_mutex);
4776 ptr = super_copy->sys_chunk_array + array_size;
4777 btrfs_cpu_key_to_disk(&disk_key, key);
4778 memcpy(ptr, &disk_key, sizeof(disk_key));
4779 ptr += sizeof(disk_key);
4780 memcpy(ptr, chunk, item_size);
4781 item_size += sizeof(disk_key);
4782 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4783 mutex_unlock(&fs_info->chunk_mutex);
4789 * sort the devices in descending order by max_avail, total_avail
4791 static int btrfs_cmp_device_info(const void *a, const void *b)
4793 const struct btrfs_device_info *di_a = a;
4794 const struct btrfs_device_info *di_b = b;
4796 if (di_a->max_avail > di_b->max_avail)
4798 if (di_a->max_avail < di_b->max_avail)
4800 if (di_a->total_avail > di_b->total_avail)
4802 if (di_a->total_avail < di_b->total_avail)
4807 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4809 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4812 btrfs_set_fs_incompat(info, RAID56);
4815 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
4817 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
4820 btrfs_set_fs_incompat(info, RAID1C34);
4824 * Structure used internally for __btrfs_alloc_chunk() function.
4825 * Wraps needed parameters.
4827 struct alloc_chunk_ctl {
4830 /* Total number of stripes to allocate */
4832 /* sub_stripes info for map */
4834 /* Stripes per device */
4836 /* Maximum number of devices to use */
4838 /* Minimum number of devices to use */
4840 /* ndevs has to be a multiple of this */
4842 /* Number of copies */
4844 /* Number of stripes worth of bytes to store parity information */
4846 u64 max_stripe_size;
4854 static void init_alloc_chunk_ctl_policy_regular(
4855 struct btrfs_fs_devices *fs_devices,
4856 struct alloc_chunk_ctl *ctl)
4858 u64 type = ctl->type;
4860 if (type & BTRFS_BLOCK_GROUP_DATA) {
4861 ctl->max_stripe_size = SZ_1G;
4862 ctl->max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4863 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4864 /* For larger filesystems, use larger metadata chunks */
4865 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4866 ctl->max_stripe_size = SZ_1G;
4868 ctl->max_stripe_size = SZ_256M;
4869 ctl->max_chunk_size = ctl->max_stripe_size;
4870 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4871 ctl->max_stripe_size = SZ_32M;
4872 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
4873 ctl->devs_max = min_t(int, ctl->devs_max,
4874 BTRFS_MAX_DEVS_SYS_CHUNK);
4879 /* We don't want a chunk larger than 10% of writable space */
4880 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4881 ctl->max_chunk_size);
4882 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
4885 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
4886 struct alloc_chunk_ctl *ctl)
4888 int index = btrfs_bg_flags_to_raid_index(ctl->type);
4890 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
4891 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
4892 ctl->devs_max = btrfs_raid_array[index].devs_max;
4894 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
4895 ctl->devs_min = btrfs_raid_array[index].devs_min;
4896 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
4897 ctl->ncopies = btrfs_raid_array[index].ncopies;
4898 ctl->nparity = btrfs_raid_array[index].nparity;
4901 switch (fs_devices->chunk_alloc_policy) {
4902 case BTRFS_CHUNK_ALLOC_REGULAR:
4903 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
4910 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
4911 struct alloc_chunk_ctl *ctl,
4912 struct btrfs_device_info *devices_info)
4914 struct btrfs_fs_info *info = fs_devices->fs_info;
4915 struct btrfs_device *device;
4917 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
4924 * in the first pass through the devices list, we gather information
4925 * about the available holes on each device.
4927 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4928 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4930 "BTRFS: read-only device in alloc_list\n");
4934 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4935 &device->dev_state) ||
4936 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4939 if (device->total_bytes > device->bytes_used)
4940 total_avail = device->total_bytes - device->bytes_used;
4944 /* If there is no space on this device, skip it. */
4945 if (total_avail < ctl->dev_extent_min)
4948 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
4950 if (ret && ret != -ENOSPC)
4954 max_avail = dev_extent_want;
4956 if (max_avail < ctl->dev_extent_min) {
4957 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4959 "%s: devid %llu has no free space, have=%llu want=%llu",
4960 __func__, device->devid, max_avail,
4961 ctl->dev_extent_min);
4965 if (ndevs == fs_devices->rw_devices) {
4966 WARN(1, "%s: found more than %llu devices\n",
4967 __func__, fs_devices->rw_devices);
4970 devices_info[ndevs].dev_offset = dev_offset;
4971 devices_info[ndevs].max_avail = max_avail;
4972 devices_info[ndevs].total_avail = total_avail;
4973 devices_info[ndevs].dev = device;
4979 * now sort the devices by hole size / available space
4981 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4982 btrfs_cmp_device_info, NULL);
4987 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
4988 struct btrfs_device_info *devices_info)
4990 /* Number of stripes that count for block group size */
4994 * The primary goal is to maximize the number of stripes, so use as
4995 * many devices as possible, even if the stripes are not maximum sized.
4997 * The DUP profile stores more than one stripe per device, the
4998 * max_avail is the total size so we have to adjust.
5000 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5002 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5004 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5005 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5008 * Use the number of data stripes to figure out how big this chunk is
5009 * really going to be in terms of logical address space, and compare
5010 * that answer with the max chunk size. If it's higher, we try to
5011 * reduce stripe_size.
5013 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5015 * Reduce stripe_size, round it up to a 16MB boundary again and
5016 * then use it, unless it ends up being even bigger than the
5017 * previous value we had already.
5019 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5020 data_stripes), SZ_16M),
5024 /* Align to BTRFS_STRIPE_LEN */
5025 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5026 ctl->chunk_size = ctl->stripe_size * data_stripes;
5031 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5032 struct alloc_chunk_ctl *ctl,
5033 struct btrfs_device_info *devices_info)
5035 struct btrfs_fs_info *info = fs_devices->fs_info;
5038 * Round down to number of usable stripes, devs_increment can be any
5039 * number so we can't use round_down() that requires power of 2, while
5040 * rounddown is safe.
5042 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5044 if (ctl->ndevs < ctl->devs_min) {
5045 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5047 "%s: not enough devices with free space: have=%d minimum required=%d",
5048 __func__, ctl->ndevs, ctl->devs_min);
5053 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5055 switch (fs_devices->chunk_alloc_policy) {
5056 case BTRFS_CHUNK_ALLOC_REGULAR:
5057 return decide_stripe_size_regular(ctl, devices_info);
5063 static int create_chunk(struct btrfs_trans_handle *trans,
5064 struct alloc_chunk_ctl *ctl,
5065 struct btrfs_device_info *devices_info)
5067 struct btrfs_fs_info *info = trans->fs_info;
5068 struct map_lookup *map = NULL;
5069 struct extent_map_tree *em_tree;
5070 struct extent_map *em;
5071 u64 start = ctl->start;
5072 u64 type = ctl->type;
5077 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5080 map->num_stripes = ctl->num_stripes;
5082 for (i = 0; i < ctl->ndevs; ++i) {
5083 for (j = 0; j < ctl->dev_stripes; ++j) {
5084 int s = i * ctl->dev_stripes + j;
5085 map->stripes[s].dev = devices_info[i].dev;
5086 map->stripes[s].physical = devices_info[i].dev_offset +
5087 j * ctl->stripe_size;
5090 map->stripe_len = BTRFS_STRIPE_LEN;
5091 map->io_align = BTRFS_STRIPE_LEN;
5092 map->io_width = BTRFS_STRIPE_LEN;
5094 map->sub_stripes = ctl->sub_stripes;
5096 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5098 em = alloc_extent_map();
5103 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5104 em->map_lookup = map;
5106 em->len = ctl->chunk_size;
5107 em->block_start = 0;
5108 em->block_len = em->len;
5109 em->orig_block_len = ctl->stripe_size;
5111 em_tree = &info->mapping_tree;
5112 write_lock(&em_tree->lock);
5113 ret = add_extent_mapping(em_tree, em, 0);
5115 write_unlock(&em_tree->lock);
5116 free_extent_map(em);
5119 write_unlock(&em_tree->lock);
5121 ret = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5123 goto error_del_extent;
5125 for (i = 0; i < map->num_stripes; i++) {
5126 struct btrfs_device *dev = map->stripes[i].dev;
5128 btrfs_device_set_bytes_used(dev,
5129 dev->bytes_used + ctl->stripe_size);
5130 if (list_empty(&dev->post_commit_list))
5131 list_add_tail(&dev->post_commit_list,
5132 &trans->transaction->dev_update_list);
5135 atomic64_sub(ctl->stripe_size * map->num_stripes,
5136 &info->free_chunk_space);
5138 free_extent_map(em);
5139 check_raid56_incompat_flag(info, type);
5140 check_raid1c34_incompat_flag(info, type);
5145 write_lock(&em_tree->lock);
5146 remove_extent_mapping(em_tree, em);
5147 write_unlock(&em_tree->lock);
5149 /* One for our allocation */
5150 free_extent_map(em);
5151 /* One for the tree reference */
5152 free_extent_map(em);
5157 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5159 struct btrfs_fs_info *info = trans->fs_info;
5160 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5161 struct btrfs_device_info *devices_info = NULL;
5162 struct alloc_chunk_ctl ctl;
5165 lockdep_assert_held(&info->chunk_mutex);
5167 if (!alloc_profile_is_valid(type, 0)) {
5172 if (list_empty(&fs_devices->alloc_list)) {
5173 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5174 btrfs_debug(info, "%s: no writable device", __func__);
5178 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5179 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5184 ctl.start = find_next_chunk(info);
5186 init_alloc_chunk_ctl(fs_devices, &ctl);
5188 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5193 ret = gather_device_info(fs_devices, &ctl, devices_info);
5197 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5201 ret = create_chunk(trans, &ctl, devices_info);
5204 kfree(devices_info);
5209 * Chunk allocation falls into two parts. The first part does work
5210 * that makes the new allocated chunk usable, but does not do any operation
5211 * that modifies the chunk tree. The second part does the work that
5212 * requires modifying the chunk tree. This division is important for the
5213 * bootstrap process of adding storage to a seed btrfs.
5215 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5216 u64 chunk_offset, u64 chunk_size)
5218 struct btrfs_fs_info *fs_info = trans->fs_info;
5219 struct btrfs_root *extent_root = fs_info->extent_root;
5220 struct btrfs_root *chunk_root = fs_info->chunk_root;
5221 struct btrfs_key key;
5222 struct btrfs_device *device;
5223 struct btrfs_chunk *chunk;
5224 struct btrfs_stripe *stripe;
5225 struct extent_map *em;
5226 struct map_lookup *map;
5233 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5237 map = em->map_lookup;
5238 item_size = btrfs_chunk_item_size(map->num_stripes);
5239 stripe_size = em->orig_block_len;
5241 chunk = kzalloc(item_size, GFP_NOFS);
5248 * Take the device list mutex to prevent races with the final phase of
5249 * a device replace operation that replaces the device object associated
5250 * with the map's stripes, because the device object's id can change
5251 * at any time during that final phase of the device replace operation
5252 * (dev-replace.c:btrfs_dev_replace_finishing()).
5254 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5255 for (i = 0; i < map->num_stripes; i++) {
5256 device = map->stripes[i].dev;
5257 dev_offset = map->stripes[i].physical;
5259 ret = btrfs_update_device(trans, device);
5262 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5263 dev_offset, stripe_size);
5268 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5272 stripe = &chunk->stripe;
5273 for (i = 0; i < map->num_stripes; i++) {
5274 device = map->stripes[i].dev;
5275 dev_offset = map->stripes[i].physical;
5277 btrfs_set_stack_stripe_devid(stripe, device->devid);
5278 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5279 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5282 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5284 btrfs_set_stack_chunk_length(chunk, chunk_size);
5285 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5286 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5287 btrfs_set_stack_chunk_type(chunk, map->type);
5288 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5289 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5290 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5291 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5292 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5294 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5295 key.type = BTRFS_CHUNK_ITEM_KEY;
5296 key.offset = chunk_offset;
5298 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5299 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5301 * TODO: Cleanup of inserted chunk root in case of
5304 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5309 free_extent_map(em);
5313 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5315 struct btrfs_fs_info *fs_info = trans->fs_info;
5319 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5320 ret = btrfs_alloc_chunk(trans, alloc_profile);
5324 alloc_profile = btrfs_system_alloc_profile(fs_info);
5325 ret = btrfs_alloc_chunk(trans, alloc_profile);
5329 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5331 const int index = btrfs_bg_flags_to_raid_index(map->type);
5333 return btrfs_raid_array[index].tolerated_failures;
5336 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5338 struct extent_map *em;
5339 struct map_lookup *map;
5344 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5348 map = em->map_lookup;
5349 for (i = 0; i < map->num_stripes; i++) {
5350 if (test_bit(BTRFS_DEV_STATE_MISSING,
5351 &map->stripes[i].dev->dev_state)) {
5355 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5356 &map->stripes[i].dev->dev_state)) {
5363 * If the number of missing devices is larger than max errors,
5364 * we can not write the data into that chunk successfully, so
5367 if (miss_ndevs > btrfs_chunk_max_errors(map))
5370 free_extent_map(em);
5374 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5376 struct extent_map *em;
5379 write_lock(&tree->lock);
5380 em = lookup_extent_mapping(tree, 0, (u64)-1);
5382 remove_extent_mapping(tree, em);
5383 write_unlock(&tree->lock);
5387 free_extent_map(em);
5388 /* once for the tree */
5389 free_extent_map(em);
5393 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5395 struct extent_map *em;
5396 struct map_lookup *map;
5399 em = btrfs_get_chunk_map(fs_info, logical, len);
5402 * We could return errors for these cases, but that could get
5403 * ugly and we'd probably do the same thing which is just not do
5404 * anything else and exit, so return 1 so the callers don't try
5405 * to use other copies.
5409 map = em->map_lookup;
5410 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5411 ret = map->num_stripes;
5412 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5413 ret = map->sub_stripes;
5414 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5416 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5418 * There could be two corrupted data stripes, we need
5419 * to loop retry in order to rebuild the correct data.
5421 * Fail a stripe at a time on every retry except the
5422 * stripe under reconstruction.
5424 ret = map->num_stripes;
5427 free_extent_map(em);
5429 down_read(&fs_info->dev_replace.rwsem);
5430 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5431 fs_info->dev_replace.tgtdev)
5433 up_read(&fs_info->dev_replace.rwsem);
5438 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5441 struct extent_map *em;
5442 struct map_lookup *map;
5443 unsigned long len = fs_info->sectorsize;
5445 em = btrfs_get_chunk_map(fs_info, logical, len);
5447 if (!WARN_ON(IS_ERR(em))) {
5448 map = em->map_lookup;
5449 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5450 len = map->stripe_len * nr_data_stripes(map);
5451 free_extent_map(em);
5456 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5458 struct extent_map *em;
5459 struct map_lookup *map;
5462 em = btrfs_get_chunk_map(fs_info, logical, len);
5464 if(!WARN_ON(IS_ERR(em))) {
5465 map = em->map_lookup;
5466 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5468 free_extent_map(em);
5473 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5474 struct map_lookup *map, int first,
5475 int dev_replace_is_ongoing)
5479 int preferred_mirror;
5481 struct btrfs_device *srcdev;
5484 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5486 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5487 num_stripes = map->sub_stripes;
5489 num_stripes = map->num_stripes;
5491 preferred_mirror = first + current->pid % num_stripes;
5493 if (dev_replace_is_ongoing &&
5494 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5495 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5496 srcdev = fs_info->dev_replace.srcdev;
5501 * try to avoid the drive that is the source drive for a
5502 * dev-replace procedure, only choose it if no other non-missing
5503 * mirror is available
5505 for (tolerance = 0; tolerance < 2; tolerance++) {
5506 if (map->stripes[preferred_mirror].dev->bdev &&
5507 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5508 return preferred_mirror;
5509 for (i = first; i < first + num_stripes; i++) {
5510 if (map->stripes[i].dev->bdev &&
5511 (tolerance || map->stripes[i].dev != srcdev))
5516 /* we couldn't find one that doesn't fail. Just return something
5517 * and the io error handling code will clean up eventually
5519 return preferred_mirror;
5522 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5523 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5530 for (i = 0; i < num_stripes - 1; i++) {
5531 /* Swap if parity is on a smaller index */
5532 if (bbio->raid_map[i] > bbio->raid_map[i + 1]) {
5533 swap(bbio->stripes[i], bbio->stripes[i + 1]);
5534 swap(bbio->raid_map[i], bbio->raid_map[i + 1]);
5541 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5543 struct btrfs_bio *bbio = kzalloc(
5544 /* the size of the btrfs_bio */
5545 sizeof(struct btrfs_bio) +
5546 /* plus the variable array for the stripes */
5547 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5548 /* plus the variable array for the tgt dev */
5549 sizeof(int) * (real_stripes) +
5551 * plus the raid_map, which includes both the tgt dev
5554 sizeof(u64) * (total_stripes),
5555 GFP_NOFS|__GFP_NOFAIL);
5557 atomic_set(&bbio->error, 0);
5558 refcount_set(&bbio->refs, 1);
5560 bbio->tgtdev_map = (int *)(bbio->stripes + total_stripes);
5561 bbio->raid_map = (u64 *)(bbio->tgtdev_map + real_stripes);
5566 void btrfs_get_bbio(struct btrfs_bio *bbio)
5568 WARN_ON(!refcount_read(&bbio->refs));
5569 refcount_inc(&bbio->refs);
5572 void btrfs_put_bbio(struct btrfs_bio *bbio)
5576 if (refcount_dec_and_test(&bbio->refs))
5580 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5582 * Please note that, discard won't be sent to target device of device
5585 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5586 u64 logical, u64 *length_ret,
5587 struct btrfs_bio **bbio_ret)
5589 struct extent_map *em;
5590 struct map_lookup *map;
5591 struct btrfs_bio *bbio;
5592 u64 length = *length_ret;
5596 u64 stripe_end_offset;
5603 u32 sub_stripes = 0;
5604 u64 stripes_per_dev = 0;
5605 u32 remaining_stripes = 0;
5606 u32 last_stripe = 0;
5610 /* discard always return a bbio */
5613 em = btrfs_get_chunk_map(fs_info, logical, length);
5617 map = em->map_lookup;
5618 /* we don't discard raid56 yet */
5619 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5624 offset = logical - em->start;
5625 length = min_t(u64, em->start + em->len - logical, length);
5626 *length_ret = length;
5628 stripe_len = map->stripe_len;
5630 * stripe_nr counts the total number of stripes we have to stride
5631 * to get to this block
5633 stripe_nr = div64_u64(offset, stripe_len);
5635 /* stripe_offset is the offset of this block in its stripe */
5636 stripe_offset = offset - stripe_nr * stripe_len;
5638 stripe_nr_end = round_up(offset + length, map->stripe_len);
5639 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5640 stripe_cnt = stripe_nr_end - stripe_nr;
5641 stripe_end_offset = stripe_nr_end * map->stripe_len -
5644 * after this, stripe_nr is the number of stripes on this
5645 * device we have to walk to find the data, and stripe_index is
5646 * the number of our device in the stripe array
5650 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5651 BTRFS_BLOCK_GROUP_RAID10)) {
5652 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5655 sub_stripes = map->sub_stripes;
5657 factor = map->num_stripes / sub_stripes;
5658 num_stripes = min_t(u64, map->num_stripes,
5659 sub_stripes * stripe_cnt);
5660 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5661 stripe_index *= sub_stripes;
5662 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5663 &remaining_stripes);
5664 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5665 last_stripe *= sub_stripes;
5666 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5667 BTRFS_BLOCK_GROUP_DUP)) {
5668 num_stripes = map->num_stripes;
5670 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5674 bbio = alloc_btrfs_bio(num_stripes, 0);
5680 for (i = 0; i < num_stripes; i++) {
5681 bbio->stripes[i].physical =
5682 map->stripes[stripe_index].physical +
5683 stripe_offset + stripe_nr * map->stripe_len;
5684 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5686 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5687 BTRFS_BLOCK_GROUP_RAID10)) {
5688 bbio->stripes[i].length = stripes_per_dev *
5691 if (i / sub_stripes < remaining_stripes)
5692 bbio->stripes[i].length +=
5696 * Special for the first stripe and
5699 * |-------|...|-------|
5703 if (i < sub_stripes)
5704 bbio->stripes[i].length -=
5707 if (stripe_index >= last_stripe &&
5708 stripe_index <= (last_stripe +
5710 bbio->stripes[i].length -=
5713 if (i == sub_stripes - 1)
5716 bbio->stripes[i].length = length;
5720 if (stripe_index == map->num_stripes) {
5727 bbio->map_type = map->type;
5728 bbio->num_stripes = num_stripes;
5730 free_extent_map(em);
5735 * In dev-replace case, for repair case (that's the only case where the mirror
5736 * is selected explicitly when calling btrfs_map_block), blocks left of the
5737 * left cursor can also be read from the target drive.
5739 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5741 * For READ, it also needs to be supported using the same mirror number.
5743 * If the requested block is not left of the left cursor, EIO is returned. This
5744 * can happen because btrfs_num_copies() returns one more in the dev-replace
5747 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5748 u64 logical, u64 length,
5749 u64 srcdev_devid, int *mirror_num,
5752 struct btrfs_bio *bbio = NULL;
5754 int index_srcdev = 0;
5756 u64 physical_of_found = 0;
5760 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5761 logical, &length, &bbio, 0, 0);
5763 ASSERT(bbio == NULL);
5767 num_stripes = bbio->num_stripes;
5768 if (*mirror_num > num_stripes) {
5770 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5771 * that means that the requested area is not left of the left
5774 btrfs_put_bbio(bbio);
5779 * process the rest of the function using the mirror_num of the source
5780 * drive. Therefore look it up first. At the end, patch the device
5781 * pointer to the one of the target drive.
5783 for (i = 0; i < num_stripes; i++) {
5784 if (bbio->stripes[i].dev->devid != srcdev_devid)
5788 * In case of DUP, in order to keep it simple, only add the
5789 * mirror with the lowest physical address
5792 physical_of_found <= bbio->stripes[i].physical)
5797 physical_of_found = bbio->stripes[i].physical;
5800 btrfs_put_bbio(bbio);
5806 *mirror_num = index_srcdev + 1;
5807 *physical = physical_of_found;
5811 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5812 struct btrfs_bio **bbio_ret,
5813 struct btrfs_dev_replace *dev_replace,
5814 int *num_stripes_ret, int *max_errors_ret)
5816 struct btrfs_bio *bbio = *bbio_ret;
5817 u64 srcdev_devid = dev_replace->srcdev->devid;
5818 int tgtdev_indexes = 0;
5819 int num_stripes = *num_stripes_ret;
5820 int max_errors = *max_errors_ret;
5823 if (op == BTRFS_MAP_WRITE) {
5824 int index_where_to_add;
5827 * duplicate the write operations while the dev replace
5828 * procedure is running. Since the copying of the old disk to
5829 * the new disk takes place at run time while the filesystem is
5830 * mounted writable, the regular write operations to the old
5831 * disk have to be duplicated to go to the new disk as well.
5833 * Note that device->missing is handled by the caller, and that
5834 * the write to the old disk is already set up in the stripes
5837 index_where_to_add = num_stripes;
5838 for (i = 0; i < num_stripes; i++) {
5839 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5840 /* write to new disk, too */
5841 struct btrfs_bio_stripe *new =
5842 bbio->stripes + index_where_to_add;
5843 struct btrfs_bio_stripe *old =
5846 new->physical = old->physical;
5847 new->length = old->length;
5848 new->dev = dev_replace->tgtdev;
5849 bbio->tgtdev_map[i] = index_where_to_add;
5850 index_where_to_add++;
5855 num_stripes = index_where_to_add;
5856 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5857 int index_srcdev = 0;
5859 u64 physical_of_found = 0;
5862 * During the dev-replace procedure, the target drive can also
5863 * be used to read data in case it is needed to repair a corrupt
5864 * block elsewhere. This is possible if the requested area is
5865 * left of the left cursor. In this area, the target drive is a
5866 * full copy of the source drive.
5868 for (i = 0; i < num_stripes; i++) {
5869 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5871 * In case of DUP, in order to keep it simple,
5872 * only add the mirror with the lowest physical
5876 physical_of_found <=
5877 bbio->stripes[i].physical)
5881 physical_of_found = bbio->stripes[i].physical;
5885 struct btrfs_bio_stripe *tgtdev_stripe =
5886 bbio->stripes + num_stripes;
5888 tgtdev_stripe->physical = physical_of_found;
5889 tgtdev_stripe->length =
5890 bbio->stripes[index_srcdev].length;
5891 tgtdev_stripe->dev = dev_replace->tgtdev;
5892 bbio->tgtdev_map[index_srcdev] = num_stripes;
5899 *num_stripes_ret = num_stripes;
5900 *max_errors_ret = max_errors;
5901 bbio->num_tgtdevs = tgtdev_indexes;
5905 static bool need_full_stripe(enum btrfs_map_op op)
5907 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5911 * btrfs_get_io_geometry - calculates the geomery of a particular (address, len)
5912 * tuple. This information is used to calculate how big a
5913 * particular bio can get before it straddles a stripe.
5915 * @fs_info - the filesystem
5916 * @logical - address that we want to figure out the geometry of
5917 * @len - the length of IO we are going to perform, starting at @logical
5918 * @op - type of operation - write or read
5919 * @io_geom - pointer used to return values
5921 * Returns < 0 in case a chunk for the given logical address cannot be found,
5922 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
5924 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5925 u64 logical, u64 len, struct btrfs_io_geometry *io_geom)
5927 struct extent_map *em;
5928 struct map_lookup *map;
5933 u64 raid56_full_stripe_start = (u64)-1;
5937 ASSERT(op != BTRFS_MAP_DISCARD);
5939 em = btrfs_get_chunk_map(fs_info, logical, len);
5943 map = em->map_lookup;
5944 /* Offset of this logical address in the chunk */
5945 offset = logical - em->start;
5946 /* Len of a stripe in a chunk */
5947 stripe_len = map->stripe_len;
5948 /* Stripe wher this block falls in */
5949 stripe_nr = div64_u64(offset, stripe_len);
5950 /* Offset of stripe in the chunk */
5951 stripe_offset = stripe_nr * stripe_len;
5952 if (offset < stripe_offset) {
5954 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
5955 stripe_offset, offset, em->start, logical, stripe_len);
5960 /* stripe_offset is the offset of this block in its stripe */
5961 stripe_offset = offset - stripe_offset;
5962 data_stripes = nr_data_stripes(map);
5964 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5965 u64 max_len = stripe_len - stripe_offset;
5968 * In case of raid56, we need to know the stripe aligned start
5970 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5971 unsigned long full_stripe_len = stripe_len * data_stripes;
5972 raid56_full_stripe_start = offset;
5975 * Allow a write of a full stripe, but make sure we
5976 * don't allow straddling of stripes
5978 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5980 raid56_full_stripe_start *= full_stripe_len;
5983 * For writes to RAID[56], allow a full stripeset across
5984 * all disks. For other RAID types and for RAID[56]
5985 * reads, just allow a single stripe (on a single disk).
5987 if (op == BTRFS_MAP_WRITE) {
5988 max_len = stripe_len * data_stripes -
5989 (offset - raid56_full_stripe_start);
5992 len = min_t(u64, em->len - offset, max_len);
5994 len = em->len - offset;
5998 io_geom->offset = offset;
5999 io_geom->stripe_len = stripe_len;
6000 io_geom->stripe_nr = stripe_nr;
6001 io_geom->stripe_offset = stripe_offset;
6002 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6006 free_extent_map(em);
6010 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6011 enum btrfs_map_op op,
6012 u64 logical, u64 *length,
6013 struct btrfs_bio **bbio_ret,
6014 int mirror_num, int need_raid_map)
6016 struct extent_map *em;
6017 struct map_lookup *map;
6027 int tgtdev_indexes = 0;
6028 struct btrfs_bio *bbio = NULL;
6029 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6030 int dev_replace_is_ongoing = 0;
6031 int num_alloc_stripes;
6032 int patch_the_first_stripe_for_dev_replace = 0;
6033 u64 physical_to_patch_in_first_stripe = 0;
6034 u64 raid56_full_stripe_start = (u64)-1;
6035 struct btrfs_io_geometry geom;
6038 ASSERT(op != BTRFS_MAP_DISCARD);
6040 ret = btrfs_get_io_geometry(fs_info, op, logical, *length, &geom);
6044 em = btrfs_get_chunk_map(fs_info, logical, *length);
6045 ASSERT(!IS_ERR(em));
6046 map = em->map_lookup;
6049 stripe_len = geom.stripe_len;
6050 stripe_nr = geom.stripe_nr;
6051 stripe_offset = geom.stripe_offset;
6052 raid56_full_stripe_start = geom.raid56_stripe_offset;
6053 data_stripes = nr_data_stripes(map);
6055 down_read(&dev_replace->rwsem);
6056 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6058 * Hold the semaphore for read during the whole operation, write is
6059 * requested at commit time but must wait.
6061 if (!dev_replace_is_ongoing)
6062 up_read(&dev_replace->rwsem);
6064 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6065 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6066 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6067 dev_replace->srcdev->devid,
6069 &physical_to_patch_in_first_stripe);
6073 patch_the_first_stripe_for_dev_replace = 1;
6074 } else if (mirror_num > map->num_stripes) {
6080 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6081 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6083 if (!need_full_stripe(op))
6085 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6086 if (need_full_stripe(op))
6087 num_stripes = map->num_stripes;
6088 else if (mirror_num)
6089 stripe_index = mirror_num - 1;
6091 stripe_index = find_live_mirror(fs_info, map, 0,
6092 dev_replace_is_ongoing);
6093 mirror_num = stripe_index + 1;
6096 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6097 if (need_full_stripe(op)) {
6098 num_stripes = map->num_stripes;
6099 } else if (mirror_num) {
6100 stripe_index = mirror_num - 1;
6105 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6106 u32 factor = map->num_stripes / map->sub_stripes;
6108 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6109 stripe_index *= map->sub_stripes;
6111 if (need_full_stripe(op))
6112 num_stripes = map->sub_stripes;
6113 else if (mirror_num)
6114 stripe_index += mirror_num - 1;
6116 int old_stripe_index = stripe_index;
6117 stripe_index = find_live_mirror(fs_info, map,
6119 dev_replace_is_ongoing);
6120 mirror_num = stripe_index - old_stripe_index + 1;
6123 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6124 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6125 /* push stripe_nr back to the start of the full stripe */
6126 stripe_nr = div64_u64(raid56_full_stripe_start,
6127 stripe_len * data_stripes);
6129 /* RAID[56] write or recovery. Return all stripes */
6130 num_stripes = map->num_stripes;
6131 max_errors = nr_parity_stripes(map);
6133 *length = map->stripe_len;
6138 * Mirror #0 or #1 means the original data block.
6139 * Mirror #2 is RAID5 parity block.
6140 * Mirror #3 is RAID6 Q block.
6142 stripe_nr = div_u64_rem(stripe_nr,
6143 data_stripes, &stripe_index);
6145 stripe_index = data_stripes + mirror_num - 2;
6147 /* We distribute the parity blocks across stripes */
6148 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6150 if (!need_full_stripe(op) && mirror_num <= 1)
6155 * after this, stripe_nr is the number of stripes on this
6156 * device we have to walk to find the data, and stripe_index is
6157 * the number of our device in the stripe array
6159 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6161 mirror_num = stripe_index + 1;
6163 if (stripe_index >= map->num_stripes) {
6165 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6166 stripe_index, map->num_stripes);
6171 num_alloc_stripes = num_stripes;
6172 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6173 if (op == BTRFS_MAP_WRITE)
6174 num_alloc_stripes <<= 1;
6175 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6176 num_alloc_stripes++;
6177 tgtdev_indexes = num_stripes;
6180 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6186 for (i = 0; i < num_stripes; i++) {
6187 bbio->stripes[i].physical = map->stripes[stripe_index].physical +
6188 stripe_offset + stripe_nr * map->stripe_len;
6189 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
6193 /* build raid_map */
6194 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6195 (need_full_stripe(op) || mirror_num > 1)) {
6199 /* Work out the disk rotation on this stripe-set */
6200 div_u64_rem(stripe_nr, num_stripes, &rot);
6202 /* Fill in the logical address of each stripe */
6203 tmp = stripe_nr * data_stripes;
6204 for (i = 0; i < data_stripes; i++)
6205 bbio->raid_map[(i+rot) % num_stripes] =
6206 em->start + (tmp + i) * map->stripe_len;
6208 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6209 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6210 bbio->raid_map[(i+rot+1) % num_stripes] =
6213 sort_parity_stripes(bbio, num_stripes);
6216 if (need_full_stripe(op))
6217 max_errors = btrfs_chunk_max_errors(map);
6219 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6220 need_full_stripe(op)) {
6221 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6226 bbio->map_type = map->type;
6227 bbio->num_stripes = num_stripes;
6228 bbio->max_errors = max_errors;
6229 bbio->mirror_num = mirror_num;
6232 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6233 * mirror_num == num_stripes + 1 && dev_replace target drive is
6234 * available as a mirror
6236 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6237 WARN_ON(num_stripes > 1);
6238 bbio->stripes[0].dev = dev_replace->tgtdev;
6239 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6240 bbio->mirror_num = map->num_stripes + 1;
6243 if (dev_replace_is_ongoing) {
6244 lockdep_assert_held(&dev_replace->rwsem);
6245 /* Unlock and let waiting writers proceed */
6246 up_read(&dev_replace->rwsem);
6248 free_extent_map(em);
6252 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6253 u64 logical, u64 *length,
6254 struct btrfs_bio **bbio_ret, int mirror_num)
6256 if (op == BTRFS_MAP_DISCARD)
6257 return __btrfs_map_block_for_discard(fs_info, logical,
6260 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6264 /* For Scrub/replace */
6265 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6266 u64 logical, u64 *length,
6267 struct btrfs_bio **bbio_ret)
6269 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6272 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6274 bio->bi_private = bbio->private;
6275 bio->bi_end_io = bbio->end_io;
6278 btrfs_put_bbio(bbio);
6281 static void btrfs_end_bio(struct bio *bio)
6283 struct btrfs_bio *bbio = bio->bi_private;
6284 int is_orig_bio = 0;
6286 if (bio->bi_status) {
6287 atomic_inc(&bbio->error);
6288 if (bio->bi_status == BLK_STS_IOERR ||
6289 bio->bi_status == BLK_STS_TARGET) {
6290 struct btrfs_device *dev = btrfs_io_bio(bio)->device;
6293 if (bio_op(bio) == REQ_OP_WRITE)
6294 btrfs_dev_stat_inc_and_print(dev,
6295 BTRFS_DEV_STAT_WRITE_ERRS);
6296 else if (!(bio->bi_opf & REQ_RAHEAD))
6297 btrfs_dev_stat_inc_and_print(dev,
6298 BTRFS_DEV_STAT_READ_ERRS);
6299 if (bio->bi_opf & REQ_PREFLUSH)
6300 btrfs_dev_stat_inc_and_print(dev,
6301 BTRFS_DEV_STAT_FLUSH_ERRS);
6305 if (bio == bbio->orig_bio)
6308 btrfs_bio_counter_dec(bbio->fs_info);
6310 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6313 bio = bbio->orig_bio;
6316 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6317 /* only send an error to the higher layers if it is
6318 * beyond the tolerance of the btrfs bio
6320 if (atomic_read(&bbio->error) > bbio->max_errors) {
6321 bio->bi_status = BLK_STS_IOERR;
6324 * this bio is actually up to date, we didn't
6325 * go over the max number of errors
6327 bio->bi_status = BLK_STS_OK;
6330 btrfs_end_bbio(bbio, bio);
6331 } else if (!is_orig_bio) {
6336 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6337 u64 physical, struct btrfs_device *dev)
6339 struct btrfs_fs_info *fs_info = bbio->fs_info;
6341 bio->bi_private = bbio;
6342 btrfs_io_bio(bio)->device = dev;
6343 bio->bi_end_io = btrfs_end_bio;
6344 bio->bi_iter.bi_sector = physical >> 9;
6345 btrfs_debug_in_rcu(fs_info,
6346 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6347 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6348 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6349 dev->devid, bio->bi_iter.bi_size);
6350 bio_set_dev(bio, dev->bdev);
6352 btrfs_bio_counter_inc_noblocked(fs_info);
6354 btrfsic_submit_bio(bio);
6357 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6359 atomic_inc(&bbio->error);
6360 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6361 /* Should be the original bio. */
6362 WARN_ON(bio != bbio->orig_bio);
6364 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6365 bio->bi_iter.bi_sector = logical >> 9;
6366 if (atomic_read(&bbio->error) > bbio->max_errors)
6367 bio->bi_status = BLK_STS_IOERR;
6369 bio->bi_status = BLK_STS_OK;
6370 btrfs_end_bbio(bbio, bio);
6374 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6377 struct btrfs_device *dev;
6378 struct bio *first_bio = bio;
6379 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6385 struct btrfs_bio *bbio = NULL;
6387 length = bio->bi_iter.bi_size;
6388 map_length = length;
6390 btrfs_bio_counter_inc_blocked(fs_info);
6391 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6392 &map_length, &bbio, mirror_num, 1);
6394 btrfs_bio_counter_dec(fs_info);
6395 return errno_to_blk_status(ret);
6398 total_devs = bbio->num_stripes;
6399 bbio->orig_bio = first_bio;
6400 bbio->private = first_bio->bi_private;
6401 bbio->end_io = first_bio->bi_end_io;
6402 bbio->fs_info = fs_info;
6403 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6405 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6406 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6407 /* In this case, map_length has been set to the length of
6408 a single stripe; not the whole write */
6409 if (bio_op(bio) == REQ_OP_WRITE) {
6410 ret = raid56_parity_write(fs_info, bio, bbio,
6413 ret = raid56_parity_recover(fs_info, bio, bbio,
6414 map_length, mirror_num, 1);
6417 btrfs_bio_counter_dec(fs_info);
6418 return errno_to_blk_status(ret);
6421 if (map_length < length) {
6423 "mapping failed logical %llu bio len %llu len %llu",
6424 logical, length, map_length);
6428 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6429 dev = bbio->stripes[dev_nr].dev;
6430 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6432 (bio_op(first_bio) == REQ_OP_WRITE &&
6433 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6434 bbio_error(bbio, first_bio, logical);
6438 if (dev_nr < total_devs - 1)
6439 bio = btrfs_bio_clone(first_bio);
6443 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical, dev);
6445 btrfs_bio_counter_dec(fs_info);
6450 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6453 * If devid and uuid are both specified, the match must be exact, otherwise
6454 * only devid is used.
6456 * If @seed is true, traverse through the seed devices.
6458 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6459 u64 devid, u8 *uuid, u8 *fsid,
6462 struct btrfs_device *device;
6464 while (fs_devices) {
6466 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6467 list_for_each_entry(device, &fs_devices->devices,
6469 if (device->devid == devid &&
6470 (!uuid || memcmp(device->uuid, uuid,
6471 BTRFS_UUID_SIZE) == 0))
6476 fs_devices = fs_devices->seed;
6483 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6484 u64 devid, u8 *dev_uuid)
6486 struct btrfs_device *device;
6488 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6492 list_add(&device->dev_list, &fs_devices->devices);
6493 device->fs_devices = fs_devices;
6494 fs_devices->num_devices++;
6496 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6497 fs_devices->missing_devices++;
6503 * btrfs_alloc_device - allocate struct btrfs_device
6504 * @fs_info: used only for generating a new devid, can be NULL if
6505 * devid is provided (i.e. @devid != NULL).
6506 * @devid: a pointer to devid for this device. If NULL a new devid
6508 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6511 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6512 * on error. Returned struct is not linked onto any lists and must be
6513 * destroyed with btrfs_free_device.
6515 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6519 struct btrfs_device *dev;
6522 if (WARN_ON(!devid && !fs_info))
6523 return ERR_PTR(-EINVAL);
6525 dev = __alloc_device();
6534 ret = find_next_devid(fs_info, &tmp);
6536 btrfs_free_device(dev);
6537 return ERR_PTR(ret);
6543 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6545 generate_random_uuid(dev->uuid);
6550 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6551 u64 devid, u8 *uuid, bool error)
6554 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6557 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6561 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6563 int index = btrfs_bg_flags_to_raid_index(type);
6564 int ncopies = btrfs_raid_array[index].ncopies;
6565 const int nparity = btrfs_raid_array[index].nparity;
6569 data_stripes = num_stripes - nparity;
6571 data_stripes = num_stripes / ncopies;
6573 return div_u64(chunk_len, data_stripes);
6576 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6577 struct btrfs_chunk *chunk)
6579 struct btrfs_fs_info *fs_info = leaf->fs_info;
6580 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6581 struct map_lookup *map;
6582 struct extent_map *em;
6586 u8 uuid[BTRFS_UUID_SIZE];
6591 logical = key->offset;
6592 length = btrfs_chunk_length(leaf, chunk);
6593 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6596 * Only need to verify chunk item if we're reading from sys chunk array,
6597 * as chunk item in tree block is already verified by tree-checker.
6599 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6600 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6605 read_lock(&map_tree->lock);
6606 em = lookup_extent_mapping(map_tree, logical, 1);
6607 read_unlock(&map_tree->lock);
6609 /* already mapped? */
6610 if (em && em->start <= logical && em->start + em->len > logical) {
6611 free_extent_map(em);
6614 free_extent_map(em);
6617 em = alloc_extent_map();
6620 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6622 free_extent_map(em);
6626 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6627 em->map_lookup = map;
6628 em->start = logical;
6631 em->block_start = 0;
6632 em->block_len = em->len;
6634 map->num_stripes = num_stripes;
6635 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6636 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6637 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6638 map->type = btrfs_chunk_type(leaf, chunk);
6639 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6640 map->verified_stripes = 0;
6641 em->orig_block_len = calc_stripe_length(map->type, em->len,
6643 for (i = 0; i < num_stripes; i++) {
6644 map->stripes[i].physical =
6645 btrfs_stripe_offset_nr(leaf, chunk, i);
6646 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6647 read_extent_buffer(leaf, uuid, (unsigned long)
6648 btrfs_stripe_dev_uuid_nr(chunk, i),
6650 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6651 devid, uuid, NULL, true);
6652 if (!map->stripes[i].dev &&
6653 !btrfs_test_opt(fs_info, DEGRADED)) {
6654 free_extent_map(em);
6655 btrfs_report_missing_device(fs_info, devid, uuid, true);
6658 if (!map->stripes[i].dev) {
6659 map->stripes[i].dev =
6660 add_missing_dev(fs_info->fs_devices, devid,
6662 if (IS_ERR(map->stripes[i].dev)) {
6663 free_extent_map(em);
6665 "failed to init missing dev %llu: %ld",
6666 devid, PTR_ERR(map->stripes[i].dev));
6667 return PTR_ERR(map->stripes[i].dev);
6669 btrfs_report_missing_device(fs_info, devid, uuid, false);
6671 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6672 &(map->stripes[i].dev->dev_state));
6676 write_lock(&map_tree->lock);
6677 ret = add_extent_mapping(map_tree, em, 0);
6678 write_unlock(&map_tree->lock);
6681 "failed to add chunk map, start=%llu len=%llu: %d",
6682 em->start, em->len, ret);
6684 free_extent_map(em);
6689 static void fill_device_from_item(struct extent_buffer *leaf,
6690 struct btrfs_dev_item *dev_item,
6691 struct btrfs_device *device)
6695 device->devid = btrfs_device_id(leaf, dev_item);
6696 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6697 device->total_bytes = device->disk_total_bytes;
6698 device->commit_total_bytes = device->disk_total_bytes;
6699 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6700 device->commit_bytes_used = device->bytes_used;
6701 device->type = btrfs_device_type(leaf, dev_item);
6702 device->io_align = btrfs_device_io_align(leaf, dev_item);
6703 device->io_width = btrfs_device_io_width(leaf, dev_item);
6704 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6705 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6706 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6708 ptr = btrfs_device_uuid(dev_item);
6709 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6712 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6715 struct btrfs_fs_devices *fs_devices;
6718 lockdep_assert_held(&uuid_mutex);
6721 fs_devices = fs_info->fs_devices->seed;
6722 while (fs_devices) {
6723 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6726 fs_devices = fs_devices->seed;
6729 fs_devices = find_fsid(fsid, NULL);
6731 if (!btrfs_test_opt(fs_info, DEGRADED))
6732 return ERR_PTR(-ENOENT);
6734 fs_devices = alloc_fs_devices(fsid, NULL);
6735 if (IS_ERR(fs_devices))
6738 fs_devices->seeding = true;
6739 fs_devices->opened = 1;
6743 fs_devices = clone_fs_devices(fs_devices);
6744 if (IS_ERR(fs_devices))
6747 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6749 free_fs_devices(fs_devices);
6750 fs_devices = ERR_PTR(ret);
6754 if (!fs_devices->seeding) {
6755 close_fs_devices(fs_devices);
6756 free_fs_devices(fs_devices);
6757 fs_devices = ERR_PTR(-EINVAL);
6761 fs_devices->seed = fs_info->fs_devices->seed;
6762 fs_info->fs_devices->seed = fs_devices;
6767 static int read_one_dev(struct extent_buffer *leaf,
6768 struct btrfs_dev_item *dev_item)
6770 struct btrfs_fs_info *fs_info = leaf->fs_info;
6771 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6772 struct btrfs_device *device;
6775 u8 fs_uuid[BTRFS_FSID_SIZE];
6776 u8 dev_uuid[BTRFS_UUID_SIZE];
6778 devid = btrfs_device_id(leaf, dev_item);
6779 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6781 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6784 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6785 fs_devices = open_seed_devices(fs_info, fs_uuid);
6786 if (IS_ERR(fs_devices))
6787 return PTR_ERR(fs_devices);
6790 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6793 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6794 btrfs_report_missing_device(fs_info, devid,
6799 device = add_missing_dev(fs_devices, devid, dev_uuid);
6800 if (IS_ERR(device)) {
6802 "failed to add missing dev %llu: %ld",
6803 devid, PTR_ERR(device));
6804 return PTR_ERR(device);
6806 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6808 if (!device->bdev) {
6809 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6810 btrfs_report_missing_device(fs_info,
6811 devid, dev_uuid, true);
6814 btrfs_report_missing_device(fs_info, devid,
6818 if (!device->bdev &&
6819 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6821 * this happens when a device that was properly setup
6822 * in the device info lists suddenly goes bad.
6823 * device->bdev is NULL, and so we have to set
6824 * device->missing to one here
6826 device->fs_devices->missing_devices++;
6827 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6830 /* Move the device to its own fs_devices */
6831 if (device->fs_devices != fs_devices) {
6832 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6833 &device->dev_state));
6835 list_move(&device->dev_list, &fs_devices->devices);
6836 device->fs_devices->num_devices--;
6837 fs_devices->num_devices++;
6839 device->fs_devices->missing_devices--;
6840 fs_devices->missing_devices++;
6842 device->fs_devices = fs_devices;
6846 if (device->fs_devices != fs_info->fs_devices) {
6847 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6848 if (device->generation !=
6849 btrfs_device_generation(leaf, dev_item))
6853 fill_device_from_item(leaf, dev_item, device);
6854 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6855 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6856 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6857 device->fs_devices->total_rw_bytes += device->total_bytes;
6858 atomic64_add(device->total_bytes - device->bytes_used,
6859 &fs_info->free_chunk_space);
6865 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6867 struct btrfs_root *root = fs_info->tree_root;
6868 struct btrfs_super_block *super_copy = fs_info->super_copy;
6869 struct extent_buffer *sb;
6870 struct btrfs_disk_key *disk_key;
6871 struct btrfs_chunk *chunk;
6873 unsigned long sb_array_offset;
6880 struct btrfs_key key;
6882 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6884 * This will create extent buffer of nodesize, superblock size is
6885 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6886 * overallocate but we can keep it as-is, only the first page is used.
6888 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6891 set_extent_buffer_uptodate(sb);
6892 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6894 * The sb extent buffer is artificial and just used to read the system array.
6895 * set_extent_buffer_uptodate() call does not properly mark all it's
6896 * pages up-to-date when the page is larger: extent does not cover the
6897 * whole page and consequently check_page_uptodate does not find all
6898 * the page's extents up-to-date (the hole beyond sb),
6899 * write_extent_buffer then triggers a WARN_ON.
6901 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6902 * but sb spans only this function. Add an explicit SetPageUptodate call
6903 * to silence the warning eg. on PowerPC 64.
6905 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6906 SetPageUptodate(sb->pages[0]);
6908 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6909 array_size = btrfs_super_sys_array_size(super_copy);
6911 array_ptr = super_copy->sys_chunk_array;
6912 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6915 while (cur_offset < array_size) {
6916 disk_key = (struct btrfs_disk_key *)array_ptr;
6917 len = sizeof(*disk_key);
6918 if (cur_offset + len > array_size)
6919 goto out_short_read;
6921 btrfs_disk_key_to_cpu(&key, disk_key);
6924 sb_array_offset += len;
6927 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
6929 "unexpected item type %u in sys_array at offset %u",
6930 (u32)key.type, cur_offset);
6935 chunk = (struct btrfs_chunk *)sb_array_offset;
6937 * At least one btrfs_chunk with one stripe must be present,
6938 * exact stripe count check comes afterwards
6940 len = btrfs_chunk_item_size(1);
6941 if (cur_offset + len > array_size)
6942 goto out_short_read;
6944 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6947 "invalid number of stripes %u in sys_array at offset %u",
6948 num_stripes, cur_offset);
6953 type = btrfs_chunk_type(sb, chunk);
6954 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6956 "invalid chunk type %llu in sys_array at offset %u",
6962 len = btrfs_chunk_item_size(num_stripes);
6963 if (cur_offset + len > array_size)
6964 goto out_short_read;
6966 ret = read_one_chunk(&key, sb, chunk);
6971 sb_array_offset += len;
6974 clear_extent_buffer_uptodate(sb);
6975 free_extent_buffer_stale(sb);
6979 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6981 clear_extent_buffer_uptodate(sb);
6982 free_extent_buffer_stale(sb);
6987 * Check if all chunks in the fs are OK for read-write degraded mount
6989 * If the @failing_dev is specified, it's accounted as missing.
6991 * Return true if all chunks meet the minimal RW mount requirements.
6992 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6994 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6995 struct btrfs_device *failing_dev)
6997 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6998 struct extent_map *em;
7002 read_lock(&map_tree->lock);
7003 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7004 read_unlock(&map_tree->lock);
7005 /* No chunk at all? Return false anyway */
7011 struct map_lookup *map;
7016 map = em->map_lookup;
7018 btrfs_get_num_tolerated_disk_barrier_failures(
7020 for (i = 0; i < map->num_stripes; i++) {
7021 struct btrfs_device *dev = map->stripes[i].dev;
7023 if (!dev || !dev->bdev ||
7024 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7025 dev->last_flush_error)
7027 else if (failing_dev && failing_dev == dev)
7030 if (missing > max_tolerated) {
7033 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7034 em->start, missing, max_tolerated);
7035 free_extent_map(em);
7039 next_start = extent_map_end(em);
7040 free_extent_map(em);
7042 read_lock(&map_tree->lock);
7043 em = lookup_extent_mapping(map_tree, next_start,
7044 (u64)(-1) - next_start);
7045 read_unlock(&map_tree->lock);
7051 static void readahead_tree_node_children(struct extent_buffer *node)
7054 const int nr_items = btrfs_header_nritems(node);
7056 for (i = 0; i < nr_items; i++) {
7059 start = btrfs_node_blockptr(node, i);
7060 readahead_tree_block(node->fs_info, start);
7064 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7066 struct btrfs_root *root = fs_info->chunk_root;
7067 struct btrfs_path *path;
7068 struct extent_buffer *leaf;
7069 struct btrfs_key key;
7070 struct btrfs_key found_key;
7074 u64 last_ra_node = 0;
7076 path = btrfs_alloc_path();
7081 * uuid_mutex is needed only if we are mounting a sprout FS
7082 * otherwise we don't need it.
7084 mutex_lock(&uuid_mutex);
7087 * It is possible for mount and umount to race in such a way that
7088 * we execute this code path, but open_fs_devices failed to clear
7089 * total_rw_bytes. We certainly want it cleared before reading the
7090 * device items, so clear it here.
7092 fs_info->fs_devices->total_rw_bytes = 0;
7095 * Read all device items, and then all the chunk items. All
7096 * device items are found before any chunk item (their object id
7097 * is smaller than the lowest possible object id for a chunk
7098 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7100 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7103 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7107 struct extent_buffer *node;
7109 leaf = path->nodes[0];
7110 slot = path->slots[0];
7111 if (slot >= btrfs_header_nritems(leaf)) {
7112 ret = btrfs_next_leaf(root, path);
7120 * The nodes on level 1 are not locked but we don't need to do
7121 * that during mount time as nothing else can access the tree
7123 node = path->nodes[1];
7125 if (last_ra_node != node->start) {
7126 readahead_tree_node_children(node);
7127 last_ra_node = node->start;
7130 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7131 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7132 struct btrfs_dev_item *dev_item;
7133 dev_item = btrfs_item_ptr(leaf, slot,
7134 struct btrfs_dev_item);
7135 ret = read_one_dev(leaf, dev_item);
7139 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7140 struct btrfs_chunk *chunk;
7141 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7142 mutex_lock(&fs_info->chunk_mutex);
7143 ret = read_one_chunk(&found_key, leaf, chunk);
7144 mutex_unlock(&fs_info->chunk_mutex);
7152 * After loading chunk tree, we've got all device information,
7153 * do another round of validation checks.
7155 if (total_dev != fs_info->fs_devices->total_devices) {
7157 "super_num_devices %llu mismatch with num_devices %llu found here",
7158 btrfs_super_num_devices(fs_info->super_copy),
7163 if (btrfs_super_total_bytes(fs_info->super_copy) <
7164 fs_info->fs_devices->total_rw_bytes) {
7166 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7167 btrfs_super_total_bytes(fs_info->super_copy),
7168 fs_info->fs_devices->total_rw_bytes);
7174 mutex_unlock(&uuid_mutex);
7176 btrfs_free_path(path);
7180 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7182 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7183 struct btrfs_device *device;
7185 while (fs_devices) {
7186 mutex_lock(&fs_devices->device_list_mutex);
7187 list_for_each_entry(device, &fs_devices->devices, dev_list)
7188 device->fs_info = fs_info;
7189 mutex_unlock(&fs_devices->device_list_mutex);
7191 fs_devices = fs_devices->seed;
7195 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7196 const struct btrfs_dev_stats_item *ptr,
7201 read_extent_buffer(eb, &val,
7202 offsetof(struct btrfs_dev_stats_item, values) +
7203 ((unsigned long)ptr) + (index * sizeof(u64)),
7208 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7209 struct btrfs_dev_stats_item *ptr,
7212 write_extent_buffer(eb, &val,
7213 offsetof(struct btrfs_dev_stats_item, values) +
7214 ((unsigned long)ptr) + (index * sizeof(u64)),
7218 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7220 struct btrfs_key key;
7221 struct btrfs_root *dev_root = fs_info->dev_root;
7222 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7223 struct extent_buffer *eb;
7226 struct btrfs_device *device;
7227 struct btrfs_path *path = NULL;
7230 path = btrfs_alloc_path();
7234 mutex_lock(&fs_devices->device_list_mutex);
7235 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7237 struct btrfs_dev_stats_item *ptr;
7239 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7240 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7241 key.offset = device->devid;
7242 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7244 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7245 btrfs_dev_stat_set(device, i, 0);
7246 device->dev_stats_valid = 1;
7247 btrfs_release_path(path);
7250 slot = path->slots[0];
7251 eb = path->nodes[0];
7252 item_size = btrfs_item_size_nr(eb, slot);
7254 ptr = btrfs_item_ptr(eb, slot,
7255 struct btrfs_dev_stats_item);
7257 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7258 if (item_size >= (1 + i) * sizeof(__le64))
7259 btrfs_dev_stat_set(device, i,
7260 btrfs_dev_stats_value(eb, ptr, i));
7262 btrfs_dev_stat_set(device, i, 0);
7265 device->dev_stats_valid = 1;
7266 btrfs_dev_stat_print_on_load(device);
7267 btrfs_release_path(path);
7269 mutex_unlock(&fs_devices->device_list_mutex);
7271 btrfs_free_path(path);
7272 return ret < 0 ? ret : 0;
7275 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7276 struct btrfs_device *device)
7278 struct btrfs_fs_info *fs_info = trans->fs_info;
7279 struct btrfs_root *dev_root = fs_info->dev_root;
7280 struct btrfs_path *path;
7281 struct btrfs_key key;
7282 struct extent_buffer *eb;
7283 struct btrfs_dev_stats_item *ptr;
7287 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7288 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7289 key.offset = device->devid;
7291 path = btrfs_alloc_path();
7294 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7296 btrfs_warn_in_rcu(fs_info,
7297 "error %d while searching for dev_stats item for device %s",
7298 ret, rcu_str_deref(device->name));
7303 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7304 /* need to delete old one and insert a new one */
7305 ret = btrfs_del_item(trans, dev_root, path);
7307 btrfs_warn_in_rcu(fs_info,
7308 "delete too small dev_stats item for device %s failed %d",
7309 rcu_str_deref(device->name), ret);
7316 /* need to insert a new item */
7317 btrfs_release_path(path);
7318 ret = btrfs_insert_empty_item(trans, dev_root, path,
7319 &key, sizeof(*ptr));
7321 btrfs_warn_in_rcu(fs_info,
7322 "insert dev_stats item for device %s failed %d",
7323 rcu_str_deref(device->name), ret);
7328 eb = path->nodes[0];
7329 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7330 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7331 btrfs_set_dev_stats_value(eb, ptr, i,
7332 btrfs_dev_stat_read(device, i));
7333 btrfs_mark_buffer_dirty(eb);
7336 btrfs_free_path(path);
7341 * called from commit_transaction. Writes all changed device stats to disk.
7343 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7345 struct btrfs_fs_info *fs_info = trans->fs_info;
7346 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7347 struct btrfs_device *device;
7351 mutex_lock(&fs_devices->device_list_mutex);
7352 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7353 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7354 if (!device->dev_stats_valid || stats_cnt == 0)
7359 * There is a LOAD-LOAD control dependency between the value of
7360 * dev_stats_ccnt and updating the on-disk values which requires
7361 * reading the in-memory counters. Such control dependencies
7362 * require explicit read memory barriers.
7364 * This memory barriers pairs with smp_mb__before_atomic in
7365 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7366 * barrier implied by atomic_xchg in
7367 * btrfs_dev_stats_read_and_reset
7371 ret = update_dev_stat_item(trans, device);
7373 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7375 mutex_unlock(&fs_devices->device_list_mutex);
7380 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7382 btrfs_dev_stat_inc(dev, index);
7383 btrfs_dev_stat_print_on_error(dev);
7386 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7388 if (!dev->dev_stats_valid)
7390 btrfs_err_rl_in_rcu(dev->fs_info,
7391 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7392 rcu_str_deref(dev->name),
7393 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7394 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7395 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7396 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7397 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7400 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7404 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7405 if (btrfs_dev_stat_read(dev, i) != 0)
7407 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7408 return; /* all values == 0, suppress message */
7410 btrfs_info_in_rcu(dev->fs_info,
7411 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7412 rcu_str_deref(dev->name),
7413 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7414 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7415 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7416 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7417 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7420 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7421 struct btrfs_ioctl_get_dev_stats *stats)
7423 struct btrfs_device *dev;
7424 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7427 mutex_lock(&fs_devices->device_list_mutex);
7428 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7430 mutex_unlock(&fs_devices->device_list_mutex);
7433 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7435 } else if (!dev->dev_stats_valid) {
7436 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7438 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7439 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7440 if (stats->nr_items > i)
7442 btrfs_dev_stat_read_and_reset(dev, i);
7444 btrfs_dev_stat_set(dev, i, 0);
7446 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7447 current->comm, task_pid_nr(current));
7449 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7450 if (stats->nr_items > i)
7451 stats->values[i] = btrfs_dev_stat_read(dev, i);
7453 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7454 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7459 * Update the size and bytes used for each device where it changed. This is
7460 * delayed since we would otherwise get errors while writing out the
7463 * Must be invoked during transaction commit.
7465 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7467 struct btrfs_device *curr, *next;
7469 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7471 if (list_empty(&trans->dev_update_list))
7475 * We don't need the device_list_mutex here. This list is owned by the
7476 * transaction and the transaction must complete before the device is
7479 mutex_lock(&trans->fs_info->chunk_mutex);
7480 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7482 list_del_init(&curr->post_commit_list);
7483 curr->commit_total_bytes = curr->disk_total_bytes;
7484 curr->commit_bytes_used = curr->bytes_used;
7486 mutex_unlock(&trans->fs_info->chunk_mutex);
7489 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7491 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7492 while (fs_devices) {
7493 fs_devices->fs_info = fs_info;
7494 fs_devices = fs_devices->seed;
7498 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7500 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7501 while (fs_devices) {
7502 fs_devices->fs_info = NULL;
7503 fs_devices = fs_devices->seed;
7508 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7510 int btrfs_bg_type_to_factor(u64 flags)
7512 const int index = btrfs_bg_flags_to_raid_index(flags);
7514 return btrfs_raid_array[index].ncopies;
7519 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7520 u64 chunk_offset, u64 devid,
7521 u64 physical_offset, u64 physical_len)
7523 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7524 struct extent_map *em;
7525 struct map_lookup *map;
7526 struct btrfs_device *dev;
7532 read_lock(&em_tree->lock);
7533 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7534 read_unlock(&em_tree->lock);
7538 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7539 physical_offset, devid);
7544 map = em->map_lookup;
7545 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7546 if (physical_len != stripe_len) {
7548 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7549 physical_offset, devid, em->start, physical_len,
7555 for (i = 0; i < map->num_stripes; i++) {
7556 if (map->stripes[i].dev->devid == devid &&
7557 map->stripes[i].physical == physical_offset) {
7559 if (map->verified_stripes >= map->num_stripes) {
7561 "too many dev extents for chunk %llu found",
7566 map->verified_stripes++;
7572 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7573 physical_offset, devid);
7577 /* Make sure no dev extent is beyond device bondary */
7578 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7580 btrfs_err(fs_info, "failed to find devid %llu", devid);
7585 /* It's possible this device is a dummy for seed device */
7586 if (dev->disk_total_bytes == 0) {
7587 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7590 btrfs_err(fs_info, "failed to find seed devid %llu",
7597 if (physical_offset + physical_len > dev->disk_total_bytes) {
7599 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7600 devid, physical_offset, physical_len,
7601 dev->disk_total_bytes);
7606 free_extent_map(em);
7610 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7612 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7613 struct extent_map *em;
7614 struct rb_node *node;
7617 read_lock(&em_tree->lock);
7618 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7619 em = rb_entry(node, struct extent_map, rb_node);
7620 if (em->map_lookup->num_stripes !=
7621 em->map_lookup->verified_stripes) {
7623 "chunk %llu has missing dev extent, have %d expect %d",
7624 em->start, em->map_lookup->verified_stripes,
7625 em->map_lookup->num_stripes);
7631 read_unlock(&em_tree->lock);
7636 * Ensure that all dev extents are mapped to correct chunk, otherwise
7637 * later chunk allocation/free would cause unexpected behavior.
7639 * NOTE: This will iterate through the whole device tree, which should be of
7640 * the same size level as the chunk tree. This slightly increases mount time.
7642 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7644 struct btrfs_path *path;
7645 struct btrfs_root *root = fs_info->dev_root;
7646 struct btrfs_key key;
7648 u64 prev_dev_ext_end = 0;
7652 key.type = BTRFS_DEV_EXTENT_KEY;
7655 path = btrfs_alloc_path();
7659 path->reada = READA_FORWARD;
7660 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7664 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7665 ret = btrfs_next_item(root, path);
7668 /* No dev extents at all? Not good */
7675 struct extent_buffer *leaf = path->nodes[0];
7676 struct btrfs_dev_extent *dext;
7677 int slot = path->slots[0];
7679 u64 physical_offset;
7683 btrfs_item_key_to_cpu(leaf, &key, slot);
7684 if (key.type != BTRFS_DEV_EXTENT_KEY)
7686 devid = key.objectid;
7687 physical_offset = key.offset;
7689 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7690 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7691 physical_len = btrfs_dev_extent_length(leaf, dext);
7693 /* Check if this dev extent overlaps with the previous one */
7694 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7696 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7697 devid, physical_offset, prev_dev_ext_end);
7702 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7703 physical_offset, physical_len);
7707 prev_dev_ext_end = physical_offset + physical_len;
7709 ret = btrfs_next_item(root, path);
7718 /* Ensure all chunks have corresponding dev extents */
7719 ret = verify_chunk_dev_extent_mapping(fs_info);
7721 btrfs_free_path(path);
7726 * Check whether the given block group or device is pinned by any inode being
7727 * used as a swapfile.
7729 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7731 struct btrfs_swapfile_pin *sp;
7732 struct rb_node *node;
7734 spin_lock(&fs_info->swapfile_pins_lock);
7735 node = fs_info->swapfile_pins.rb_node;
7737 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7739 node = node->rb_left;
7740 else if (ptr > sp->ptr)
7741 node = node->rb_right;
7745 spin_unlock(&fs_info->swapfile_pins_lock);
7746 return node != NULL;