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 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4466 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4467 BTRFS_UUID_KEY_SUBVOL,
4470 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4476 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4477 ret = btrfs_uuid_tree_add(trans,
4478 root_item.received_uuid,
4479 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4482 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4490 ret = btrfs_end_transaction(trans);
4496 btrfs_release_path(path);
4497 if (key.offset < (u64)-1) {
4499 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4501 key.type = BTRFS_ROOT_ITEM_KEY;
4502 } else if (key.objectid < (u64)-1) {
4504 key.type = BTRFS_ROOT_ITEM_KEY;
4513 btrfs_free_path(path);
4514 if (trans && !IS_ERR(trans))
4515 btrfs_end_transaction(trans);
4517 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4519 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4520 up(&fs_info->uuid_tree_rescan_sem);
4524 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4526 struct btrfs_trans_handle *trans;
4527 struct btrfs_root *tree_root = fs_info->tree_root;
4528 struct btrfs_root *uuid_root;
4529 struct task_struct *task;
4536 trans = btrfs_start_transaction(tree_root, 2);
4538 return PTR_ERR(trans);
4540 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4541 if (IS_ERR(uuid_root)) {
4542 ret = PTR_ERR(uuid_root);
4543 btrfs_abort_transaction(trans, ret);
4544 btrfs_end_transaction(trans);
4548 fs_info->uuid_root = uuid_root;
4550 ret = btrfs_commit_transaction(trans);
4554 down(&fs_info->uuid_tree_rescan_sem);
4555 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4557 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4558 btrfs_warn(fs_info, "failed to start uuid_scan task");
4559 up(&fs_info->uuid_tree_rescan_sem);
4560 return PTR_ERR(task);
4567 * shrinking a device means finding all of the device extents past
4568 * the new size, and then following the back refs to the chunks.
4569 * The chunk relocation code actually frees the device extent
4571 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4573 struct btrfs_fs_info *fs_info = device->fs_info;
4574 struct btrfs_root *root = fs_info->dev_root;
4575 struct btrfs_trans_handle *trans;
4576 struct btrfs_dev_extent *dev_extent = NULL;
4577 struct btrfs_path *path;
4583 bool retried = false;
4584 struct extent_buffer *l;
4585 struct btrfs_key key;
4586 struct btrfs_super_block *super_copy = fs_info->super_copy;
4587 u64 old_total = btrfs_super_total_bytes(super_copy);
4588 u64 old_size = btrfs_device_get_total_bytes(device);
4592 new_size = round_down(new_size, fs_info->sectorsize);
4594 diff = round_down(old_size - new_size, fs_info->sectorsize);
4596 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4599 path = btrfs_alloc_path();
4603 path->reada = READA_BACK;
4605 trans = btrfs_start_transaction(root, 0);
4606 if (IS_ERR(trans)) {
4607 btrfs_free_path(path);
4608 return PTR_ERR(trans);
4611 mutex_lock(&fs_info->chunk_mutex);
4613 btrfs_device_set_total_bytes(device, new_size);
4614 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4615 device->fs_devices->total_rw_bytes -= diff;
4616 atomic64_sub(diff, &fs_info->free_chunk_space);
4620 * Once the device's size has been set to the new size, ensure all
4621 * in-memory chunks are synced to disk so that the loop below sees them
4622 * and relocates them accordingly.
4624 if (contains_pending_extent(device, &start, diff)) {
4625 mutex_unlock(&fs_info->chunk_mutex);
4626 ret = btrfs_commit_transaction(trans);
4630 mutex_unlock(&fs_info->chunk_mutex);
4631 btrfs_end_transaction(trans);
4635 key.objectid = device->devid;
4636 key.offset = (u64)-1;
4637 key.type = BTRFS_DEV_EXTENT_KEY;
4640 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4641 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4643 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4647 ret = btrfs_previous_item(root, path, 0, key.type);
4649 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4654 btrfs_release_path(path);
4659 slot = path->slots[0];
4660 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4662 if (key.objectid != device->devid) {
4663 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4664 btrfs_release_path(path);
4668 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4669 length = btrfs_dev_extent_length(l, dev_extent);
4671 if (key.offset + length <= new_size) {
4672 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4673 btrfs_release_path(path);
4677 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4678 btrfs_release_path(path);
4681 * We may be relocating the only data chunk we have,
4682 * which could potentially end up with losing data's
4683 * raid profile, so lets allocate an empty one in
4686 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4688 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4692 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4693 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4694 if (ret == -ENOSPC) {
4697 if (ret == -ETXTBSY) {
4699 "could not shrink block group %llu due to active swapfile",
4704 } while (key.offset-- > 0);
4706 if (failed && !retried) {
4710 } else if (failed && retried) {
4715 /* Shrinking succeeded, else we would be at "done". */
4716 trans = btrfs_start_transaction(root, 0);
4717 if (IS_ERR(trans)) {
4718 ret = PTR_ERR(trans);
4722 mutex_lock(&fs_info->chunk_mutex);
4723 /* Clear all state bits beyond the shrunk device size */
4724 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4727 btrfs_device_set_disk_total_bytes(device, new_size);
4728 if (list_empty(&device->post_commit_list))
4729 list_add_tail(&device->post_commit_list,
4730 &trans->transaction->dev_update_list);
4732 WARN_ON(diff > old_total);
4733 btrfs_set_super_total_bytes(super_copy,
4734 round_down(old_total - diff, fs_info->sectorsize));
4735 mutex_unlock(&fs_info->chunk_mutex);
4737 /* Now btrfs_update_device() will change the on-disk size. */
4738 ret = btrfs_update_device(trans, device);
4740 btrfs_abort_transaction(trans, ret);
4741 btrfs_end_transaction(trans);
4743 ret = btrfs_commit_transaction(trans);
4746 btrfs_free_path(path);
4748 mutex_lock(&fs_info->chunk_mutex);
4749 btrfs_device_set_total_bytes(device, old_size);
4750 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4751 device->fs_devices->total_rw_bytes += diff;
4752 atomic64_add(diff, &fs_info->free_chunk_space);
4753 mutex_unlock(&fs_info->chunk_mutex);
4758 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4759 struct btrfs_key *key,
4760 struct btrfs_chunk *chunk, int item_size)
4762 struct btrfs_super_block *super_copy = fs_info->super_copy;
4763 struct btrfs_disk_key disk_key;
4767 mutex_lock(&fs_info->chunk_mutex);
4768 array_size = btrfs_super_sys_array_size(super_copy);
4769 if (array_size + item_size + sizeof(disk_key)
4770 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4771 mutex_unlock(&fs_info->chunk_mutex);
4775 ptr = super_copy->sys_chunk_array + array_size;
4776 btrfs_cpu_key_to_disk(&disk_key, key);
4777 memcpy(ptr, &disk_key, sizeof(disk_key));
4778 ptr += sizeof(disk_key);
4779 memcpy(ptr, chunk, item_size);
4780 item_size += sizeof(disk_key);
4781 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4782 mutex_unlock(&fs_info->chunk_mutex);
4788 * sort the devices in descending order by max_avail, total_avail
4790 static int btrfs_cmp_device_info(const void *a, const void *b)
4792 const struct btrfs_device_info *di_a = a;
4793 const struct btrfs_device_info *di_b = b;
4795 if (di_a->max_avail > di_b->max_avail)
4797 if (di_a->max_avail < di_b->max_avail)
4799 if (di_a->total_avail > di_b->total_avail)
4801 if (di_a->total_avail < di_b->total_avail)
4806 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4808 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4811 btrfs_set_fs_incompat(info, RAID56);
4814 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
4816 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
4819 btrfs_set_fs_incompat(info, RAID1C34);
4823 * Structure used internally for __btrfs_alloc_chunk() function.
4824 * Wraps needed parameters.
4826 struct alloc_chunk_ctl {
4829 /* Total number of stripes to allocate */
4831 /* sub_stripes info for map */
4833 /* Stripes per device */
4835 /* Maximum number of devices to use */
4837 /* Minimum number of devices to use */
4839 /* ndevs has to be a multiple of this */
4841 /* Number of copies */
4843 /* Number of stripes worth of bytes to store parity information */
4845 u64 max_stripe_size;
4853 static void init_alloc_chunk_ctl_policy_regular(
4854 struct btrfs_fs_devices *fs_devices,
4855 struct alloc_chunk_ctl *ctl)
4857 u64 type = ctl->type;
4859 if (type & BTRFS_BLOCK_GROUP_DATA) {
4860 ctl->max_stripe_size = SZ_1G;
4861 ctl->max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4862 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4863 /* For larger filesystems, use larger metadata chunks */
4864 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4865 ctl->max_stripe_size = SZ_1G;
4867 ctl->max_stripe_size = SZ_256M;
4868 ctl->max_chunk_size = ctl->max_stripe_size;
4869 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4870 ctl->max_stripe_size = SZ_32M;
4871 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
4872 ctl->devs_max = min_t(int, ctl->devs_max,
4873 BTRFS_MAX_DEVS_SYS_CHUNK);
4878 /* We don't want a chunk larger than 10% of writable space */
4879 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4880 ctl->max_chunk_size);
4881 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
4884 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
4885 struct alloc_chunk_ctl *ctl)
4887 int index = btrfs_bg_flags_to_raid_index(ctl->type);
4889 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
4890 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
4891 ctl->devs_max = btrfs_raid_array[index].devs_max;
4893 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
4894 ctl->devs_min = btrfs_raid_array[index].devs_min;
4895 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
4896 ctl->ncopies = btrfs_raid_array[index].ncopies;
4897 ctl->nparity = btrfs_raid_array[index].nparity;
4900 switch (fs_devices->chunk_alloc_policy) {
4901 case BTRFS_CHUNK_ALLOC_REGULAR:
4902 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
4909 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
4910 struct alloc_chunk_ctl *ctl,
4911 struct btrfs_device_info *devices_info)
4913 struct btrfs_fs_info *info = fs_devices->fs_info;
4914 struct btrfs_device *device;
4916 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
4923 * in the first pass through the devices list, we gather information
4924 * about the available holes on each device.
4926 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4927 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4929 "BTRFS: read-only device in alloc_list\n");
4933 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4934 &device->dev_state) ||
4935 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4938 if (device->total_bytes > device->bytes_used)
4939 total_avail = device->total_bytes - device->bytes_used;
4943 /* If there is no space on this device, skip it. */
4944 if (total_avail < ctl->dev_extent_min)
4947 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
4949 if (ret && ret != -ENOSPC)
4953 max_avail = dev_extent_want;
4955 if (max_avail < ctl->dev_extent_min) {
4956 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4958 "%s: devid %llu has no free space, have=%llu want=%llu",
4959 __func__, device->devid, max_avail,
4960 ctl->dev_extent_min);
4964 if (ndevs == fs_devices->rw_devices) {
4965 WARN(1, "%s: found more than %llu devices\n",
4966 __func__, fs_devices->rw_devices);
4969 devices_info[ndevs].dev_offset = dev_offset;
4970 devices_info[ndevs].max_avail = max_avail;
4971 devices_info[ndevs].total_avail = total_avail;
4972 devices_info[ndevs].dev = device;
4978 * now sort the devices by hole size / available space
4980 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4981 btrfs_cmp_device_info, NULL);
4986 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
4987 struct btrfs_device_info *devices_info)
4989 /* Number of stripes that count for block group size */
4993 * The primary goal is to maximize the number of stripes, so use as
4994 * many devices as possible, even if the stripes are not maximum sized.
4996 * The DUP profile stores more than one stripe per device, the
4997 * max_avail is the total size so we have to adjust.
4999 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5001 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5003 /* This will have to be fixed for RAID1 and RAID10 over more drives */
5004 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5007 * Use the number of data stripes to figure out how big this chunk is
5008 * really going to be in terms of logical address space, and compare
5009 * that answer with the max chunk size. If it's higher, we try to
5010 * reduce stripe_size.
5012 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5014 * Reduce stripe_size, round it up to a 16MB boundary again and
5015 * then use it, unless it ends up being even bigger than the
5016 * previous value we had already.
5018 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5019 data_stripes), SZ_16M),
5023 /* Align to BTRFS_STRIPE_LEN */
5024 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5025 ctl->chunk_size = ctl->stripe_size * data_stripes;
5030 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5031 struct alloc_chunk_ctl *ctl,
5032 struct btrfs_device_info *devices_info)
5034 struct btrfs_fs_info *info = fs_devices->fs_info;
5037 * Round down to number of usable stripes, devs_increment can be any
5038 * number so we can't use round_down() that requires power of 2, while
5039 * rounddown is safe.
5041 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5043 if (ctl->ndevs < ctl->devs_min) {
5044 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5046 "%s: not enough devices with free space: have=%d minimum required=%d",
5047 __func__, ctl->ndevs, ctl->devs_min);
5052 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5054 switch (fs_devices->chunk_alloc_policy) {
5055 case BTRFS_CHUNK_ALLOC_REGULAR:
5056 return decide_stripe_size_regular(ctl, devices_info);
5062 static int create_chunk(struct btrfs_trans_handle *trans,
5063 struct alloc_chunk_ctl *ctl,
5064 struct btrfs_device_info *devices_info)
5066 struct btrfs_fs_info *info = trans->fs_info;
5067 struct map_lookup *map = NULL;
5068 struct extent_map_tree *em_tree;
5069 struct extent_map *em;
5070 u64 start = ctl->start;
5071 u64 type = ctl->type;
5076 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5079 map->num_stripes = ctl->num_stripes;
5081 for (i = 0; i < ctl->ndevs; ++i) {
5082 for (j = 0; j < ctl->dev_stripes; ++j) {
5083 int s = i * ctl->dev_stripes + j;
5084 map->stripes[s].dev = devices_info[i].dev;
5085 map->stripes[s].physical = devices_info[i].dev_offset +
5086 j * ctl->stripe_size;
5089 map->stripe_len = BTRFS_STRIPE_LEN;
5090 map->io_align = BTRFS_STRIPE_LEN;
5091 map->io_width = BTRFS_STRIPE_LEN;
5093 map->sub_stripes = ctl->sub_stripes;
5095 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5097 em = alloc_extent_map();
5102 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5103 em->map_lookup = map;
5105 em->len = ctl->chunk_size;
5106 em->block_start = 0;
5107 em->block_len = em->len;
5108 em->orig_block_len = ctl->stripe_size;
5110 em_tree = &info->mapping_tree;
5111 write_lock(&em_tree->lock);
5112 ret = add_extent_mapping(em_tree, em, 0);
5114 write_unlock(&em_tree->lock);
5115 free_extent_map(em);
5118 write_unlock(&em_tree->lock);
5120 ret = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5122 goto error_del_extent;
5124 for (i = 0; i < map->num_stripes; i++) {
5125 struct btrfs_device *dev = map->stripes[i].dev;
5127 btrfs_device_set_bytes_used(dev,
5128 dev->bytes_used + ctl->stripe_size);
5129 if (list_empty(&dev->post_commit_list))
5130 list_add_tail(&dev->post_commit_list,
5131 &trans->transaction->dev_update_list);
5134 atomic64_sub(ctl->stripe_size * map->num_stripes,
5135 &info->free_chunk_space);
5137 free_extent_map(em);
5138 check_raid56_incompat_flag(info, type);
5139 check_raid1c34_incompat_flag(info, type);
5144 write_lock(&em_tree->lock);
5145 remove_extent_mapping(em_tree, em);
5146 write_unlock(&em_tree->lock);
5148 /* One for our allocation */
5149 free_extent_map(em);
5150 /* One for the tree reference */
5151 free_extent_map(em);
5156 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5158 struct btrfs_fs_info *info = trans->fs_info;
5159 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5160 struct btrfs_device_info *devices_info = NULL;
5161 struct alloc_chunk_ctl ctl;
5164 lockdep_assert_held(&info->chunk_mutex);
5166 if (!alloc_profile_is_valid(type, 0)) {
5171 if (list_empty(&fs_devices->alloc_list)) {
5172 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5173 btrfs_debug(info, "%s: no writable device", __func__);
5177 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5178 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5183 ctl.start = find_next_chunk(info);
5185 init_alloc_chunk_ctl(fs_devices, &ctl);
5187 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5192 ret = gather_device_info(fs_devices, &ctl, devices_info);
5196 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5200 ret = create_chunk(trans, &ctl, devices_info);
5203 kfree(devices_info);
5208 * Chunk allocation falls into two parts. The first part does work
5209 * that makes the new allocated chunk usable, but does not do any operation
5210 * that modifies the chunk tree. The second part does the work that
5211 * requires modifying the chunk tree. This division is important for the
5212 * bootstrap process of adding storage to a seed btrfs.
5214 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5215 u64 chunk_offset, u64 chunk_size)
5217 struct btrfs_fs_info *fs_info = trans->fs_info;
5218 struct btrfs_root *extent_root = fs_info->extent_root;
5219 struct btrfs_root *chunk_root = fs_info->chunk_root;
5220 struct btrfs_key key;
5221 struct btrfs_device *device;
5222 struct btrfs_chunk *chunk;
5223 struct btrfs_stripe *stripe;
5224 struct extent_map *em;
5225 struct map_lookup *map;
5232 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5236 map = em->map_lookup;
5237 item_size = btrfs_chunk_item_size(map->num_stripes);
5238 stripe_size = em->orig_block_len;
5240 chunk = kzalloc(item_size, GFP_NOFS);
5247 * Take the device list mutex to prevent races with the final phase of
5248 * a device replace operation that replaces the device object associated
5249 * with the map's stripes, because the device object's id can change
5250 * at any time during that final phase of the device replace operation
5251 * (dev-replace.c:btrfs_dev_replace_finishing()).
5253 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5254 for (i = 0; i < map->num_stripes; i++) {
5255 device = map->stripes[i].dev;
5256 dev_offset = map->stripes[i].physical;
5258 ret = btrfs_update_device(trans, device);
5261 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5262 dev_offset, stripe_size);
5267 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5271 stripe = &chunk->stripe;
5272 for (i = 0; i < map->num_stripes; i++) {
5273 device = map->stripes[i].dev;
5274 dev_offset = map->stripes[i].physical;
5276 btrfs_set_stack_stripe_devid(stripe, device->devid);
5277 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5278 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5281 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5283 btrfs_set_stack_chunk_length(chunk, chunk_size);
5284 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5285 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5286 btrfs_set_stack_chunk_type(chunk, map->type);
5287 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5288 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5289 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5290 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5291 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5293 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5294 key.type = BTRFS_CHUNK_ITEM_KEY;
5295 key.offset = chunk_offset;
5297 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5298 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5300 * TODO: Cleanup of inserted chunk root in case of
5303 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5308 free_extent_map(em);
5312 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5314 struct btrfs_fs_info *fs_info = trans->fs_info;
5318 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5319 ret = btrfs_alloc_chunk(trans, alloc_profile);
5323 alloc_profile = btrfs_system_alloc_profile(fs_info);
5324 ret = btrfs_alloc_chunk(trans, alloc_profile);
5328 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5330 const int index = btrfs_bg_flags_to_raid_index(map->type);
5332 return btrfs_raid_array[index].tolerated_failures;
5335 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5337 struct extent_map *em;
5338 struct map_lookup *map;
5343 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5347 map = em->map_lookup;
5348 for (i = 0; i < map->num_stripes; i++) {
5349 if (test_bit(BTRFS_DEV_STATE_MISSING,
5350 &map->stripes[i].dev->dev_state)) {
5354 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5355 &map->stripes[i].dev->dev_state)) {
5362 * If the number of missing devices is larger than max errors,
5363 * we can not write the data into that chunk successfully, so
5366 if (miss_ndevs > btrfs_chunk_max_errors(map))
5369 free_extent_map(em);
5373 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5375 struct extent_map *em;
5378 write_lock(&tree->lock);
5379 em = lookup_extent_mapping(tree, 0, (u64)-1);
5381 remove_extent_mapping(tree, em);
5382 write_unlock(&tree->lock);
5386 free_extent_map(em);
5387 /* once for the tree */
5388 free_extent_map(em);
5392 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5394 struct extent_map *em;
5395 struct map_lookup *map;
5398 em = btrfs_get_chunk_map(fs_info, logical, len);
5401 * We could return errors for these cases, but that could get
5402 * ugly and we'd probably do the same thing which is just not do
5403 * anything else and exit, so return 1 so the callers don't try
5404 * to use other copies.
5408 map = em->map_lookup;
5409 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5410 ret = map->num_stripes;
5411 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5412 ret = map->sub_stripes;
5413 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5415 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5417 * There could be two corrupted data stripes, we need
5418 * to loop retry in order to rebuild the correct data.
5420 * Fail a stripe at a time on every retry except the
5421 * stripe under reconstruction.
5423 ret = map->num_stripes;
5426 free_extent_map(em);
5428 down_read(&fs_info->dev_replace.rwsem);
5429 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5430 fs_info->dev_replace.tgtdev)
5432 up_read(&fs_info->dev_replace.rwsem);
5437 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5440 struct extent_map *em;
5441 struct map_lookup *map;
5442 unsigned long len = fs_info->sectorsize;
5444 em = btrfs_get_chunk_map(fs_info, logical, len);
5446 if (!WARN_ON(IS_ERR(em))) {
5447 map = em->map_lookup;
5448 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5449 len = map->stripe_len * nr_data_stripes(map);
5450 free_extent_map(em);
5455 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5457 struct extent_map *em;
5458 struct map_lookup *map;
5461 em = btrfs_get_chunk_map(fs_info, logical, len);
5463 if(!WARN_ON(IS_ERR(em))) {
5464 map = em->map_lookup;
5465 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5467 free_extent_map(em);
5472 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5473 struct map_lookup *map, int first,
5474 int dev_replace_is_ongoing)
5478 int preferred_mirror;
5480 struct btrfs_device *srcdev;
5483 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5485 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5486 num_stripes = map->sub_stripes;
5488 num_stripes = map->num_stripes;
5490 preferred_mirror = first + current->pid % num_stripes;
5492 if (dev_replace_is_ongoing &&
5493 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5494 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5495 srcdev = fs_info->dev_replace.srcdev;
5500 * try to avoid the drive that is the source drive for a
5501 * dev-replace procedure, only choose it if no other non-missing
5502 * mirror is available
5504 for (tolerance = 0; tolerance < 2; tolerance++) {
5505 if (map->stripes[preferred_mirror].dev->bdev &&
5506 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5507 return preferred_mirror;
5508 for (i = first; i < first + num_stripes; i++) {
5509 if (map->stripes[i].dev->bdev &&
5510 (tolerance || map->stripes[i].dev != srcdev))
5515 /* we couldn't find one that doesn't fail. Just return something
5516 * and the io error handling code will clean up eventually
5518 return preferred_mirror;
5521 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5522 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5529 for (i = 0; i < num_stripes - 1; i++) {
5530 /* Swap if parity is on a smaller index */
5531 if (bbio->raid_map[i] > bbio->raid_map[i + 1]) {
5532 swap(bbio->stripes[i], bbio->stripes[i + 1]);
5533 swap(bbio->raid_map[i], bbio->raid_map[i + 1]);
5540 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5542 struct btrfs_bio *bbio = kzalloc(
5543 /* the size of the btrfs_bio */
5544 sizeof(struct btrfs_bio) +
5545 /* plus the variable array for the stripes */
5546 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5547 /* plus the variable array for the tgt dev */
5548 sizeof(int) * (real_stripes) +
5550 * plus the raid_map, which includes both the tgt dev
5553 sizeof(u64) * (total_stripes),
5554 GFP_NOFS|__GFP_NOFAIL);
5556 atomic_set(&bbio->error, 0);
5557 refcount_set(&bbio->refs, 1);
5559 bbio->tgtdev_map = (int *)(bbio->stripes + total_stripes);
5560 bbio->raid_map = (u64 *)(bbio->tgtdev_map + real_stripes);
5565 void btrfs_get_bbio(struct btrfs_bio *bbio)
5567 WARN_ON(!refcount_read(&bbio->refs));
5568 refcount_inc(&bbio->refs);
5571 void btrfs_put_bbio(struct btrfs_bio *bbio)
5575 if (refcount_dec_and_test(&bbio->refs))
5579 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5581 * Please note that, discard won't be sent to target device of device
5584 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5585 u64 logical, u64 *length_ret,
5586 struct btrfs_bio **bbio_ret)
5588 struct extent_map *em;
5589 struct map_lookup *map;
5590 struct btrfs_bio *bbio;
5591 u64 length = *length_ret;
5595 u64 stripe_end_offset;
5602 u32 sub_stripes = 0;
5603 u64 stripes_per_dev = 0;
5604 u32 remaining_stripes = 0;
5605 u32 last_stripe = 0;
5609 /* discard always return a bbio */
5612 em = btrfs_get_chunk_map(fs_info, logical, length);
5616 map = em->map_lookup;
5617 /* we don't discard raid56 yet */
5618 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5623 offset = logical - em->start;
5624 length = min_t(u64, em->start + em->len - logical, length);
5625 *length_ret = length;
5627 stripe_len = map->stripe_len;
5629 * stripe_nr counts the total number of stripes we have to stride
5630 * to get to this block
5632 stripe_nr = div64_u64(offset, stripe_len);
5634 /* stripe_offset is the offset of this block in its stripe */
5635 stripe_offset = offset - stripe_nr * stripe_len;
5637 stripe_nr_end = round_up(offset + length, map->stripe_len);
5638 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5639 stripe_cnt = stripe_nr_end - stripe_nr;
5640 stripe_end_offset = stripe_nr_end * map->stripe_len -
5643 * after this, stripe_nr is the number of stripes on this
5644 * device we have to walk to find the data, and stripe_index is
5645 * the number of our device in the stripe array
5649 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5650 BTRFS_BLOCK_GROUP_RAID10)) {
5651 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5654 sub_stripes = map->sub_stripes;
5656 factor = map->num_stripes / sub_stripes;
5657 num_stripes = min_t(u64, map->num_stripes,
5658 sub_stripes * stripe_cnt);
5659 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5660 stripe_index *= sub_stripes;
5661 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5662 &remaining_stripes);
5663 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5664 last_stripe *= sub_stripes;
5665 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5666 BTRFS_BLOCK_GROUP_DUP)) {
5667 num_stripes = map->num_stripes;
5669 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5673 bbio = alloc_btrfs_bio(num_stripes, 0);
5679 for (i = 0; i < num_stripes; i++) {
5680 bbio->stripes[i].physical =
5681 map->stripes[stripe_index].physical +
5682 stripe_offset + stripe_nr * map->stripe_len;
5683 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5685 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5686 BTRFS_BLOCK_GROUP_RAID10)) {
5687 bbio->stripes[i].length = stripes_per_dev *
5690 if (i / sub_stripes < remaining_stripes)
5691 bbio->stripes[i].length +=
5695 * Special for the first stripe and
5698 * |-------|...|-------|
5702 if (i < sub_stripes)
5703 bbio->stripes[i].length -=
5706 if (stripe_index >= last_stripe &&
5707 stripe_index <= (last_stripe +
5709 bbio->stripes[i].length -=
5712 if (i == sub_stripes - 1)
5715 bbio->stripes[i].length = length;
5719 if (stripe_index == map->num_stripes) {
5726 bbio->map_type = map->type;
5727 bbio->num_stripes = num_stripes;
5729 free_extent_map(em);
5734 * In dev-replace case, for repair case (that's the only case where the mirror
5735 * is selected explicitly when calling btrfs_map_block), blocks left of the
5736 * left cursor can also be read from the target drive.
5738 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5740 * For READ, it also needs to be supported using the same mirror number.
5742 * If the requested block is not left of the left cursor, EIO is returned. This
5743 * can happen because btrfs_num_copies() returns one more in the dev-replace
5746 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5747 u64 logical, u64 length,
5748 u64 srcdev_devid, int *mirror_num,
5751 struct btrfs_bio *bbio = NULL;
5753 int index_srcdev = 0;
5755 u64 physical_of_found = 0;
5759 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5760 logical, &length, &bbio, 0, 0);
5762 ASSERT(bbio == NULL);
5766 num_stripes = bbio->num_stripes;
5767 if (*mirror_num > num_stripes) {
5769 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5770 * that means that the requested area is not left of the left
5773 btrfs_put_bbio(bbio);
5778 * process the rest of the function using the mirror_num of the source
5779 * drive. Therefore look it up first. At the end, patch the device
5780 * pointer to the one of the target drive.
5782 for (i = 0; i < num_stripes; i++) {
5783 if (bbio->stripes[i].dev->devid != srcdev_devid)
5787 * In case of DUP, in order to keep it simple, only add the
5788 * mirror with the lowest physical address
5791 physical_of_found <= bbio->stripes[i].physical)
5796 physical_of_found = bbio->stripes[i].physical;
5799 btrfs_put_bbio(bbio);
5805 *mirror_num = index_srcdev + 1;
5806 *physical = physical_of_found;
5810 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5811 struct btrfs_bio **bbio_ret,
5812 struct btrfs_dev_replace *dev_replace,
5813 int *num_stripes_ret, int *max_errors_ret)
5815 struct btrfs_bio *bbio = *bbio_ret;
5816 u64 srcdev_devid = dev_replace->srcdev->devid;
5817 int tgtdev_indexes = 0;
5818 int num_stripes = *num_stripes_ret;
5819 int max_errors = *max_errors_ret;
5822 if (op == BTRFS_MAP_WRITE) {
5823 int index_where_to_add;
5826 * duplicate the write operations while the dev replace
5827 * procedure is running. Since the copying of the old disk to
5828 * the new disk takes place at run time while the filesystem is
5829 * mounted writable, the regular write operations to the old
5830 * disk have to be duplicated to go to the new disk as well.
5832 * Note that device->missing is handled by the caller, and that
5833 * the write to the old disk is already set up in the stripes
5836 index_where_to_add = num_stripes;
5837 for (i = 0; i < num_stripes; i++) {
5838 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5839 /* write to new disk, too */
5840 struct btrfs_bio_stripe *new =
5841 bbio->stripes + index_where_to_add;
5842 struct btrfs_bio_stripe *old =
5845 new->physical = old->physical;
5846 new->length = old->length;
5847 new->dev = dev_replace->tgtdev;
5848 bbio->tgtdev_map[i] = index_where_to_add;
5849 index_where_to_add++;
5854 num_stripes = index_where_to_add;
5855 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5856 int index_srcdev = 0;
5858 u64 physical_of_found = 0;
5861 * During the dev-replace procedure, the target drive can also
5862 * be used to read data in case it is needed to repair a corrupt
5863 * block elsewhere. This is possible if the requested area is
5864 * left of the left cursor. In this area, the target drive is a
5865 * full copy of the source drive.
5867 for (i = 0; i < num_stripes; i++) {
5868 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5870 * In case of DUP, in order to keep it simple,
5871 * only add the mirror with the lowest physical
5875 physical_of_found <=
5876 bbio->stripes[i].physical)
5880 physical_of_found = bbio->stripes[i].physical;
5884 struct btrfs_bio_stripe *tgtdev_stripe =
5885 bbio->stripes + num_stripes;
5887 tgtdev_stripe->physical = physical_of_found;
5888 tgtdev_stripe->length =
5889 bbio->stripes[index_srcdev].length;
5890 tgtdev_stripe->dev = dev_replace->tgtdev;
5891 bbio->tgtdev_map[index_srcdev] = num_stripes;
5898 *num_stripes_ret = num_stripes;
5899 *max_errors_ret = max_errors;
5900 bbio->num_tgtdevs = tgtdev_indexes;
5904 static bool need_full_stripe(enum btrfs_map_op op)
5906 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5910 * btrfs_get_io_geometry - calculates the geomery of a particular (address, len)
5911 * tuple. This information is used to calculate how big a
5912 * particular bio can get before it straddles a stripe.
5914 * @fs_info - the filesystem
5915 * @logical - address that we want to figure out the geometry of
5916 * @len - the length of IO we are going to perform, starting at @logical
5917 * @op - type of operation - write or read
5918 * @io_geom - pointer used to return values
5920 * Returns < 0 in case a chunk for the given logical address cannot be found,
5921 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
5923 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5924 u64 logical, u64 len, struct btrfs_io_geometry *io_geom)
5926 struct extent_map *em;
5927 struct map_lookup *map;
5932 u64 raid56_full_stripe_start = (u64)-1;
5936 ASSERT(op != BTRFS_MAP_DISCARD);
5938 em = btrfs_get_chunk_map(fs_info, logical, len);
5942 map = em->map_lookup;
5943 /* Offset of this logical address in the chunk */
5944 offset = logical - em->start;
5945 /* Len of a stripe in a chunk */
5946 stripe_len = map->stripe_len;
5947 /* Stripe wher this block falls in */
5948 stripe_nr = div64_u64(offset, stripe_len);
5949 /* Offset of stripe in the chunk */
5950 stripe_offset = stripe_nr * stripe_len;
5951 if (offset < stripe_offset) {
5953 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
5954 stripe_offset, offset, em->start, logical, stripe_len);
5959 /* stripe_offset is the offset of this block in its stripe */
5960 stripe_offset = offset - stripe_offset;
5961 data_stripes = nr_data_stripes(map);
5963 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5964 u64 max_len = stripe_len - stripe_offset;
5967 * In case of raid56, we need to know the stripe aligned start
5969 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5970 unsigned long full_stripe_len = stripe_len * data_stripes;
5971 raid56_full_stripe_start = offset;
5974 * Allow a write of a full stripe, but make sure we
5975 * don't allow straddling of stripes
5977 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5979 raid56_full_stripe_start *= full_stripe_len;
5982 * For writes to RAID[56], allow a full stripeset across
5983 * all disks. For other RAID types and for RAID[56]
5984 * reads, just allow a single stripe (on a single disk).
5986 if (op == BTRFS_MAP_WRITE) {
5987 max_len = stripe_len * data_stripes -
5988 (offset - raid56_full_stripe_start);
5991 len = min_t(u64, em->len - offset, max_len);
5993 len = em->len - offset;
5997 io_geom->offset = offset;
5998 io_geom->stripe_len = stripe_len;
5999 io_geom->stripe_nr = stripe_nr;
6000 io_geom->stripe_offset = stripe_offset;
6001 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6005 free_extent_map(em);
6009 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6010 enum btrfs_map_op op,
6011 u64 logical, u64 *length,
6012 struct btrfs_bio **bbio_ret,
6013 int mirror_num, int need_raid_map)
6015 struct extent_map *em;
6016 struct map_lookup *map;
6026 int tgtdev_indexes = 0;
6027 struct btrfs_bio *bbio = NULL;
6028 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6029 int dev_replace_is_ongoing = 0;
6030 int num_alloc_stripes;
6031 int patch_the_first_stripe_for_dev_replace = 0;
6032 u64 physical_to_patch_in_first_stripe = 0;
6033 u64 raid56_full_stripe_start = (u64)-1;
6034 struct btrfs_io_geometry geom;
6037 ASSERT(op != BTRFS_MAP_DISCARD);
6039 ret = btrfs_get_io_geometry(fs_info, op, logical, *length, &geom);
6043 em = btrfs_get_chunk_map(fs_info, logical, *length);
6044 ASSERT(!IS_ERR(em));
6045 map = em->map_lookup;
6048 stripe_len = geom.stripe_len;
6049 stripe_nr = geom.stripe_nr;
6050 stripe_offset = geom.stripe_offset;
6051 raid56_full_stripe_start = geom.raid56_stripe_offset;
6052 data_stripes = nr_data_stripes(map);
6054 down_read(&dev_replace->rwsem);
6055 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6057 * Hold the semaphore for read during the whole operation, write is
6058 * requested at commit time but must wait.
6060 if (!dev_replace_is_ongoing)
6061 up_read(&dev_replace->rwsem);
6063 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6064 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6065 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6066 dev_replace->srcdev->devid,
6068 &physical_to_patch_in_first_stripe);
6072 patch_the_first_stripe_for_dev_replace = 1;
6073 } else if (mirror_num > map->num_stripes) {
6079 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6080 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6082 if (!need_full_stripe(op))
6084 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6085 if (need_full_stripe(op))
6086 num_stripes = map->num_stripes;
6087 else if (mirror_num)
6088 stripe_index = mirror_num - 1;
6090 stripe_index = find_live_mirror(fs_info, map, 0,
6091 dev_replace_is_ongoing);
6092 mirror_num = stripe_index + 1;
6095 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6096 if (need_full_stripe(op)) {
6097 num_stripes = map->num_stripes;
6098 } else if (mirror_num) {
6099 stripe_index = mirror_num - 1;
6104 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6105 u32 factor = map->num_stripes / map->sub_stripes;
6107 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6108 stripe_index *= map->sub_stripes;
6110 if (need_full_stripe(op))
6111 num_stripes = map->sub_stripes;
6112 else if (mirror_num)
6113 stripe_index += mirror_num - 1;
6115 int old_stripe_index = stripe_index;
6116 stripe_index = find_live_mirror(fs_info, map,
6118 dev_replace_is_ongoing);
6119 mirror_num = stripe_index - old_stripe_index + 1;
6122 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6123 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6124 /* push stripe_nr back to the start of the full stripe */
6125 stripe_nr = div64_u64(raid56_full_stripe_start,
6126 stripe_len * data_stripes);
6128 /* RAID[56] write or recovery. Return all stripes */
6129 num_stripes = map->num_stripes;
6130 max_errors = nr_parity_stripes(map);
6132 *length = map->stripe_len;
6137 * Mirror #0 or #1 means the original data block.
6138 * Mirror #2 is RAID5 parity block.
6139 * Mirror #3 is RAID6 Q block.
6141 stripe_nr = div_u64_rem(stripe_nr,
6142 data_stripes, &stripe_index);
6144 stripe_index = data_stripes + mirror_num - 2;
6146 /* We distribute the parity blocks across stripes */
6147 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6149 if (!need_full_stripe(op) && mirror_num <= 1)
6154 * after this, stripe_nr is the number of stripes on this
6155 * device we have to walk to find the data, and stripe_index is
6156 * the number of our device in the stripe array
6158 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6160 mirror_num = stripe_index + 1;
6162 if (stripe_index >= map->num_stripes) {
6164 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6165 stripe_index, map->num_stripes);
6170 num_alloc_stripes = num_stripes;
6171 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6172 if (op == BTRFS_MAP_WRITE)
6173 num_alloc_stripes <<= 1;
6174 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6175 num_alloc_stripes++;
6176 tgtdev_indexes = num_stripes;
6179 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6185 for (i = 0; i < num_stripes; i++) {
6186 bbio->stripes[i].physical = map->stripes[stripe_index].physical +
6187 stripe_offset + stripe_nr * map->stripe_len;
6188 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
6192 /* build raid_map */
6193 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6194 (need_full_stripe(op) || mirror_num > 1)) {
6198 /* Work out the disk rotation on this stripe-set */
6199 div_u64_rem(stripe_nr, num_stripes, &rot);
6201 /* Fill in the logical address of each stripe */
6202 tmp = stripe_nr * data_stripes;
6203 for (i = 0; i < data_stripes; i++)
6204 bbio->raid_map[(i+rot) % num_stripes] =
6205 em->start + (tmp + i) * map->stripe_len;
6207 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6208 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6209 bbio->raid_map[(i+rot+1) % num_stripes] =
6212 sort_parity_stripes(bbio, num_stripes);
6215 if (need_full_stripe(op))
6216 max_errors = btrfs_chunk_max_errors(map);
6218 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6219 need_full_stripe(op)) {
6220 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6225 bbio->map_type = map->type;
6226 bbio->num_stripes = num_stripes;
6227 bbio->max_errors = max_errors;
6228 bbio->mirror_num = mirror_num;
6231 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6232 * mirror_num == num_stripes + 1 && dev_replace target drive is
6233 * available as a mirror
6235 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6236 WARN_ON(num_stripes > 1);
6237 bbio->stripes[0].dev = dev_replace->tgtdev;
6238 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6239 bbio->mirror_num = map->num_stripes + 1;
6242 if (dev_replace_is_ongoing) {
6243 lockdep_assert_held(&dev_replace->rwsem);
6244 /* Unlock and let waiting writers proceed */
6245 up_read(&dev_replace->rwsem);
6247 free_extent_map(em);
6251 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6252 u64 logical, u64 *length,
6253 struct btrfs_bio **bbio_ret, int mirror_num)
6255 if (op == BTRFS_MAP_DISCARD)
6256 return __btrfs_map_block_for_discard(fs_info, logical,
6259 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6263 /* For Scrub/replace */
6264 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6265 u64 logical, u64 *length,
6266 struct btrfs_bio **bbio_ret)
6268 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6271 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6273 bio->bi_private = bbio->private;
6274 bio->bi_end_io = bbio->end_io;
6277 btrfs_put_bbio(bbio);
6280 static void btrfs_end_bio(struct bio *bio)
6282 struct btrfs_bio *bbio = bio->bi_private;
6283 int is_orig_bio = 0;
6285 if (bio->bi_status) {
6286 atomic_inc(&bbio->error);
6287 if (bio->bi_status == BLK_STS_IOERR ||
6288 bio->bi_status == BLK_STS_TARGET) {
6289 struct btrfs_device *dev = btrfs_io_bio(bio)->device;
6292 if (bio_op(bio) == REQ_OP_WRITE)
6293 btrfs_dev_stat_inc_and_print(dev,
6294 BTRFS_DEV_STAT_WRITE_ERRS);
6295 else if (!(bio->bi_opf & REQ_RAHEAD))
6296 btrfs_dev_stat_inc_and_print(dev,
6297 BTRFS_DEV_STAT_READ_ERRS);
6298 if (bio->bi_opf & REQ_PREFLUSH)
6299 btrfs_dev_stat_inc_and_print(dev,
6300 BTRFS_DEV_STAT_FLUSH_ERRS);
6304 if (bio == bbio->orig_bio)
6307 btrfs_bio_counter_dec(bbio->fs_info);
6309 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6312 bio = bbio->orig_bio;
6315 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6316 /* only send an error to the higher layers if it is
6317 * beyond the tolerance of the btrfs bio
6319 if (atomic_read(&bbio->error) > bbio->max_errors) {
6320 bio->bi_status = BLK_STS_IOERR;
6323 * this bio is actually up to date, we didn't
6324 * go over the max number of errors
6326 bio->bi_status = BLK_STS_OK;
6329 btrfs_end_bbio(bbio, bio);
6330 } else if (!is_orig_bio) {
6335 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6336 u64 physical, struct btrfs_device *dev)
6338 struct btrfs_fs_info *fs_info = bbio->fs_info;
6340 bio->bi_private = bbio;
6341 btrfs_io_bio(bio)->device = dev;
6342 bio->bi_end_io = btrfs_end_bio;
6343 bio->bi_iter.bi_sector = physical >> 9;
6344 btrfs_debug_in_rcu(fs_info,
6345 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6346 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6347 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6348 dev->devid, bio->bi_iter.bi_size);
6349 bio_set_dev(bio, dev->bdev);
6351 btrfs_bio_counter_inc_noblocked(fs_info);
6353 btrfsic_submit_bio(bio);
6356 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6358 atomic_inc(&bbio->error);
6359 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6360 /* Should be the original bio. */
6361 WARN_ON(bio != bbio->orig_bio);
6363 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6364 bio->bi_iter.bi_sector = logical >> 9;
6365 if (atomic_read(&bbio->error) > bbio->max_errors)
6366 bio->bi_status = BLK_STS_IOERR;
6368 bio->bi_status = BLK_STS_OK;
6369 btrfs_end_bbio(bbio, bio);
6373 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6376 struct btrfs_device *dev;
6377 struct bio *first_bio = bio;
6378 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6384 struct btrfs_bio *bbio = NULL;
6386 length = bio->bi_iter.bi_size;
6387 map_length = length;
6389 btrfs_bio_counter_inc_blocked(fs_info);
6390 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6391 &map_length, &bbio, mirror_num, 1);
6393 btrfs_bio_counter_dec(fs_info);
6394 return errno_to_blk_status(ret);
6397 total_devs = bbio->num_stripes;
6398 bbio->orig_bio = first_bio;
6399 bbio->private = first_bio->bi_private;
6400 bbio->end_io = first_bio->bi_end_io;
6401 bbio->fs_info = fs_info;
6402 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6404 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6405 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6406 /* In this case, map_length has been set to the length of
6407 a single stripe; not the whole write */
6408 if (bio_op(bio) == REQ_OP_WRITE) {
6409 ret = raid56_parity_write(fs_info, bio, bbio,
6412 ret = raid56_parity_recover(fs_info, bio, bbio,
6413 map_length, mirror_num, 1);
6416 btrfs_bio_counter_dec(fs_info);
6417 return errno_to_blk_status(ret);
6420 if (map_length < length) {
6422 "mapping failed logical %llu bio len %llu len %llu",
6423 logical, length, map_length);
6427 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6428 dev = bbio->stripes[dev_nr].dev;
6429 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6431 (bio_op(first_bio) == REQ_OP_WRITE &&
6432 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6433 bbio_error(bbio, first_bio, logical);
6437 if (dev_nr < total_devs - 1)
6438 bio = btrfs_bio_clone(first_bio);
6442 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical, dev);
6444 btrfs_bio_counter_dec(fs_info);
6449 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6452 * If devid and uuid are both specified, the match must be exact, otherwise
6453 * only devid is used.
6455 * If @seed is true, traverse through the seed devices.
6457 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6458 u64 devid, u8 *uuid, u8 *fsid,
6461 struct btrfs_device *device;
6463 while (fs_devices) {
6465 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6466 list_for_each_entry(device, &fs_devices->devices,
6468 if (device->devid == devid &&
6469 (!uuid || memcmp(device->uuid, uuid,
6470 BTRFS_UUID_SIZE) == 0))
6475 fs_devices = fs_devices->seed;
6482 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6483 u64 devid, u8 *dev_uuid)
6485 struct btrfs_device *device;
6487 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6491 list_add(&device->dev_list, &fs_devices->devices);
6492 device->fs_devices = fs_devices;
6493 fs_devices->num_devices++;
6495 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6496 fs_devices->missing_devices++;
6502 * btrfs_alloc_device - allocate struct btrfs_device
6503 * @fs_info: used only for generating a new devid, can be NULL if
6504 * devid is provided (i.e. @devid != NULL).
6505 * @devid: a pointer to devid for this device. If NULL a new devid
6507 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6510 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6511 * on error. Returned struct is not linked onto any lists and must be
6512 * destroyed with btrfs_free_device.
6514 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6518 struct btrfs_device *dev;
6521 if (WARN_ON(!devid && !fs_info))
6522 return ERR_PTR(-EINVAL);
6524 dev = __alloc_device();
6533 ret = find_next_devid(fs_info, &tmp);
6535 btrfs_free_device(dev);
6536 return ERR_PTR(ret);
6542 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6544 generate_random_uuid(dev->uuid);
6549 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6550 u64 devid, u8 *uuid, bool error)
6553 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6556 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6560 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6562 int index = btrfs_bg_flags_to_raid_index(type);
6563 int ncopies = btrfs_raid_array[index].ncopies;
6564 const int nparity = btrfs_raid_array[index].nparity;
6568 data_stripes = num_stripes - nparity;
6570 data_stripes = num_stripes / ncopies;
6572 return div_u64(chunk_len, data_stripes);
6575 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6576 struct btrfs_chunk *chunk)
6578 struct btrfs_fs_info *fs_info = leaf->fs_info;
6579 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6580 struct map_lookup *map;
6581 struct extent_map *em;
6585 u8 uuid[BTRFS_UUID_SIZE];
6590 logical = key->offset;
6591 length = btrfs_chunk_length(leaf, chunk);
6592 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6595 * Only need to verify chunk item if we're reading from sys chunk array,
6596 * as chunk item in tree block is already verified by tree-checker.
6598 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6599 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6604 read_lock(&map_tree->lock);
6605 em = lookup_extent_mapping(map_tree, logical, 1);
6606 read_unlock(&map_tree->lock);
6608 /* already mapped? */
6609 if (em && em->start <= logical && em->start + em->len > logical) {
6610 free_extent_map(em);
6613 free_extent_map(em);
6616 em = alloc_extent_map();
6619 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6621 free_extent_map(em);
6625 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6626 em->map_lookup = map;
6627 em->start = logical;
6630 em->block_start = 0;
6631 em->block_len = em->len;
6633 map->num_stripes = num_stripes;
6634 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6635 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6636 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6637 map->type = btrfs_chunk_type(leaf, chunk);
6638 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6639 map->verified_stripes = 0;
6640 em->orig_block_len = calc_stripe_length(map->type, em->len,
6642 for (i = 0; i < num_stripes; i++) {
6643 map->stripes[i].physical =
6644 btrfs_stripe_offset_nr(leaf, chunk, i);
6645 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6646 read_extent_buffer(leaf, uuid, (unsigned long)
6647 btrfs_stripe_dev_uuid_nr(chunk, i),
6649 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6650 devid, uuid, NULL, true);
6651 if (!map->stripes[i].dev &&
6652 !btrfs_test_opt(fs_info, DEGRADED)) {
6653 free_extent_map(em);
6654 btrfs_report_missing_device(fs_info, devid, uuid, true);
6657 if (!map->stripes[i].dev) {
6658 map->stripes[i].dev =
6659 add_missing_dev(fs_info->fs_devices, devid,
6661 if (IS_ERR(map->stripes[i].dev)) {
6662 free_extent_map(em);
6664 "failed to init missing dev %llu: %ld",
6665 devid, PTR_ERR(map->stripes[i].dev));
6666 return PTR_ERR(map->stripes[i].dev);
6668 btrfs_report_missing_device(fs_info, devid, uuid, false);
6670 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6671 &(map->stripes[i].dev->dev_state));
6675 write_lock(&map_tree->lock);
6676 ret = add_extent_mapping(map_tree, em, 0);
6677 write_unlock(&map_tree->lock);
6680 "failed to add chunk map, start=%llu len=%llu: %d",
6681 em->start, em->len, ret);
6683 free_extent_map(em);
6688 static void fill_device_from_item(struct extent_buffer *leaf,
6689 struct btrfs_dev_item *dev_item,
6690 struct btrfs_device *device)
6694 device->devid = btrfs_device_id(leaf, dev_item);
6695 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6696 device->total_bytes = device->disk_total_bytes;
6697 device->commit_total_bytes = device->disk_total_bytes;
6698 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6699 device->commit_bytes_used = device->bytes_used;
6700 device->type = btrfs_device_type(leaf, dev_item);
6701 device->io_align = btrfs_device_io_align(leaf, dev_item);
6702 device->io_width = btrfs_device_io_width(leaf, dev_item);
6703 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6704 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6705 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6707 ptr = btrfs_device_uuid(dev_item);
6708 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6711 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6714 struct btrfs_fs_devices *fs_devices;
6717 lockdep_assert_held(&uuid_mutex);
6720 fs_devices = fs_info->fs_devices->seed;
6721 while (fs_devices) {
6722 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6725 fs_devices = fs_devices->seed;
6728 fs_devices = find_fsid(fsid, NULL);
6730 if (!btrfs_test_opt(fs_info, DEGRADED))
6731 return ERR_PTR(-ENOENT);
6733 fs_devices = alloc_fs_devices(fsid, NULL);
6734 if (IS_ERR(fs_devices))
6737 fs_devices->seeding = true;
6738 fs_devices->opened = 1;
6742 fs_devices = clone_fs_devices(fs_devices);
6743 if (IS_ERR(fs_devices))
6746 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6748 free_fs_devices(fs_devices);
6749 fs_devices = ERR_PTR(ret);
6753 if (!fs_devices->seeding) {
6754 close_fs_devices(fs_devices);
6755 free_fs_devices(fs_devices);
6756 fs_devices = ERR_PTR(-EINVAL);
6760 fs_devices->seed = fs_info->fs_devices->seed;
6761 fs_info->fs_devices->seed = fs_devices;
6766 static int read_one_dev(struct extent_buffer *leaf,
6767 struct btrfs_dev_item *dev_item)
6769 struct btrfs_fs_info *fs_info = leaf->fs_info;
6770 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6771 struct btrfs_device *device;
6774 u8 fs_uuid[BTRFS_FSID_SIZE];
6775 u8 dev_uuid[BTRFS_UUID_SIZE];
6777 devid = btrfs_device_id(leaf, dev_item);
6778 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6780 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6783 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6784 fs_devices = open_seed_devices(fs_info, fs_uuid);
6785 if (IS_ERR(fs_devices))
6786 return PTR_ERR(fs_devices);
6789 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6792 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6793 btrfs_report_missing_device(fs_info, devid,
6798 device = add_missing_dev(fs_devices, devid, dev_uuid);
6799 if (IS_ERR(device)) {
6801 "failed to add missing dev %llu: %ld",
6802 devid, PTR_ERR(device));
6803 return PTR_ERR(device);
6805 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6807 if (!device->bdev) {
6808 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6809 btrfs_report_missing_device(fs_info,
6810 devid, dev_uuid, true);
6813 btrfs_report_missing_device(fs_info, devid,
6817 if (!device->bdev &&
6818 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6820 * this happens when a device that was properly setup
6821 * in the device info lists suddenly goes bad.
6822 * device->bdev is NULL, and so we have to set
6823 * device->missing to one here
6825 device->fs_devices->missing_devices++;
6826 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6829 /* Move the device to its own fs_devices */
6830 if (device->fs_devices != fs_devices) {
6831 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6832 &device->dev_state));
6834 list_move(&device->dev_list, &fs_devices->devices);
6835 device->fs_devices->num_devices--;
6836 fs_devices->num_devices++;
6838 device->fs_devices->missing_devices--;
6839 fs_devices->missing_devices++;
6841 device->fs_devices = fs_devices;
6845 if (device->fs_devices != fs_info->fs_devices) {
6846 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6847 if (device->generation !=
6848 btrfs_device_generation(leaf, dev_item))
6852 fill_device_from_item(leaf, dev_item, device);
6853 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6854 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6855 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6856 device->fs_devices->total_rw_bytes += device->total_bytes;
6857 atomic64_add(device->total_bytes - device->bytes_used,
6858 &fs_info->free_chunk_space);
6864 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6866 struct btrfs_root *root = fs_info->tree_root;
6867 struct btrfs_super_block *super_copy = fs_info->super_copy;
6868 struct extent_buffer *sb;
6869 struct btrfs_disk_key *disk_key;
6870 struct btrfs_chunk *chunk;
6872 unsigned long sb_array_offset;
6879 struct btrfs_key key;
6881 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6883 * This will create extent buffer of nodesize, superblock size is
6884 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6885 * overallocate but we can keep it as-is, only the first page is used.
6887 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6890 set_extent_buffer_uptodate(sb);
6891 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6893 * The sb extent buffer is artificial and just used to read the system array.
6894 * set_extent_buffer_uptodate() call does not properly mark all it's
6895 * pages up-to-date when the page is larger: extent does not cover the
6896 * whole page and consequently check_page_uptodate does not find all
6897 * the page's extents up-to-date (the hole beyond sb),
6898 * write_extent_buffer then triggers a WARN_ON.
6900 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6901 * but sb spans only this function. Add an explicit SetPageUptodate call
6902 * to silence the warning eg. on PowerPC 64.
6904 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6905 SetPageUptodate(sb->pages[0]);
6907 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6908 array_size = btrfs_super_sys_array_size(super_copy);
6910 array_ptr = super_copy->sys_chunk_array;
6911 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6914 while (cur_offset < array_size) {
6915 disk_key = (struct btrfs_disk_key *)array_ptr;
6916 len = sizeof(*disk_key);
6917 if (cur_offset + len > array_size)
6918 goto out_short_read;
6920 btrfs_disk_key_to_cpu(&key, disk_key);
6923 sb_array_offset += len;
6926 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
6928 "unexpected item type %u in sys_array at offset %u",
6929 (u32)key.type, cur_offset);
6934 chunk = (struct btrfs_chunk *)sb_array_offset;
6936 * At least one btrfs_chunk with one stripe must be present,
6937 * exact stripe count check comes afterwards
6939 len = btrfs_chunk_item_size(1);
6940 if (cur_offset + len > array_size)
6941 goto out_short_read;
6943 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6946 "invalid number of stripes %u in sys_array at offset %u",
6947 num_stripes, cur_offset);
6952 type = btrfs_chunk_type(sb, chunk);
6953 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6955 "invalid chunk type %llu in sys_array at offset %u",
6961 len = btrfs_chunk_item_size(num_stripes);
6962 if (cur_offset + len > array_size)
6963 goto out_short_read;
6965 ret = read_one_chunk(&key, sb, chunk);
6970 sb_array_offset += len;
6973 clear_extent_buffer_uptodate(sb);
6974 free_extent_buffer_stale(sb);
6978 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6980 clear_extent_buffer_uptodate(sb);
6981 free_extent_buffer_stale(sb);
6986 * Check if all chunks in the fs are OK for read-write degraded mount
6988 * If the @failing_dev is specified, it's accounted as missing.
6990 * Return true if all chunks meet the minimal RW mount requirements.
6991 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6993 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6994 struct btrfs_device *failing_dev)
6996 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6997 struct extent_map *em;
7001 read_lock(&map_tree->lock);
7002 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7003 read_unlock(&map_tree->lock);
7004 /* No chunk at all? Return false anyway */
7010 struct map_lookup *map;
7015 map = em->map_lookup;
7017 btrfs_get_num_tolerated_disk_barrier_failures(
7019 for (i = 0; i < map->num_stripes; i++) {
7020 struct btrfs_device *dev = map->stripes[i].dev;
7022 if (!dev || !dev->bdev ||
7023 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7024 dev->last_flush_error)
7026 else if (failing_dev && failing_dev == dev)
7029 if (missing > max_tolerated) {
7032 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7033 em->start, missing, max_tolerated);
7034 free_extent_map(em);
7038 next_start = extent_map_end(em);
7039 free_extent_map(em);
7041 read_lock(&map_tree->lock);
7042 em = lookup_extent_mapping(map_tree, next_start,
7043 (u64)(-1) - next_start);
7044 read_unlock(&map_tree->lock);
7050 static void readahead_tree_node_children(struct extent_buffer *node)
7053 const int nr_items = btrfs_header_nritems(node);
7055 for (i = 0; i < nr_items; i++) {
7058 start = btrfs_node_blockptr(node, i);
7059 readahead_tree_block(node->fs_info, start);
7063 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7065 struct btrfs_root *root = fs_info->chunk_root;
7066 struct btrfs_path *path;
7067 struct extent_buffer *leaf;
7068 struct btrfs_key key;
7069 struct btrfs_key found_key;
7073 u64 last_ra_node = 0;
7075 path = btrfs_alloc_path();
7080 * uuid_mutex is needed only if we are mounting a sprout FS
7081 * otherwise we don't need it.
7083 mutex_lock(&uuid_mutex);
7086 * It is possible for mount and umount to race in such a way that
7087 * we execute this code path, but open_fs_devices failed to clear
7088 * total_rw_bytes. We certainly want it cleared before reading the
7089 * device items, so clear it here.
7091 fs_info->fs_devices->total_rw_bytes = 0;
7094 * Read all device items, and then all the chunk items. All
7095 * device items are found before any chunk item (their object id
7096 * is smaller than the lowest possible object id for a chunk
7097 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7099 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7102 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7106 struct extent_buffer *node;
7108 leaf = path->nodes[0];
7109 slot = path->slots[0];
7110 if (slot >= btrfs_header_nritems(leaf)) {
7111 ret = btrfs_next_leaf(root, path);
7119 * The nodes on level 1 are not locked but we don't need to do
7120 * that during mount time as nothing else can access the tree
7122 node = path->nodes[1];
7124 if (last_ra_node != node->start) {
7125 readahead_tree_node_children(node);
7126 last_ra_node = node->start;
7129 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7130 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7131 struct btrfs_dev_item *dev_item;
7132 dev_item = btrfs_item_ptr(leaf, slot,
7133 struct btrfs_dev_item);
7134 ret = read_one_dev(leaf, dev_item);
7138 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7139 struct btrfs_chunk *chunk;
7140 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7141 mutex_lock(&fs_info->chunk_mutex);
7142 ret = read_one_chunk(&found_key, leaf, chunk);
7143 mutex_unlock(&fs_info->chunk_mutex);
7151 * After loading chunk tree, we've got all device information,
7152 * do another round of validation checks.
7154 if (total_dev != fs_info->fs_devices->total_devices) {
7156 "super_num_devices %llu mismatch with num_devices %llu found here",
7157 btrfs_super_num_devices(fs_info->super_copy),
7162 if (btrfs_super_total_bytes(fs_info->super_copy) <
7163 fs_info->fs_devices->total_rw_bytes) {
7165 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7166 btrfs_super_total_bytes(fs_info->super_copy),
7167 fs_info->fs_devices->total_rw_bytes);
7173 mutex_unlock(&uuid_mutex);
7175 btrfs_free_path(path);
7179 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7181 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7182 struct btrfs_device *device;
7184 while (fs_devices) {
7185 mutex_lock(&fs_devices->device_list_mutex);
7186 list_for_each_entry(device, &fs_devices->devices, dev_list)
7187 device->fs_info = fs_info;
7188 mutex_unlock(&fs_devices->device_list_mutex);
7190 fs_devices = fs_devices->seed;
7194 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7195 const struct btrfs_dev_stats_item *ptr,
7200 read_extent_buffer(eb, &val,
7201 offsetof(struct btrfs_dev_stats_item, values) +
7202 ((unsigned long)ptr) + (index * sizeof(u64)),
7207 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7208 struct btrfs_dev_stats_item *ptr,
7211 write_extent_buffer(eb, &val,
7212 offsetof(struct btrfs_dev_stats_item, values) +
7213 ((unsigned long)ptr) + (index * sizeof(u64)),
7217 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7219 struct btrfs_key key;
7220 struct btrfs_root *dev_root = fs_info->dev_root;
7221 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7222 struct extent_buffer *eb;
7225 struct btrfs_device *device;
7226 struct btrfs_path *path = NULL;
7229 path = btrfs_alloc_path();
7233 mutex_lock(&fs_devices->device_list_mutex);
7234 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7236 struct btrfs_dev_stats_item *ptr;
7238 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7239 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7240 key.offset = device->devid;
7241 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7243 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7244 btrfs_dev_stat_set(device, i, 0);
7245 device->dev_stats_valid = 1;
7246 btrfs_release_path(path);
7249 slot = path->slots[0];
7250 eb = path->nodes[0];
7251 item_size = btrfs_item_size_nr(eb, slot);
7253 ptr = btrfs_item_ptr(eb, slot,
7254 struct btrfs_dev_stats_item);
7256 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7257 if (item_size >= (1 + i) * sizeof(__le64))
7258 btrfs_dev_stat_set(device, i,
7259 btrfs_dev_stats_value(eb, ptr, i));
7261 btrfs_dev_stat_set(device, i, 0);
7264 device->dev_stats_valid = 1;
7265 btrfs_dev_stat_print_on_load(device);
7266 btrfs_release_path(path);
7268 mutex_unlock(&fs_devices->device_list_mutex);
7270 btrfs_free_path(path);
7271 return ret < 0 ? ret : 0;
7274 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7275 struct btrfs_device *device)
7277 struct btrfs_fs_info *fs_info = trans->fs_info;
7278 struct btrfs_root *dev_root = fs_info->dev_root;
7279 struct btrfs_path *path;
7280 struct btrfs_key key;
7281 struct extent_buffer *eb;
7282 struct btrfs_dev_stats_item *ptr;
7286 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7287 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7288 key.offset = device->devid;
7290 path = btrfs_alloc_path();
7293 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7295 btrfs_warn_in_rcu(fs_info,
7296 "error %d while searching for dev_stats item for device %s",
7297 ret, rcu_str_deref(device->name));
7302 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7303 /* need to delete old one and insert a new one */
7304 ret = btrfs_del_item(trans, dev_root, path);
7306 btrfs_warn_in_rcu(fs_info,
7307 "delete too small dev_stats item for device %s failed %d",
7308 rcu_str_deref(device->name), ret);
7315 /* need to insert a new item */
7316 btrfs_release_path(path);
7317 ret = btrfs_insert_empty_item(trans, dev_root, path,
7318 &key, sizeof(*ptr));
7320 btrfs_warn_in_rcu(fs_info,
7321 "insert dev_stats item for device %s failed %d",
7322 rcu_str_deref(device->name), ret);
7327 eb = path->nodes[0];
7328 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7329 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7330 btrfs_set_dev_stats_value(eb, ptr, i,
7331 btrfs_dev_stat_read(device, i));
7332 btrfs_mark_buffer_dirty(eb);
7335 btrfs_free_path(path);
7340 * called from commit_transaction. Writes all changed device stats to disk.
7342 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7344 struct btrfs_fs_info *fs_info = trans->fs_info;
7345 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7346 struct btrfs_device *device;
7350 mutex_lock(&fs_devices->device_list_mutex);
7351 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7352 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7353 if (!device->dev_stats_valid || stats_cnt == 0)
7358 * There is a LOAD-LOAD control dependency between the value of
7359 * dev_stats_ccnt and updating the on-disk values which requires
7360 * reading the in-memory counters. Such control dependencies
7361 * require explicit read memory barriers.
7363 * This memory barriers pairs with smp_mb__before_atomic in
7364 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7365 * barrier implied by atomic_xchg in
7366 * btrfs_dev_stats_read_and_reset
7370 ret = update_dev_stat_item(trans, device);
7372 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7374 mutex_unlock(&fs_devices->device_list_mutex);
7379 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7381 btrfs_dev_stat_inc(dev, index);
7382 btrfs_dev_stat_print_on_error(dev);
7385 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7387 if (!dev->dev_stats_valid)
7389 btrfs_err_rl_in_rcu(dev->fs_info,
7390 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7391 rcu_str_deref(dev->name),
7392 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7393 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7394 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7395 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7396 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7399 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7403 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7404 if (btrfs_dev_stat_read(dev, i) != 0)
7406 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7407 return; /* all values == 0, suppress message */
7409 btrfs_info_in_rcu(dev->fs_info,
7410 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7411 rcu_str_deref(dev->name),
7412 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7413 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7414 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7415 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7416 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7419 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7420 struct btrfs_ioctl_get_dev_stats *stats)
7422 struct btrfs_device *dev;
7423 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7426 mutex_lock(&fs_devices->device_list_mutex);
7427 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7429 mutex_unlock(&fs_devices->device_list_mutex);
7432 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7434 } else if (!dev->dev_stats_valid) {
7435 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7437 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7438 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7439 if (stats->nr_items > i)
7441 btrfs_dev_stat_read_and_reset(dev, i);
7443 btrfs_dev_stat_set(dev, i, 0);
7445 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7446 current->comm, task_pid_nr(current));
7448 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7449 if (stats->nr_items > i)
7450 stats->values[i] = btrfs_dev_stat_read(dev, i);
7452 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7453 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7458 * Update the size and bytes used for each device where it changed. This is
7459 * delayed since we would otherwise get errors while writing out the
7462 * Must be invoked during transaction commit.
7464 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7466 struct btrfs_device *curr, *next;
7468 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7470 if (list_empty(&trans->dev_update_list))
7474 * We don't need the device_list_mutex here. This list is owned by the
7475 * transaction and the transaction must complete before the device is
7478 mutex_lock(&trans->fs_info->chunk_mutex);
7479 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7481 list_del_init(&curr->post_commit_list);
7482 curr->commit_total_bytes = curr->disk_total_bytes;
7483 curr->commit_bytes_used = curr->bytes_used;
7485 mutex_unlock(&trans->fs_info->chunk_mutex);
7488 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7490 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7491 while (fs_devices) {
7492 fs_devices->fs_info = fs_info;
7493 fs_devices = fs_devices->seed;
7497 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7499 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7500 while (fs_devices) {
7501 fs_devices->fs_info = NULL;
7502 fs_devices = fs_devices->seed;
7507 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7509 int btrfs_bg_type_to_factor(u64 flags)
7511 const int index = btrfs_bg_flags_to_raid_index(flags);
7513 return btrfs_raid_array[index].ncopies;
7518 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7519 u64 chunk_offset, u64 devid,
7520 u64 physical_offset, u64 physical_len)
7522 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7523 struct extent_map *em;
7524 struct map_lookup *map;
7525 struct btrfs_device *dev;
7531 read_lock(&em_tree->lock);
7532 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7533 read_unlock(&em_tree->lock);
7537 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7538 physical_offset, devid);
7543 map = em->map_lookup;
7544 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7545 if (physical_len != stripe_len) {
7547 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7548 physical_offset, devid, em->start, physical_len,
7554 for (i = 0; i < map->num_stripes; i++) {
7555 if (map->stripes[i].dev->devid == devid &&
7556 map->stripes[i].physical == physical_offset) {
7558 if (map->verified_stripes >= map->num_stripes) {
7560 "too many dev extents for chunk %llu found",
7565 map->verified_stripes++;
7571 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7572 physical_offset, devid);
7576 /* Make sure no dev extent is beyond device bondary */
7577 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7579 btrfs_err(fs_info, "failed to find devid %llu", devid);
7584 /* It's possible this device is a dummy for seed device */
7585 if (dev->disk_total_bytes == 0) {
7586 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7589 btrfs_err(fs_info, "failed to find seed devid %llu",
7596 if (physical_offset + physical_len > dev->disk_total_bytes) {
7598 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7599 devid, physical_offset, physical_len,
7600 dev->disk_total_bytes);
7605 free_extent_map(em);
7609 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7611 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7612 struct extent_map *em;
7613 struct rb_node *node;
7616 read_lock(&em_tree->lock);
7617 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7618 em = rb_entry(node, struct extent_map, rb_node);
7619 if (em->map_lookup->num_stripes !=
7620 em->map_lookup->verified_stripes) {
7622 "chunk %llu has missing dev extent, have %d expect %d",
7623 em->start, em->map_lookup->verified_stripes,
7624 em->map_lookup->num_stripes);
7630 read_unlock(&em_tree->lock);
7635 * Ensure that all dev extents are mapped to correct chunk, otherwise
7636 * later chunk allocation/free would cause unexpected behavior.
7638 * NOTE: This will iterate through the whole device tree, which should be of
7639 * the same size level as the chunk tree. This slightly increases mount time.
7641 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7643 struct btrfs_path *path;
7644 struct btrfs_root *root = fs_info->dev_root;
7645 struct btrfs_key key;
7647 u64 prev_dev_ext_end = 0;
7651 key.type = BTRFS_DEV_EXTENT_KEY;
7654 path = btrfs_alloc_path();
7658 path->reada = READA_FORWARD;
7659 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7663 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7664 ret = btrfs_next_item(root, path);
7667 /* No dev extents at all? Not good */
7674 struct extent_buffer *leaf = path->nodes[0];
7675 struct btrfs_dev_extent *dext;
7676 int slot = path->slots[0];
7678 u64 physical_offset;
7682 btrfs_item_key_to_cpu(leaf, &key, slot);
7683 if (key.type != BTRFS_DEV_EXTENT_KEY)
7685 devid = key.objectid;
7686 physical_offset = key.offset;
7688 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7689 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7690 physical_len = btrfs_dev_extent_length(leaf, dext);
7692 /* Check if this dev extent overlaps with the previous one */
7693 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7695 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7696 devid, physical_offset, prev_dev_ext_end);
7701 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7702 physical_offset, physical_len);
7706 prev_dev_ext_end = physical_offset + physical_len;
7708 ret = btrfs_next_item(root, path);
7717 /* Ensure all chunks have corresponding dev extents */
7718 ret = verify_chunk_dev_extent_mapping(fs_info);
7720 btrfs_free_path(path);
7725 * Check whether the given block group or device is pinned by any inode being
7726 * used as a swapfile.
7728 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7730 struct btrfs_swapfile_pin *sp;
7731 struct rb_node *node;
7733 spin_lock(&fs_info->swapfile_pins_lock);
7734 node = fs_info->swapfile_pins.rb_node;
7736 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7738 node = node->rb_left;
7739 else if (ptr > sp->ptr)
7740 node = node->rb_right;
7744 spin_unlock(&fs_info->swapfile_pins_lock);
7745 return node != NULL;