1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/mm.h>
9 #include <linux/slab.h>
10 #include <linux/blkdev.h>
11 #include <linux/ratelimit.h>
12 #include <linux/kthread.h>
13 #include <linux/raid/pq.h>
14 #include <linux/semaphore.h>
15 #include <linux/uuid.h>
16 #include <linux/list_sort.h>
19 #include "extent_map.h"
21 #include "transaction.h"
22 #include "print-tree.h"
25 #include "async-thread.h"
26 #include "check-integrity.h"
27 #include "rcu-string.h"
28 #include "dev-replace.h"
30 #include "tree-checker.h"
31 #include "space-info.h"
32 #include "block-group.h"
35 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
36 [BTRFS_RAID_RAID10] = {
39 .devs_max = 0, /* 0 == as many as possible */
41 .tolerated_failures = 1,
45 .raid_name = "raid10",
46 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
47 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
49 [BTRFS_RAID_RAID1] = {
54 .tolerated_failures = 1,
59 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
60 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
62 [BTRFS_RAID_RAID1C3] = {
67 .tolerated_failures = 2,
71 .raid_name = "raid1c3",
72 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3,
73 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
75 [BTRFS_RAID_RAID1C4] = {
80 .tolerated_failures = 3,
84 .raid_name = "raid1c4",
85 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4,
86 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
93 .tolerated_failures = 0,
98 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
101 [BTRFS_RAID_RAID0] = {
106 .tolerated_failures = 0,
110 .raid_name = "raid0",
111 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
114 [BTRFS_RAID_SINGLE] = {
119 .tolerated_failures = 0,
123 .raid_name = "single",
127 [BTRFS_RAID_RAID5] = {
132 .tolerated_failures = 1,
136 .raid_name = "raid5",
137 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
138 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
140 [BTRFS_RAID_RAID6] = {
145 .tolerated_failures = 2,
149 .raid_name = "raid6",
150 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
151 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
155 const char *btrfs_bg_type_to_raid_name(u64 flags)
157 const int index = btrfs_bg_flags_to_raid_index(flags);
159 if (index >= BTRFS_NR_RAID_TYPES)
162 return btrfs_raid_array[index].raid_name;
166 * Fill @buf with textual description of @bg_flags, no more than @size_buf
167 * bytes including terminating null byte.
169 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
174 u64 flags = bg_flags;
175 u32 size_bp = size_buf;
182 #define DESCRIBE_FLAG(flag, desc) \
184 if (flags & (flag)) { \
185 ret = snprintf(bp, size_bp, "%s|", (desc)); \
186 if (ret < 0 || ret >= size_bp) \
194 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
195 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
196 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
198 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
199 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
200 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
201 btrfs_raid_array[i].raid_name);
205 ret = snprintf(bp, size_bp, "0x%llx|", flags);
209 if (size_bp < size_buf)
210 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
213 * The text is trimmed, it's up to the caller to provide sufficiently
219 static int init_first_rw_device(struct btrfs_trans_handle *trans);
220 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
221 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
222 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
223 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
224 enum btrfs_map_op op,
225 u64 logical, u64 *length,
226 struct btrfs_bio **bbio_ret,
227 int mirror_num, int need_raid_map);
233 * There are several mutexes that protect manipulation of devices and low-level
234 * structures like chunks but not block groups, extents or files
236 * uuid_mutex (global lock)
237 * ------------------------
238 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
239 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
240 * device) or requested by the device= mount option
242 * the mutex can be very coarse and can cover long-running operations
244 * protects: updates to fs_devices counters like missing devices, rw devices,
245 * seeding, structure cloning, opening/closing devices at mount/umount time
247 * global::fs_devs - add, remove, updates to the global list
249 * does not protect: manipulation of the fs_devices::devices list in general
250 * but in mount context it could be used to exclude list modifications by eg.
253 * btrfs_device::name - renames (write side), read is RCU
255 * fs_devices::device_list_mutex (per-fs, with RCU)
256 * ------------------------------------------------
257 * protects updates to fs_devices::devices, ie. adding and deleting
259 * simple list traversal with read-only actions can be done with RCU protection
261 * may be used to exclude some operations from running concurrently without any
262 * modifications to the list (see write_all_supers)
264 * Is not required at mount and close times, because our device list is
265 * protected by the uuid_mutex at that point.
269 * protects balance structures (status, state) and context accessed from
270 * several places (internally, ioctl)
274 * protects chunks, adding or removing during allocation, trim or when a new
275 * device is added/removed. Additionally it also protects post_commit_list of
276 * individual devices, since they can be added to the transaction's
277 * post_commit_list only with chunk_mutex held.
281 * a big lock that is held by the cleaner thread and prevents running subvolume
282 * cleaning together with relocation or delayed iputs
294 * Exclusive operations
295 * ====================
297 * Maintains the exclusivity of the following operations that apply to the
298 * whole filesystem and cannot run in parallel.
303 * - Device replace (*)
306 * The device operations (as above) can be in one of the following states:
312 * Only device operations marked with (*) can go into the Paused state for the
315 * - ioctl (only Balance can be Paused through ioctl)
316 * - filesystem remounted as read-only
317 * - filesystem unmounted and mounted as read-only
318 * - system power-cycle and filesystem mounted as read-only
319 * - filesystem or device errors leading to forced read-only
321 * The status of exclusive operation is set and cleared atomically.
322 * During the course of Paused state, fs_info::exclusive_operation remains set.
323 * A device operation in Paused or Running state can be canceled or resumed
324 * either by ioctl (Balance only) or when remounted as read-write.
325 * The exclusive status is cleared when the device operation is canceled or
329 DEFINE_MUTEX(uuid_mutex);
330 static LIST_HEAD(fs_uuids);
331 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
337 * alloc_fs_devices - allocate struct btrfs_fs_devices
338 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
339 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
341 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
342 * The returned struct is not linked onto any lists and can be destroyed with
343 * kfree() right away.
345 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
346 const u8 *metadata_fsid)
348 struct btrfs_fs_devices *fs_devs;
350 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
352 return ERR_PTR(-ENOMEM);
354 mutex_init(&fs_devs->device_list_mutex);
356 INIT_LIST_HEAD(&fs_devs->devices);
357 INIT_LIST_HEAD(&fs_devs->alloc_list);
358 INIT_LIST_HEAD(&fs_devs->fs_list);
359 INIT_LIST_HEAD(&fs_devs->seed_list);
361 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
364 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
366 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
371 void btrfs_free_device(struct btrfs_device *device)
373 WARN_ON(!list_empty(&device->post_commit_list));
374 rcu_string_free(device->name);
375 extent_io_tree_release(&device->alloc_state);
376 bio_put(device->flush_bio);
380 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
382 struct btrfs_device *device;
383 WARN_ON(fs_devices->opened);
384 while (!list_empty(&fs_devices->devices)) {
385 device = list_entry(fs_devices->devices.next,
386 struct btrfs_device, dev_list);
387 list_del(&device->dev_list);
388 btrfs_free_device(device);
393 void __exit btrfs_cleanup_fs_uuids(void)
395 struct btrfs_fs_devices *fs_devices;
397 while (!list_empty(&fs_uuids)) {
398 fs_devices = list_entry(fs_uuids.next,
399 struct btrfs_fs_devices, fs_list);
400 list_del(&fs_devices->fs_list);
401 free_fs_devices(fs_devices);
406 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
407 * Returned struct is not linked onto any lists and must be destroyed using
410 static struct btrfs_device *__alloc_device(struct btrfs_fs_info *fs_info)
412 struct btrfs_device *dev;
414 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
416 return ERR_PTR(-ENOMEM);
419 * Preallocate a bio that's always going to be used for flushing device
420 * barriers and matches the device lifespan
422 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
423 if (!dev->flush_bio) {
425 return ERR_PTR(-ENOMEM);
428 INIT_LIST_HEAD(&dev->dev_list);
429 INIT_LIST_HEAD(&dev->dev_alloc_list);
430 INIT_LIST_HEAD(&dev->post_commit_list);
432 atomic_set(&dev->reada_in_flight, 0);
433 atomic_set(&dev->dev_stats_ccnt, 0);
434 btrfs_device_data_ordered_init(dev, fs_info);
435 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
436 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
437 extent_io_tree_init(fs_info, &dev->alloc_state,
438 IO_TREE_DEVICE_ALLOC_STATE, NULL);
443 static noinline struct btrfs_fs_devices *find_fsid(
444 const u8 *fsid, const u8 *metadata_fsid)
446 struct btrfs_fs_devices *fs_devices;
450 /* Handle non-split brain cases */
451 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
453 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
454 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
455 BTRFS_FSID_SIZE) == 0)
458 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
465 static struct btrfs_fs_devices *find_fsid_with_metadata_uuid(
466 struct btrfs_super_block *disk_super)
469 struct btrfs_fs_devices *fs_devices;
472 * Handle scanned device having completed its fsid change but
473 * belonging to a fs_devices that was created by first scanning
474 * a device which didn't have its fsid/metadata_uuid changed
475 * at all and the CHANGING_FSID_V2 flag set.
477 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
478 if (fs_devices->fsid_change &&
479 memcmp(disk_super->metadata_uuid, fs_devices->fsid,
480 BTRFS_FSID_SIZE) == 0 &&
481 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
482 BTRFS_FSID_SIZE) == 0) {
487 * Handle scanned device having completed its fsid change but
488 * belonging to a fs_devices that was created by a device that
489 * has an outdated pair of fsid/metadata_uuid and
490 * CHANGING_FSID_V2 flag set.
492 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
493 if (fs_devices->fsid_change &&
494 memcmp(fs_devices->metadata_uuid,
495 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
496 memcmp(disk_super->metadata_uuid, fs_devices->metadata_uuid,
497 BTRFS_FSID_SIZE) == 0) {
502 return find_fsid(disk_super->fsid, disk_super->metadata_uuid);
507 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
508 int flush, struct block_device **bdev,
509 struct btrfs_super_block **disk_super)
513 *bdev = blkdev_get_by_path(device_path, flags, holder);
516 ret = PTR_ERR(*bdev);
521 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
522 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
524 blkdev_put(*bdev, flags);
527 invalidate_bdev(*bdev);
528 *disk_super = btrfs_read_dev_super(*bdev);
529 if (IS_ERR(*disk_super)) {
530 ret = PTR_ERR(*disk_super);
531 blkdev_put(*bdev, flags);
542 static bool device_path_matched(const char *path, struct btrfs_device *device)
547 found = strcmp(rcu_str_deref(device->name), path);
554 * Search and remove all stale (devices which are not mounted) devices.
555 * When both inputs are NULL, it will search and release all stale devices.
556 * path: Optional. When provided will it release all unmounted devices
557 * matching this path only.
558 * skip_dev: Optional. Will skip this device when searching for the stale
560 * Return: 0 for success or if @path is NULL.
561 * -EBUSY if @path is a mounted device.
562 * -ENOENT if @path does not match any device in the list.
564 static int btrfs_free_stale_devices(const char *path,
565 struct btrfs_device *skip_device)
567 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
568 struct btrfs_device *device, *tmp_device;
574 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
576 mutex_lock(&fs_devices->device_list_mutex);
577 list_for_each_entry_safe(device, tmp_device,
578 &fs_devices->devices, dev_list) {
579 if (skip_device && skip_device == device)
581 if (path && !device->name)
583 if (path && !device_path_matched(path, device))
585 if (fs_devices->opened) {
586 /* for an already deleted device return 0 */
587 if (path && ret != 0)
592 /* delete the stale device */
593 fs_devices->num_devices--;
594 list_del(&device->dev_list);
595 btrfs_free_device(device);
599 mutex_unlock(&fs_devices->device_list_mutex);
601 if (fs_devices->num_devices == 0) {
602 btrfs_sysfs_remove_fsid(fs_devices);
603 list_del(&fs_devices->fs_list);
604 free_fs_devices(fs_devices);
612 * This is only used on mount, and we are protected from competing things
613 * messing with our fs_devices by the uuid_mutex, thus we do not need the
614 * fs_devices->device_list_mutex here.
616 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
617 struct btrfs_device *device, fmode_t flags,
620 struct request_queue *q;
621 struct block_device *bdev;
622 struct btrfs_super_block *disk_super;
631 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
636 devid = btrfs_stack_device_id(&disk_super->dev_item);
637 if (devid != device->devid)
638 goto error_free_page;
640 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
641 goto error_free_page;
643 device->generation = btrfs_super_generation(disk_super);
645 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
646 if (btrfs_super_incompat_flags(disk_super) &
647 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
649 "BTRFS: Invalid seeding and uuid-changed device detected\n");
650 goto error_free_page;
653 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
654 fs_devices->seeding = true;
656 if (bdev_read_only(bdev))
657 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
659 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
662 q = bdev_get_queue(bdev);
663 if (!blk_queue_nonrot(q))
664 fs_devices->rotating = true;
667 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
668 device->mode = flags;
670 fs_devices->open_devices++;
671 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
672 device->devid != BTRFS_DEV_REPLACE_DEVID) {
673 fs_devices->rw_devices++;
674 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
676 btrfs_release_disk_super(disk_super);
681 btrfs_release_disk_super(disk_super);
682 blkdev_put(bdev, flags);
688 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
689 * being created with a disk that has already completed its fsid change. Such
690 * disk can belong to an fs which has its FSID changed or to one which doesn't.
691 * Handle both cases here.
693 static struct btrfs_fs_devices *find_fsid_inprogress(
694 struct btrfs_super_block *disk_super)
696 struct btrfs_fs_devices *fs_devices;
698 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
699 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
700 BTRFS_FSID_SIZE) != 0 &&
701 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
702 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
707 return find_fsid(disk_super->fsid, NULL);
711 static struct btrfs_fs_devices *find_fsid_changed(
712 struct btrfs_super_block *disk_super)
714 struct btrfs_fs_devices *fs_devices;
717 * Handles the case where scanned device is part of an fs that had
718 * multiple successful changes of FSID but curently device didn't
719 * observe it. Meaning our fsid will be different than theirs. We need
720 * to handle two subcases :
721 * 1 - The fs still continues to have different METADATA/FSID uuids.
722 * 2 - The fs is switched back to its original FSID (METADATA/FSID
725 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
727 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
728 BTRFS_FSID_SIZE) != 0 &&
729 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
730 BTRFS_FSID_SIZE) == 0 &&
731 memcmp(fs_devices->fsid, disk_super->fsid,
732 BTRFS_FSID_SIZE) != 0)
735 /* Unchanged UUIDs */
736 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
737 BTRFS_FSID_SIZE) == 0 &&
738 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
739 BTRFS_FSID_SIZE) == 0)
746 static struct btrfs_fs_devices *find_fsid_reverted_metadata(
747 struct btrfs_super_block *disk_super)
749 struct btrfs_fs_devices *fs_devices;
752 * Handle the case where the scanned device is part of an fs whose last
753 * metadata UUID change reverted it to the original FSID. At the same
754 * time * fs_devices was first created by another constitutent device
755 * which didn't fully observe the operation. This results in an
756 * btrfs_fs_devices created with metadata/fsid different AND
757 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
758 * fs_devices equal to the FSID of the disk.
760 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
761 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
762 BTRFS_FSID_SIZE) != 0 &&
763 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
764 BTRFS_FSID_SIZE) == 0 &&
765 fs_devices->fsid_change)
772 * Add new device to list of registered devices
775 * device pointer which was just added or updated when successful
776 * error pointer when failed
778 static noinline struct btrfs_device *device_list_add(const char *path,
779 struct btrfs_super_block *disk_super,
780 bool *new_device_added)
782 struct btrfs_device *device;
783 struct btrfs_fs_devices *fs_devices = NULL;
784 struct rcu_string *name;
785 u64 found_transid = btrfs_super_generation(disk_super);
786 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
787 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
788 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
789 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
790 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
792 if (fsid_change_in_progress) {
793 if (!has_metadata_uuid)
794 fs_devices = find_fsid_inprogress(disk_super);
796 fs_devices = find_fsid_changed(disk_super);
797 } else if (has_metadata_uuid) {
798 fs_devices = find_fsid_with_metadata_uuid(disk_super);
800 fs_devices = find_fsid_reverted_metadata(disk_super);
802 fs_devices = find_fsid(disk_super->fsid, NULL);
807 if (has_metadata_uuid)
808 fs_devices = alloc_fs_devices(disk_super->fsid,
809 disk_super->metadata_uuid);
811 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
813 if (IS_ERR(fs_devices))
814 return ERR_CAST(fs_devices);
816 fs_devices->fsid_change = fsid_change_in_progress;
818 mutex_lock(&fs_devices->device_list_mutex);
819 list_add(&fs_devices->fs_list, &fs_uuids);
823 mutex_lock(&fs_devices->device_list_mutex);
824 device = btrfs_find_device(fs_devices, devid,
825 disk_super->dev_item.uuid, NULL, false);
828 * If this disk has been pulled into an fs devices created by
829 * a device which had the CHANGING_FSID_V2 flag then replace the
830 * metadata_uuid/fsid values of the fs_devices.
832 if (fs_devices->fsid_change &&
833 found_transid > fs_devices->latest_generation) {
834 memcpy(fs_devices->fsid, disk_super->fsid,
837 if (has_metadata_uuid)
838 memcpy(fs_devices->metadata_uuid,
839 disk_super->metadata_uuid,
842 memcpy(fs_devices->metadata_uuid,
843 disk_super->fsid, BTRFS_FSID_SIZE);
845 fs_devices->fsid_change = false;
850 if (fs_devices->opened) {
851 mutex_unlock(&fs_devices->device_list_mutex);
852 return ERR_PTR(-EBUSY);
855 device = btrfs_alloc_device(NULL, &devid,
856 disk_super->dev_item.uuid);
857 if (IS_ERR(device)) {
858 mutex_unlock(&fs_devices->device_list_mutex);
859 /* we can safely leave the fs_devices entry around */
863 name = rcu_string_strdup(path, GFP_NOFS);
865 btrfs_free_device(device);
866 mutex_unlock(&fs_devices->device_list_mutex);
867 return ERR_PTR(-ENOMEM);
869 rcu_assign_pointer(device->name, name);
871 list_add_rcu(&device->dev_list, &fs_devices->devices);
872 fs_devices->num_devices++;
874 device->fs_devices = fs_devices;
875 *new_device_added = true;
877 if (disk_super->label[0])
879 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
880 disk_super->label, devid, found_transid, path,
881 current->comm, task_pid_nr(current));
884 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
885 disk_super->fsid, devid, found_transid, path,
886 current->comm, task_pid_nr(current));
888 } else if (!device->name || strcmp(device->name->str, path)) {
890 * When FS is already mounted.
891 * 1. If you are here and if the device->name is NULL that
892 * means this device was missing at time of FS mount.
893 * 2. If you are here and if the device->name is different
894 * from 'path' that means either
895 * a. The same device disappeared and reappeared with
897 * b. The missing-disk-which-was-replaced, has
900 * We must allow 1 and 2a above. But 2b would be a spurious
903 * Further in case of 1 and 2a above, the disk at 'path'
904 * would have missed some transaction when it was away and
905 * in case of 2a the stale bdev has to be updated as well.
906 * 2b must not be allowed at all time.
910 * For now, we do allow update to btrfs_fs_device through the
911 * btrfs dev scan cli after FS has been mounted. We're still
912 * tracking a problem where systems fail mount by subvolume id
913 * when we reject replacement on a mounted FS.
915 if (!fs_devices->opened && found_transid < device->generation) {
917 * That is if the FS is _not_ mounted and if you
918 * are here, that means there is more than one
919 * disk with same uuid and devid.We keep the one
920 * with larger generation number or the last-in if
921 * generation are equal.
923 mutex_unlock(&fs_devices->device_list_mutex);
924 return ERR_PTR(-EEXIST);
928 * We are going to replace the device path for a given devid,
929 * make sure it's the same device if the device is mounted
932 struct block_device *path_bdev;
934 path_bdev = lookup_bdev(path);
935 if (IS_ERR(path_bdev)) {
936 mutex_unlock(&fs_devices->device_list_mutex);
937 return ERR_CAST(path_bdev);
940 if (device->bdev != path_bdev) {
942 mutex_unlock(&fs_devices->device_list_mutex);
944 * device->fs_info may not be reliable here, so
945 * pass in a NULL instead. This avoids a
946 * possible use-after-free when the fs_info and
947 * fs_info->sb are already torn down.
949 btrfs_warn_in_rcu(NULL,
950 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
951 path, devid, found_transid,
953 task_pid_nr(current));
954 return ERR_PTR(-EEXIST);
957 btrfs_info_in_rcu(device->fs_info,
958 "devid %llu device path %s changed to %s scanned by %s (%d)",
959 devid, rcu_str_deref(device->name),
961 task_pid_nr(current));
964 name = rcu_string_strdup(path, GFP_NOFS);
966 mutex_unlock(&fs_devices->device_list_mutex);
967 return ERR_PTR(-ENOMEM);
969 rcu_string_free(device->name);
970 rcu_assign_pointer(device->name, name);
971 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
972 fs_devices->missing_devices--;
973 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
978 * Unmount does not free the btrfs_device struct but would zero
979 * generation along with most of the other members. So just update
980 * it back. We need it to pick the disk with largest generation
983 if (!fs_devices->opened) {
984 device->generation = found_transid;
985 fs_devices->latest_generation = max_t(u64, found_transid,
986 fs_devices->latest_generation);
989 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
991 mutex_unlock(&fs_devices->device_list_mutex);
995 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
997 struct btrfs_fs_devices *fs_devices;
998 struct btrfs_device *device;
999 struct btrfs_device *orig_dev;
1002 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1003 if (IS_ERR(fs_devices))
1006 mutex_lock(&orig->device_list_mutex);
1007 fs_devices->total_devices = orig->total_devices;
1009 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1010 struct rcu_string *name;
1012 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1014 if (IS_ERR(device)) {
1015 ret = PTR_ERR(device);
1020 * This is ok to do without rcu read locked because we hold the
1021 * uuid mutex so nothing we touch in here is going to disappear.
1023 if (orig_dev->name) {
1024 name = rcu_string_strdup(orig_dev->name->str,
1027 btrfs_free_device(device);
1031 rcu_assign_pointer(device->name, name);
1034 list_add(&device->dev_list, &fs_devices->devices);
1035 device->fs_devices = fs_devices;
1036 fs_devices->num_devices++;
1038 mutex_unlock(&orig->device_list_mutex);
1041 mutex_unlock(&orig->device_list_mutex);
1042 free_fs_devices(fs_devices);
1043 return ERR_PTR(ret);
1046 static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
1047 int step, struct btrfs_device **latest_dev)
1049 struct btrfs_device *device, *next;
1051 /* This is the initialized path, it is safe to release the devices. */
1052 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1053 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
1054 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1055 &device->dev_state) &&
1056 !test_bit(BTRFS_DEV_STATE_MISSING,
1057 &device->dev_state) &&
1059 device->generation > (*latest_dev)->generation)) {
1060 *latest_dev = device;
1066 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1067 * in btrfs_init_dev_replace() so just continue.
1069 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1073 blkdev_put(device->bdev, device->mode);
1074 device->bdev = NULL;
1075 fs_devices->open_devices--;
1077 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1078 list_del_init(&device->dev_alloc_list);
1079 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1081 list_del_init(&device->dev_list);
1082 fs_devices->num_devices--;
1083 btrfs_free_device(device);
1089 * After we have read the system tree and know devids belonging to this
1090 * filesystem, remove the device which does not belong there.
1092 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1094 struct btrfs_device *latest_dev = NULL;
1095 struct btrfs_fs_devices *seed_dev;
1097 mutex_lock(&uuid_mutex);
1098 __btrfs_free_extra_devids(fs_devices, step, &latest_dev);
1100 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1101 __btrfs_free_extra_devids(seed_dev, step, &latest_dev);
1103 fs_devices->latest_bdev = latest_dev->bdev;
1105 mutex_unlock(&uuid_mutex);
1108 static void btrfs_close_bdev(struct btrfs_device *device)
1113 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1114 sync_blockdev(device->bdev);
1115 invalidate_bdev(device->bdev);
1118 blkdev_put(device->bdev, device->mode);
1121 static void btrfs_close_one_device(struct btrfs_device *device)
1123 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1125 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1126 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1127 list_del_init(&device->dev_alloc_list);
1128 fs_devices->rw_devices--;
1131 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1132 fs_devices->missing_devices--;
1134 btrfs_close_bdev(device);
1136 fs_devices->open_devices--;
1137 device->bdev = NULL;
1139 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1141 device->fs_info = NULL;
1142 atomic_set(&device->dev_stats_ccnt, 0);
1143 extent_io_tree_release(&device->alloc_state);
1145 /* Verify the device is back in a pristine state */
1146 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1147 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1148 ASSERT(list_empty(&device->dev_alloc_list));
1149 ASSERT(list_empty(&device->post_commit_list));
1150 ASSERT(atomic_read(&device->reada_in_flight) == 0);
1153 static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
1155 struct btrfs_device *device, *tmp;
1157 lockdep_assert_held(&uuid_mutex);
1159 if (--fs_devices->opened > 0)
1162 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
1163 btrfs_close_one_device(device);
1165 WARN_ON(fs_devices->open_devices);
1166 WARN_ON(fs_devices->rw_devices);
1167 fs_devices->opened = 0;
1168 fs_devices->seeding = false;
1169 fs_devices->fs_info = NULL;
1172 void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1175 struct btrfs_fs_devices *tmp;
1177 mutex_lock(&uuid_mutex);
1178 close_fs_devices(fs_devices);
1179 if (!fs_devices->opened)
1180 list_splice_init(&fs_devices->seed_list, &list);
1182 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
1183 close_fs_devices(fs_devices);
1184 list_del(&fs_devices->seed_list);
1185 free_fs_devices(fs_devices);
1187 mutex_unlock(&uuid_mutex);
1190 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1191 fmode_t flags, void *holder)
1193 struct btrfs_device *device;
1194 struct btrfs_device *latest_dev = NULL;
1195 struct btrfs_device *tmp_device;
1197 flags |= FMODE_EXCL;
1199 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1203 ret = btrfs_open_one_device(fs_devices, device, flags, holder);
1205 (!latest_dev || device->generation > latest_dev->generation)) {
1206 latest_dev = device;
1207 } else if (ret == -ENODATA) {
1208 fs_devices->num_devices--;
1209 list_del(&device->dev_list);
1210 btrfs_free_device(device);
1213 if (fs_devices->open_devices == 0)
1216 fs_devices->opened = 1;
1217 fs_devices->latest_bdev = latest_dev->bdev;
1218 fs_devices->total_rw_bytes = 0;
1219 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1224 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1226 struct btrfs_device *dev1, *dev2;
1228 dev1 = list_entry(a, struct btrfs_device, dev_list);
1229 dev2 = list_entry(b, struct btrfs_device, dev_list);
1231 if (dev1->devid < dev2->devid)
1233 else if (dev1->devid > dev2->devid)
1238 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1239 fmode_t flags, void *holder)
1243 lockdep_assert_held(&uuid_mutex);
1245 * The device_list_mutex cannot be taken here in case opening the
1246 * underlying device takes further locks like bd_mutex.
1248 * We also don't need the lock here as this is called during mount and
1249 * exclusion is provided by uuid_mutex
1252 if (fs_devices->opened) {
1253 fs_devices->opened++;
1256 list_sort(NULL, &fs_devices->devices, devid_cmp);
1257 ret = open_fs_devices(fs_devices, flags, holder);
1263 void btrfs_release_disk_super(struct btrfs_super_block *super)
1265 struct page *page = virt_to_page(super);
1270 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1273 struct btrfs_super_block *disk_super;
1278 /* make sure our super fits in the device */
1279 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1280 return ERR_PTR(-EINVAL);
1282 /* make sure our super fits in the page */
1283 if (sizeof(*disk_super) > PAGE_SIZE)
1284 return ERR_PTR(-EINVAL);
1286 /* make sure our super doesn't straddle pages on disk */
1287 index = bytenr >> PAGE_SHIFT;
1288 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index)
1289 return ERR_PTR(-EINVAL);
1291 /* pull in the page with our super */
1292 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL);
1295 return ERR_CAST(page);
1297 p = page_address(page);
1299 /* align our pointer to the offset of the super block */
1300 disk_super = p + offset_in_page(bytenr);
1302 if (btrfs_super_bytenr(disk_super) != bytenr ||
1303 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1304 btrfs_release_disk_super(p);
1305 return ERR_PTR(-EINVAL);
1308 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1])
1309 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0;
1314 int btrfs_forget_devices(const char *path)
1318 mutex_lock(&uuid_mutex);
1319 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1320 mutex_unlock(&uuid_mutex);
1326 * Look for a btrfs signature on a device. This may be called out of the mount path
1327 * and we are not allowed to call set_blocksize during the scan. The superblock
1328 * is read via pagecache
1330 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1333 struct btrfs_super_block *disk_super;
1334 bool new_device_added = false;
1335 struct btrfs_device *device = NULL;
1336 struct block_device *bdev;
1339 lockdep_assert_held(&uuid_mutex);
1342 * we would like to check all the supers, but that would make
1343 * a btrfs mount succeed after a mkfs from a different FS.
1344 * So, we need to add a special mount option to scan for
1345 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1347 bytenr = btrfs_sb_offset(0);
1348 flags |= FMODE_EXCL;
1350 bdev = blkdev_get_by_path(path, flags, holder);
1352 return ERR_CAST(bdev);
1354 disk_super = btrfs_read_disk_super(bdev, bytenr);
1355 if (IS_ERR(disk_super)) {
1356 device = ERR_CAST(disk_super);
1357 goto error_bdev_put;
1360 device = device_list_add(path, disk_super, &new_device_added);
1361 if (!IS_ERR(device)) {
1362 if (new_device_added)
1363 btrfs_free_stale_devices(path, device);
1366 btrfs_release_disk_super(disk_super);
1369 blkdev_put(bdev, flags);
1375 * Try to find a chunk that intersects [start, start + len] range and when one
1376 * such is found, record the end of it in *start
1378 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1381 u64 physical_start, physical_end;
1383 lockdep_assert_held(&device->fs_info->chunk_mutex);
1385 if (!find_first_extent_bit(&device->alloc_state, *start,
1386 &physical_start, &physical_end,
1387 CHUNK_ALLOCATED, NULL)) {
1389 if (in_range(physical_start, *start, len) ||
1390 in_range(*start, physical_start,
1391 physical_end - physical_start)) {
1392 *start = physical_end + 1;
1399 static u64 dev_extent_search_start(struct btrfs_device *device, u64 start)
1401 switch (device->fs_devices->chunk_alloc_policy) {
1402 case BTRFS_CHUNK_ALLOC_REGULAR:
1404 * We don't want to overwrite the superblock on the drive nor
1405 * any area used by the boot loader (grub for example), so we
1406 * make sure to start at an offset of at least 1MB.
1408 return max_t(u64, start, SZ_1M);
1415 * dev_extent_hole_check - check if specified hole is suitable for allocation
1416 * @device: the device which we have the hole
1417 * @hole_start: starting position of the hole
1418 * @hole_size: the size of the hole
1419 * @num_bytes: the size of the free space that we need
1421 * This function may modify @hole_start and @hole_end to reflect the suitable
1422 * position for allocation. Returns 1 if hole position is updated, 0 otherwise.
1424 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1425 u64 *hole_size, u64 num_bytes)
1427 bool changed = false;
1428 u64 hole_end = *hole_start + *hole_size;
1431 * Check before we set max_hole_start, otherwise we could end up
1432 * sending back this offset anyway.
1434 if (contains_pending_extent(device, hole_start, *hole_size)) {
1435 if (hole_end >= *hole_start)
1436 *hole_size = hole_end - *hole_start;
1442 switch (device->fs_devices->chunk_alloc_policy) {
1443 case BTRFS_CHUNK_ALLOC_REGULAR:
1444 /* No extra check */
1454 * find_free_dev_extent_start - find free space in the specified device
1455 * @device: the device which we search the free space in
1456 * @num_bytes: the size of the free space that we need
1457 * @search_start: the position from which to begin the search
1458 * @start: store the start of the free space.
1459 * @len: the size of the free space. that we find, or the size
1460 * of the max free space if we don't find suitable free space
1462 * this uses a pretty simple search, the expectation is that it is
1463 * called very infrequently and that a given device has a small number
1466 * @start is used to store the start of the free space if we find. But if we
1467 * don't find suitable free space, it will be used to store the start position
1468 * of the max free space.
1470 * @len is used to store the size of the free space that we find.
1471 * But if we don't find suitable free space, it is used to store the size of
1472 * the max free space.
1474 * NOTE: This function will search *commit* root of device tree, and does extra
1475 * check to ensure dev extents are not double allocated.
1476 * This makes the function safe to allocate dev extents but may not report
1477 * correct usable device space, as device extent freed in current transaction
1478 * is not reported as avaiable.
1480 static int find_free_dev_extent_start(struct btrfs_device *device,
1481 u64 num_bytes, u64 search_start, u64 *start,
1484 struct btrfs_fs_info *fs_info = device->fs_info;
1485 struct btrfs_root *root = fs_info->dev_root;
1486 struct btrfs_key key;
1487 struct btrfs_dev_extent *dev_extent;
1488 struct btrfs_path *path;
1493 u64 search_end = device->total_bytes;
1496 struct extent_buffer *l;
1498 search_start = dev_extent_search_start(device, search_start);
1500 path = btrfs_alloc_path();
1504 max_hole_start = search_start;
1508 if (search_start >= search_end ||
1509 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1514 path->reada = READA_FORWARD;
1515 path->search_commit_root = 1;
1516 path->skip_locking = 1;
1518 key.objectid = device->devid;
1519 key.offset = search_start;
1520 key.type = BTRFS_DEV_EXTENT_KEY;
1522 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1526 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1533 slot = path->slots[0];
1534 if (slot >= btrfs_header_nritems(l)) {
1535 ret = btrfs_next_leaf(root, path);
1543 btrfs_item_key_to_cpu(l, &key, slot);
1545 if (key.objectid < device->devid)
1548 if (key.objectid > device->devid)
1551 if (key.type != BTRFS_DEV_EXTENT_KEY)
1554 if (key.offset > search_start) {
1555 hole_size = key.offset - search_start;
1556 dev_extent_hole_check(device, &search_start, &hole_size,
1559 if (hole_size > max_hole_size) {
1560 max_hole_start = search_start;
1561 max_hole_size = hole_size;
1565 * If this free space is greater than which we need,
1566 * it must be the max free space that we have found
1567 * until now, so max_hole_start must point to the start
1568 * of this free space and the length of this free space
1569 * is stored in max_hole_size. Thus, we return
1570 * max_hole_start and max_hole_size and go back to the
1573 if (hole_size >= num_bytes) {
1579 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1580 extent_end = key.offset + btrfs_dev_extent_length(l,
1582 if (extent_end > search_start)
1583 search_start = extent_end;
1590 * At this point, search_start should be the end of
1591 * allocated dev extents, and when shrinking the device,
1592 * search_end may be smaller than search_start.
1594 if (search_end > search_start) {
1595 hole_size = search_end - search_start;
1596 if (dev_extent_hole_check(device, &search_start, &hole_size,
1598 btrfs_release_path(path);
1602 if (hole_size > max_hole_size) {
1603 max_hole_start = search_start;
1604 max_hole_size = hole_size;
1609 if (max_hole_size < num_bytes)
1615 btrfs_free_path(path);
1616 *start = max_hole_start;
1618 *len = max_hole_size;
1622 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1623 u64 *start, u64 *len)
1625 /* FIXME use last free of some kind */
1626 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1629 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1630 struct btrfs_device *device,
1631 u64 start, u64 *dev_extent_len)
1633 struct btrfs_fs_info *fs_info = device->fs_info;
1634 struct btrfs_root *root = fs_info->dev_root;
1636 struct btrfs_path *path;
1637 struct btrfs_key key;
1638 struct btrfs_key found_key;
1639 struct extent_buffer *leaf = NULL;
1640 struct btrfs_dev_extent *extent = NULL;
1642 path = btrfs_alloc_path();
1646 key.objectid = device->devid;
1648 key.type = BTRFS_DEV_EXTENT_KEY;
1650 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1652 ret = btrfs_previous_item(root, path, key.objectid,
1653 BTRFS_DEV_EXTENT_KEY);
1656 leaf = path->nodes[0];
1657 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1658 extent = btrfs_item_ptr(leaf, path->slots[0],
1659 struct btrfs_dev_extent);
1660 BUG_ON(found_key.offset > start || found_key.offset +
1661 btrfs_dev_extent_length(leaf, extent) < start);
1663 btrfs_release_path(path);
1665 } else if (ret == 0) {
1666 leaf = path->nodes[0];
1667 extent = btrfs_item_ptr(leaf, path->slots[0],
1668 struct btrfs_dev_extent);
1670 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1674 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1676 ret = btrfs_del_item(trans, root, path);
1678 btrfs_handle_fs_error(fs_info, ret,
1679 "Failed to remove dev extent item");
1681 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1684 btrfs_free_path(path);
1688 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1689 struct btrfs_device *device,
1690 u64 chunk_offset, u64 start, u64 num_bytes)
1693 struct btrfs_path *path;
1694 struct btrfs_fs_info *fs_info = device->fs_info;
1695 struct btrfs_root *root = fs_info->dev_root;
1696 struct btrfs_dev_extent *extent;
1697 struct extent_buffer *leaf;
1698 struct btrfs_key key;
1700 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1701 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1702 path = btrfs_alloc_path();
1706 key.objectid = device->devid;
1708 key.type = BTRFS_DEV_EXTENT_KEY;
1709 ret = btrfs_insert_empty_item(trans, root, path, &key,
1714 leaf = path->nodes[0];
1715 extent = btrfs_item_ptr(leaf, path->slots[0],
1716 struct btrfs_dev_extent);
1717 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1718 BTRFS_CHUNK_TREE_OBJECTID);
1719 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1720 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1721 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1723 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1724 btrfs_mark_buffer_dirty(leaf);
1726 btrfs_free_path(path);
1730 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1732 struct extent_map_tree *em_tree;
1733 struct extent_map *em;
1737 em_tree = &fs_info->mapping_tree;
1738 read_lock(&em_tree->lock);
1739 n = rb_last(&em_tree->map.rb_root);
1741 em = rb_entry(n, struct extent_map, rb_node);
1742 ret = em->start + em->len;
1744 read_unlock(&em_tree->lock);
1749 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1753 struct btrfs_key key;
1754 struct btrfs_key found_key;
1755 struct btrfs_path *path;
1757 path = btrfs_alloc_path();
1761 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1762 key.type = BTRFS_DEV_ITEM_KEY;
1763 key.offset = (u64)-1;
1765 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1771 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1776 ret = btrfs_previous_item(fs_info->chunk_root, path,
1777 BTRFS_DEV_ITEMS_OBJECTID,
1778 BTRFS_DEV_ITEM_KEY);
1782 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1784 *devid_ret = found_key.offset + 1;
1788 btrfs_free_path(path);
1793 * the device information is stored in the chunk root
1794 * the btrfs_device struct should be fully filled in
1796 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1797 struct btrfs_device *device)
1800 struct btrfs_path *path;
1801 struct btrfs_dev_item *dev_item;
1802 struct extent_buffer *leaf;
1803 struct btrfs_key key;
1806 path = btrfs_alloc_path();
1810 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1811 key.type = BTRFS_DEV_ITEM_KEY;
1812 key.offset = device->devid;
1814 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1815 &key, sizeof(*dev_item));
1819 leaf = path->nodes[0];
1820 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1822 btrfs_set_device_id(leaf, dev_item, device->devid);
1823 btrfs_set_device_generation(leaf, dev_item, 0);
1824 btrfs_set_device_type(leaf, dev_item, device->type);
1825 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1826 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1827 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1828 btrfs_set_device_total_bytes(leaf, dev_item,
1829 btrfs_device_get_disk_total_bytes(device));
1830 btrfs_set_device_bytes_used(leaf, dev_item,
1831 btrfs_device_get_bytes_used(device));
1832 btrfs_set_device_group(leaf, dev_item, 0);
1833 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1834 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1835 btrfs_set_device_start_offset(leaf, dev_item, 0);
1837 ptr = btrfs_device_uuid(dev_item);
1838 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1839 ptr = btrfs_device_fsid(dev_item);
1840 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1841 ptr, BTRFS_FSID_SIZE);
1842 btrfs_mark_buffer_dirty(leaf);
1846 btrfs_free_path(path);
1851 * Function to update ctime/mtime for a given device path.
1852 * Mainly used for ctime/mtime based probe like libblkid.
1854 static void update_dev_time(const char *path_name)
1858 filp = filp_open(path_name, O_RDWR, 0);
1861 file_update_time(filp);
1862 filp_close(filp, NULL);
1865 static int btrfs_rm_dev_item(struct btrfs_device *device)
1867 struct btrfs_root *root = device->fs_info->chunk_root;
1869 struct btrfs_path *path;
1870 struct btrfs_key key;
1871 struct btrfs_trans_handle *trans;
1873 path = btrfs_alloc_path();
1877 trans = btrfs_start_transaction(root, 0);
1878 if (IS_ERR(trans)) {
1879 btrfs_free_path(path);
1880 return PTR_ERR(trans);
1882 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1883 key.type = BTRFS_DEV_ITEM_KEY;
1884 key.offset = device->devid;
1886 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1890 btrfs_abort_transaction(trans, ret);
1891 btrfs_end_transaction(trans);
1895 ret = btrfs_del_item(trans, root, path);
1897 btrfs_abort_transaction(trans, ret);
1898 btrfs_end_transaction(trans);
1902 btrfs_free_path(path);
1904 ret = btrfs_commit_transaction(trans);
1909 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1910 * filesystem. It's up to the caller to adjust that number regarding eg. device
1913 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1921 seq = read_seqbegin(&fs_info->profiles_lock);
1923 all_avail = fs_info->avail_data_alloc_bits |
1924 fs_info->avail_system_alloc_bits |
1925 fs_info->avail_metadata_alloc_bits;
1926 } while (read_seqretry(&fs_info->profiles_lock, seq));
1928 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1929 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1932 if (num_devices < btrfs_raid_array[i].devs_min) {
1933 int ret = btrfs_raid_array[i].mindev_error;
1943 static struct btrfs_device * btrfs_find_next_active_device(
1944 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1946 struct btrfs_device *next_device;
1948 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1949 if (next_device != device &&
1950 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1951 && next_device->bdev)
1959 * Helper function to check if the given device is part of s_bdev / latest_bdev
1960 * and replace it with the provided or the next active device, in the context
1961 * where this function called, there should be always be another device (or
1962 * this_dev) which is active.
1964 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
1965 struct btrfs_device *next_device)
1967 struct btrfs_fs_info *fs_info = device->fs_info;
1970 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1972 ASSERT(next_device);
1974 if (fs_info->sb->s_bdev &&
1975 (fs_info->sb->s_bdev == device->bdev))
1976 fs_info->sb->s_bdev = next_device->bdev;
1978 if (fs_info->fs_devices->latest_bdev == device->bdev)
1979 fs_info->fs_devices->latest_bdev = next_device->bdev;
1983 * Return btrfs_fs_devices::num_devices excluding the device that's being
1984 * currently replaced.
1986 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1988 u64 num_devices = fs_info->fs_devices->num_devices;
1990 down_read(&fs_info->dev_replace.rwsem);
1991 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1992 ASSERT(num_devices > 1);
1995 up_read(&fs_info->dev_replace.rwsem);
2000 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info,
2001 struct block_device *bdev,
2002 const char *device_path)
2004 struct btrfs_super_block *disk_super;
2010 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2014 disk_super = btrfs_read_dev_one_super(bdev, copy_num);
2015 if (IS_ERR(disk_super))
2018 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
2020 page = virt_to_page(disk_super);
2021 set_page_dirty(page);
2023 /* write_on_page() unlocks the page */
2024 ret = write_one_page(page);
2027 "error clearing superblock number %d (%d)",
2029 btrfs_release_disk_super(disk_super);
2033 /* Notify udev that device has changed */
2034 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2036 /* Update ctime/mtime for device path for libblkid */
2037 update_dev_time(device_path);
2040 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2043 struct btrfs_device *device;
2044 struct btrfs_fs_devices *cur_devices;
2045 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2049 mutex_lock(&uuid_mutex);
2051 num_devices = btrfs_num_devices(fs_info);
2053 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2057 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2059 if (IS_ERR(device)) {
2060 if (PTR_ERR(device) == -ENOENT &&
2061 strcmp(device_path, "missing") == 0)
2062 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2064 ret = PTR_ERR(device);
2068 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2069 btrfs_warn_in_rcu(fs_info,
2070 "cannot remove device %s (devid %llu) due to active swapfile",
2071 rcu_str_deref(device->name), device->devid);
2076 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2077 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2081 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2082 fs_info->fs_devices->rw_devices == 1) {
2083 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2087 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2088 mutex_lock(&fs_info->chunk_mutex);
2089 list_del_init(&device->dev_alloc_list);
2090 device->fs_devices->rw_devices--;
2091 mutex_unlock(&fs_info->chunk_mutex);
2094 mutex_unlock(&uuid_mutex);
2095 ret = btrfs_shrink_device(device, 0);
2097 btrfs_reada_remove_dev(device);
2098 mutex_lock(&uuid_mutex);
2103 * TODO: the superblock still includes this device in its num_devices
2104 * counter although write_all_supers() is not locked out. This
2105 * could give a filesystem state which requires a degraded mount.
2107 ret = btrfs_rm_dev_item(device);
2111 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2112 btrfs_scrub_cancel_dev(device);
2115 * the device list mutex makes sure that we don't change
2116 * the device list while someone else is writing out all
2117 * the device supers. Whoever is writing all supers, should
2118 * lock the device list mutex before getting the number of
2119 * devices in the super block (super_copy). Conversely,
2120 * whoever updates the number of devices in the super block
2121 * (super_copy) should hold the device list mutex.
2125 * In normal cases the cur_devices == fs_devices. But in case
2126 * of deleting a seed device, the cur_devices should point to
2127 * its own fs_devices listed under the fs_devices->seed.
2129 cur_devices = device->fs_devices;
2130 mutex_lock(&fs_devices->device_list_mutex);
2131 list_del_rcu(&device->dev_list);
2133 cur_devices->num_devices--;
2134 cur_devices->total_devices--;
2135 /* Update total_devices of the parent fs_devices if it's seed */
2136 if (cur_devices != fs_devices)
2137 fs_devices->total_devices--;
2139 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2140 cur_devices->missing_devices--;
2142 btrfs_assign_next_active_device(device, NULL);
2145 cur_devices->open_devices--;
2146 /* remove sysfs entry */
2147 btrfs_sysfs_remove_device(device);
2150 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2151 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2152 mutex_unlock(&fs_devices->device_list_mutex);
2155 * at this point, the device is zero sized and detached from
2156 * the devices list. All that's left is to zero out the old
2157 * supers and free the device.
2159 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2160 btrfs_scratch_superblocks(fs_info, device->bdev,
2163 btrfs_close_bdev(device);
2165 btrfs_free_device(device);
2167 if (cur_devices->open_devices == 0) {
2168 list_del_init(&cur_devices->seed_list);
2169 close_fs_devices(cur_devices);
2170 free_fs_devices(cur_devices);
2174 mutex_unlock(&uuid_mutex);
2178 btrfs_reada_undo_remove_dev(device);
2179 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2180 mutex_lock(&fs_info->chunk_mutex);
2181 list_add(&device->dev_alloc_list,
2182 &fs_devices->alloc_list);
2183 device->fs_devices->rw_devices++;
2184 mutex_unlock(&fs_info->chunk_mutex);
2189 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2191 struct btrfs_fs_devices *fs_devices;
2193 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2196 * in case of fs with no seed, srcdev->fs_devices will point
2197 * to fs_devices of fs_info. However when the dev being replaced is
2198 * a seed dev it will point to the seed's local fs_devices. In short
2199 * srcdev will have its correct fs_devices in both the cases.
2201 fs_devices = srcdev->fs_devices;
2203 list_del_rcu(&srcdev->dev_list);
2204 list_del(&srcdev->dev_alloc_list);
2205 fs_devices->num_devices--;
2206 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2207 fs_devices->missing_devices--;
2209 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2210 fs_devices->rw_devices--;
2213 fs_devices->open_devices--;
2216 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2218 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2220 mutex_lock(&uuid_mutex);
2222 btrfs_close_bdev(srcdev);
2224 btrfs_free_device(srcdev);
2226 /* if this is no devs we rather delete the fs_devices */
2227 if (!fs_devices->num_devices) {
2229 * On a mounted FS, num_devices can't be zero unless it's a
2230 * seed. In case of a seed device being replaced, the replace
2231 * target added to the sprout FS, so there will be no more
2232 * device left under the seed FS.
2234 ASSERT(fs_devices->seeding);
2236 list_del_init(&fs_devices->seed_list);
2237 close_fs_devices(fs_devices);
2238 free_fs_devices(fs_devices);
2240 mutex_unlock(&uuid_mutex);
2243 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2245 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2247 mutex_lock(&fs_devices->device_list_mutex);
2249 btrfs_sysfs_remove_device(tgtdev);
2252 fs_devices->open_devices--;
2254 fs_devices->num_devices--;
2256 btrfs_assign_next_active_device(tgtdev, NULL);
2258 list_del_rcu(&tgtdev->dev_list);
2260 mutex_unlock(&fs_devices->device_list_mutex);
2263 * The update_dev_time() with in btrfs_scratch_superblocks()
2264 * may lead to a call to btrfs_show_devname() which will try
2265 * to hold device_list_mutex. And here this device
2266 * is already out of device list, so we don't have to hold
2267 * the device_list_mutex lock.
2269 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev,
2272 btrfs_close_bdev(tgtdev);
2274 btrfs_free_device(tgtdev);
2277 static struct btrfs_device *btrfs_find_device_by_path(
2278 struct btrfs_fs_info *fs_info, const char *device_path)
2281 struct btrfs_super_block *disk_super;
2284 struct block_device *bdev;
2285 struct btrfs_device *device;
2287 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2288 fs_info->bdev_holder, 0, &bdev, &disk_super);
2290 return ERR_PTR(ret);
2292 devid = btrfs_stack_device_id(&disk_super->dev_item);
2293 dev_uuid = disk_super->dev_item.uuid;
2294 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2295 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2296 disk_super->metadata_uuid, true);
2298 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2299 disk_super->fsid, true);
2301 btrfs_release_disk_super(disk_super);
2303 device = ERR_PTR(-ENOENT);
2304 blkdev_put(bdev, FMODE_READ);
2309 * Lookup a device given by device id, or the path if the id is 0.
2311 struct btrfs_device *btrfs_find_device_by_devspec(
2312 struct btrfs_fs_info *fs_info, u64 devid,
2313 const char *device_path)
2315 struct btrfs_device *device;
2318 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2321 return ERR_PTR(-ENOENT);
2325 if (!device_path || !device_path[0])
2326 return ERR_PTR(-EINVAL);
2328 if (strcmp(device_path, "missing") == 0) {
2329 /* Find first missing device */
2330 list_for_each_entry(device, &fs_info->fs_devices->devices,
2332 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2333 &device->dev_state) && !device->bdev)
2336 return ERR_PTR(-ENOENT);
2339 return btrfs_find_device_by_path(fs_info, device_path);
2343 * does all the dirty work required for changing file system's UUID.
2345 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2347 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2348 struct btrfs_fs_devices *old_devices;
2349 struct btrfs_fs_devices *seed_devices;
2350 struct btrfs_super_block *disk_super = fs_info->super_copy;
2351 struct btrfs_device *device;
2354 lockdep_assert_held(&uuid_mutex);
2355 if (!fs_devices->seeding)
2359 * Private copy of the seed devices, anchored at
2360 * fs_info->fs_devices->seed_list
2362 seed_devices = alloc_fs_devices(NULL, NULL);
2363 if (IS_ERR(seed_devices))
2364 return PTR_ERR(seed_devices);
2367 * It's necessary to retain a copy of the original seed fs_devices in
2368 * fs_uuids so that filesystems which have been seeded can successfully
2369 * reference the seed device from open_seed_devices. This also supports
2372 old_devices = clone_fs_devices(fs_devices);
2373 if (IS_ERR(old_devices)) {
2374 kfree(seed_devices);
2375 return PTR_ERR(old_devices);
2378 list_add(&old_devices->fs_list, &fs_uuids);
2380 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2381 seed_devices->opened = 1;
2382 INIT_LIST_HEAD(&seed_devices->devices);
2383 INIT_LIST_HEAD(&seed_devices->alloc_list);
2384 mutex_init(&seed_devices->device_list_mutex);
2386 mutex_lock(&fs_devices->device_list_mutex);
2387 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2389 list_for_each_entry(device, &seed_devices->devices, dev_list)
2390 device->fs_devices = seed_devices;
2392 fs_devices->seeding = false;
2393 fs_devices->num_devices = 0;
2394 fs_devices->open_devices = 0;
2395 fs_devices->missing_devices = 0;
2396 fs_devices->rotating = false;
2397 list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2399 generate_random_uuid(fs_devices->fsid);
2400 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2401 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2402 mutex_unlock(&fs_devices->device_list_mutex);
2404 super_flags = btrfs_super_flags(disk_super) &
2405 ~BTRFS_SUPER_FLAG_SEEDING;
2406 btrfs_set_super_flags(disk_super, super_flags);
2412 * Store the expected generation for seed devices in device items.
2414 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2416 struct btrfs_fs_info *fs_info = trans->fs_info;
2417 struct btrfs_root *root = fs_info->chunk_root;
2418 struct btrfs_path *path;
2419 struct extent_buffer *leaf;
2420 struct btrfs_dev_item *dev_item;
2421 struct btrfs_device *device;
2422 struct btrfs_key key;
2423 u8 fs_uuid[BTRFS_FSID_SIZE];
2424 u8 dev_uuid[BTRFS_UUID_SIZE];
2428 path = btrfs_alloc_path();
2432 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2434 key.type = BTRFS_DEV_ITEM_KEY;
2437 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2441 leaf = path->nodes[0];
2443 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2444 ret = btrfs_next_leaf(root, path);
2449 leaf = path->nodes[0];
2450 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2451 btrfs_release_path(path);
2455 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2456 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2457 key.type != BTRFS_DEV_ITEM_KEY)
2460 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2461 struct btrfs_dev_item);
2462 devid = btrfs_device_id(leaf, dev_item);
2463 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2465 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2467 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2469 BUG_ON(!device); /* Logic error */
2471 if (device->fs_devices->seeding) {
2472 btrfs_set_device_generation(leaf, dev_item,
2473 device->generation);
2474 btrfs_mark_buffer_dirty(leaf);
2482 btrfs_free_path(path);
2486 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2488 struct btrfs_root *root = fs_info->dev_root;
2489 struct request_queue *q;
2490 struct btrfs_trans_handle *trans;
2491 struct btrfs_device *device;
2492 struct block_device *bdev;
2493 struct super_block *sb = fs_info->sb;
2494 struct rcu_string *name;
2495 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2496 u64 orig_super_total_bytes;
2497 u64 orig_super_num_devices;
2498 int seeding_dev = 0;
2500 bool locked = false;
2502 if (sb_rdonly(sb) && !fs_devices->seeding)
2505 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2506 fs_info->bdev_holder);
2508 return PTR_ERR(bdev);
2510 if (fs_devices->seeding) {
2512 down_write(&sb->s_umount);
2513 mutex_lock(&uuid_mutex);
2517 sync_blockdev(bdev);
2520 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2521 if (device->bdev == bdev) {
2529 device = btrfs_alloc_device(fs_info, NULL, NULL);
2530 if (IS_ERR(device)) {
2531 /* we can safely leave the fs_devices entry around */
2532 ret = PTR_ERR(device);
2536 name = rcu_string_strdup(device_path, GFP_KERNEL);
2539 goto error_free_device;
2541 rcu_assign_pointer(device->name, name);
2543 trans = btrfs_start_transaction(root, 0);
2544 if (IS_ERR(trans)) {
2545 ret = PTR_ERR(trans);
2546 goto error_free_device;
2549 q = bdev_get_queue(bdev);
2550 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2551 device->generation = trans->transid;
2552 device->io_width = fs_info->sectorsize;
2553 device->io_align = fs_info->sectorsize;
2554 device->sector_size = fs_info->sectorsize;
2555 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2556 fs_info->sectorsize);
2557 device->disk_total_bytes = device->total_bytes;
2558 device->commit_total_bytes = device->total_bytes;
2559 device->fs_info = fs_info;
2560 device->bdev = bdev;
2561 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2562 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2563 device->mode = FMODE_EXCL;
2564 device->dev_stats_valid = 1;
2565 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2568 sb->s_flags &= ~SB_RDONLY;
2569 ret = btrfs_prepare_sprout(fs_info);
2571 btrfs_abort_transaction(trans, ret);
2576 device->fs_devices = fs_devices;
2578 mutex_lock(&fs_devices->device_list_mutex);
2579 mutex_lock(&fs_info->chunk_mutex);
2580 list_add_rcu(&device->dev_list, &fs_devices->devices);
2581 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2582 fs_devices->num_devices++;
2583 fs_devices->open_devices++;
2584 fs_devices->rw_devices++;
2585 fs_devices->total_devices++;
2586 fs_devices->total_rw_bytes += device->total_bytes;
2588 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2590 if (!blk_queue_nonrot(q))
2591 fs_devices->rotating = true;
2593 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2594 btrfs_set_super_total_bytes(fs_info->super_copy,
2595 round_down(orig_super_total_bytes + device->total_bytes,
2596 fs_info->sectorsize));
2598 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2599 btrfs_set_super_num_devices(fs_info->super_copy,
2600 orig_super_num_devices + 1);
2603 * we've got more storage, clear any full flags on the space
2606 btrfs_clear_space_info_full(fs_info);
2608 mutex_unlock(&fs_info->chunk_mutex);
2610 /* Add sysfs device entry */
2611 btrfs_sysfs_add_device(device);
2613 mutex_unlock(&fs_devices->device_list_mutex);
2616 mutex_lock(&fs_info->chunk_mutex);
2617 ret = init_first_rw_device(trans);
2618 mutex_unlock(&fs_info->chunk_mutex);
2620 btrfs_abort_transaction(trans, ret);
2625 ret = btrfs_add_dev_item(trans, device);
2627 btrfs_abort_transaction(trans, ret);
2632 ret = btrfs_finish_sprout(trans);
2634 btrfs_abort_transaction(trans, ret);
2639 * fs_devices now represents the newly sprouted filesystem and
2640 * its fsid has been changed by btrfs_prepare_sprout
2642 btrfs_sysfs_update_sprout_fsid(fs_devices);
2645 ret = btrfs_commit_transaction(trans);
2648 mutex_unlock(&uuid_mutex);
2649 up_write(&sb->s_umount);
2652 if (ret) /* transaction commit */
2655 ret = btrfs_relocate_sys_chunks(fs_info);
2657 btrfs_handle_fs_error(fs_info, ret,
2658 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2659 trans = btrfs_attach_transaction(root);
2660 if (IS_ERR(trans)) {
2661 if (PTR_ERR(trans) == -ENOENT)
2663 ret = PTR_ERR(trans);
2667 ret = btrfs_commit_transaction(trans);
2671 * Now that we have written a new super block to this device, check all
2672 * other fs_devices list if device_path alienates any other scanned
2674 * We can ignore the return value as it typically returns -EINVAL and
2675 * only succeeds if the device was an alien.
2677 btrfs_forget_devices(device_path);
2679 /* Update ctime/mtime for blkid or udev */
2680 update_dev_time(device_path);
2685 btrfs_sysfs_remove_device(device);
2686 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2687 mutex_lock(&fs_info->chunk_mutex);
2688 list_del_rcu(&device->dev_list);
2689 list_del(&device->dev_alloc_list);
2690 fs_info->fs_devices->num_devices--;
2691 fs_info->fs_devices->open_devices--;
2692 fs_info->fs_devices->rw_devices--;
2693 fs_info->fs_devices->total_devices--;
2694 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2695 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2696 btrfs_set_super_total_bytes(fs_info->super_copy,
2697 orig_super_total_bytes);
2698 btrfs_set_super_num_devices(fs_info->super_copy,
2699 orig_super_num_devices);
2700 mutex_unlock(&fs_info->chunk_mutex);
2701 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2704 sb->s_flags |= SB_RDONLY;
2706 btrfs_end_transaction(trans);
2708 btrfs_free_device(device);
2710 blkdev_put(bdev, FMODE_EXCL);
2712 mutex_unlock(&uuid_mutex);
2713 up_write(&sb->s_umount);
2718 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2719 struct btrfs_device *device)
2722 struct btrfs_path *path;
2723 struct btrfs_root *root = device->fs_info->chunk_root;
2724 struct btrfs_dev_item *dev_item;
2725 struct extent_buffer *leaf;
2726 struct btrfs_key key;
2728 path = btrfs_alloc_path();
2732 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2733 key.type = BTRFS_DEV_ITEM_KEY;
2734 key.offset = device->devid;
2736 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2745 leaf = path->nodes[0];
2746 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2748 btrfs_set_device_id(leaf, dev_item, device->devid);
2749 btrfs_set_device_type(leaf, dev_item, device->type);
2750 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2751 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2752 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2753 btrfs_set_device_total_bytes(leaf, dev_item,
2754 btrfs_device_get_disk_total_bytes(device));
2755 btrfs_set_device_bytes_used(leaf, dev_item,
2756 btrfs_device_get_bytes_used(device));
2757 btrfs_mark_buffer_dirty(leaf);
2760 btrfs_free_path(path);
2764 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2765 struct btrfs_device *device, u64 new_size)
2767 struct btrfs_fs_info *fs_info = device->fs_info;
2768 struct btrfs_super_block *super_copy = fs_info->super_copy;
2772 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2775 new_size = round_down(new_size, fs_info->sectorsize);
2777 mutex_lock(&fs_info->chunk_mutex);
2778 old_total = btrfs_super_total_bytes(super_copy);
2779 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2781 if (new_size <= device->total_bytes ||
2782 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2783 mutex_unlock(&fs_info->chunk_mutex);
2787 btrfs_set_super_total_bytes(super_copy,
2788 round_down(old_total + diff, fs_info->sectorsize));
2789 device->fs_devices->total_rw_bytes += diff;
2791 btrfs_device_set_total_bytes(device, new_size);
2792 btrfs_device_set_disk_total_bytes(device, new_size);
2793 btrfs_clear_space_info_full(device->fs_info);
2794 if (list_empty(&device->post_commit_list))
2795 list_add_tail(&device->post_commit_list,
2796 &trans->transaction->dev_update_list);
2797 mutex_unlock(&fs_info->chunk_mutex);
2799 return btrfs_update_device(trans, device);
2802 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2804 struct btrfs_fs_info *fs_info = trans->fs_info;
2805 struct btrfs_root *root = fs_info->chunk_root;
2807 struct btrfs_path *path;
2808 struct btrfs_key key;
2810 path = btrfs_alloc_path();
2814 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2815 key.offset = chunk_offset;
2816 key.type = BTRFS_CHUNK_ITEM_KEY;
2818 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2821 else if (ret > 0) { /* Logic error or corruption */
2822 btrfs_handle_fs_error(fs_info, -ENOENT,
2823 "Failed lookup while freeing chunk.");
2828 ret = btrfs_del_item(trans, root, path);
2830 btrfs_handle_fs_error(fs_info, ret,
2831 "Failed to delete chunk item.");
2833 btrfs_free_path(path);
2837 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2839 struct btrfs_super_block *super_copy = fs_info->super_copy;
2840 struct btrfs_disk_key *disk_key;
2841 struct btrfs_chunk *chunk;
2848 struct btrfs_key key;
2850 mutex_lock(&fs_info->chunk_mutex);
2851 array_size = btrfs_super_sys_array_size(super_copy);
2853 ptr = super_copy->sys_chunk_array;
2856 while (cur < array_size) {
2857 disk_key = (struct btrfs_disk_key *)ptr;
2858 btrfs_disk_key_to_cpu(&key, disk_key);
2860 len = sizeof(*disk_key);
2862 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2863 chunk = (struct btrfs_chunk *)(ptr + len);
2864 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2865 len += btrfs_chunk_item_size(num_stripes);
2870 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2871 key.offset == chunk_offset) {
2872 memmove(ptr, ptr + len, array_size - (cur + len));
2874 btrfs_set_super_sys_array_size(super_copy, array_size);
2880 mutex_unlock(&fs_info->chunk_mutex);
2885 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2886 * @logical: Logical block offset in bytes.
2887 * @length: Length of extent in bytes.
2889 * Return: Chunk mapping or ERR_PTR.
2891 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2892 u64 logical, u64 length)
2894 struct extent_map_tree *em_tree;
2895 struct extent_map *em;
2897 em_tree = &fs_info->mapping_tree;
2898 read_lock(&em_tree->lock);
2899 em = lookup_extent_mapping(em_tree, logical, length);
2900 read_unlock(&em_tree->lock);
2903 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2905 return ERR_PTR(-EINVAL);
2908 if (em->start > logical || em->start + em->len < logical) {
2910 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2911 logical, length, em->start, em->start + em->len);
2912 free_extent_map(em);
2913 return ERR_PTR(-EINVAL);
2916 /* callers are responsible for dropping em's ref. */
2920 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2922 struct btrfs_fs_info *fs_info = trans->fs_info;
2923 struct extent_map *em;
2924 struct map_lookup *map;
2925 u64 dev_extent_len = 0;
2927 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2929 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2932 * This is a logic error, but we don't want to just rely on the
2933 * user having built with ASSERT enabled, so if ASSERT doesn't
2934 * do anything we still error out.
2939 map = em->map_lookup;
2940 mutex_lock(&fs_info->chunk_mutex);
2941 check_system_chunk(trans, map->type);
2942 mutex_unlock(&fs_info->chunk_mutex);
2945 * Take the device list mutex to prevent races with the final phase of
2946 * a device replace operation that replaces the device object associated
2947 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2949 mutex_lock(&fs_devices->device_list_mutex);
2950 for (i = 0; i < map->num_stripes; i++) {
2951 struct btrfs_device *device = map->stripes[i].dev;
2952 ret = btrfs_free_dev_extent(trans, device,
2953 map->stripes[i].physical,
2956 mutex_unlock(&fs_devices->device_list_mutex);
2957 btrfs_abort_transaction(trans, ret);
2961 if (device->bytes_used > 0) {
2962 mutex_lock(&fs_info->chunk_mutex);
2963 btrfs_device_set_bytes_used(device,
2964 device->bytes_used - dev_extent_len);
2965 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2966 btrfs_clear_space_info_full(fs_info);
2967 mutex_unlock(&fs_info->chunk_mutex);
2970 ret = btrfs_update_device(trans, device);
2972 mutex_unlock(&fs_devices->device_list_mutex);
2973 btrfs_abort_transaction(trans, ret);
2977 mutex_unlock(&fs_devices->device_list_mutex);
2979 ret = btrfs_free_chunk(trans, chunk_offset);
2981 btrfs_abort_transaction(trans, ret);
2985 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2987 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2988 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2990 btrfs_abort_transaction(trans, ret);
2995 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2997 btrfs_abort_transaction(trans, ret);
3003 free_extent_map(em);
3007 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3009 struct btrfs_root *root = fs_info->chunk_root;
3010 struct btrfs_trans_handle *trans;
3011 struct btrfs_block_group *block_group;
3015 * Prevent races with automatic removal of unused block groups.
3016 * After we relocate and before we remove the chunk with offset
3017 * chunk_offset, automatic removal of the block group can kick in,
3018 * resulting in a failure when calling btrfs_remove_chunk() below.
3020 * Make sure to acquire this mutex before doing a tree search (dev
3021 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3022 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3023 * we release the path used to search the chunk/dev tree and before
3024 * the current task acquires this mutex and calls us.
3026 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3028 /* step one, relocate all the extents inside this chunk */
3029 btrfs_scrub_pause(fs_info);
3030 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3031 btrfs_scrub_continue(fs_info);
3035 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3038 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3039 btrfs_put_block_group(block_group);
3041 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3043 if (IS_ERR(trans)) {
3044 ret = PTR_ERR(trans);
3045 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3050 * step two, delete the device extents and the
3051 * chunk tree entries
3053 ret = btrfs_remove_chunk(trans, chunk_offset);
3054 btrfs_end_transaction(trans);
3058 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3060 struct btrfs_root *chunk_root = fs_info->chunk_root;
3061 struct btrfs_path *path;
3062 struct extent_buffer *leaf;
3063 struct btrfs_chunk *chunk;
3064 struct btrfs_key key;
3065 struct btrfs_key found_key;
3067 bool retried = false;
3071 path = btrfs_alloc_path();
3076 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3077 key.offset = (u64)-1;
3078 key.type = BTRFS_CHUNK_ITEM_KEY;
3081 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3082 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3084 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3087 BUG_ON(ret == 0); /* Corruption */
3089 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3092 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3098 leaf = path->nodes[0];
3099 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3101 chunk = btrfs_item_ptr(leaf, path->slots[0],
3102 struct btrfs_chunk);
3103 chunk_type = btrfs_chunk_type(leaf, chunk);
3104 btrfs_release_path(path);
3106 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3107 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3113 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3115 if (found_key.offset == 0)
3117 key.offset = found_key.offset - 1;
3120 if (failed && !retried) {
3124 } else if (WARN_ON(failed && retried)) {
3128 btrfs_free_path(path);
3133 * return 1 : allocate a data chunk successfully,
3134 * return <0: errors during allocating a data chunk,
3135 * return 0 : no need to allocate a data chunk.
3137 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3140 struct btrfs_block_group *cache;
3144 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3146 chunk_type = cache->flags;
3147 btrfs_put_block_group(cache);
3149 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3152 spin_lock(&fs_info->data_sinfo->lock);
3153 bytes_used = fs_info->data_sinfo->bytes_used;
3154 spin_unlock(&fs_info->data_sinfo->lock);
3157 struct btrfs_trans_handle *trans;
3160 trans = btrfs_join_transaction(fs_info->tree_root);
3162 return PTR_ERR(trans);
3164 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3165 btrfs_end_transaction(trans);
3174 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3175 struct btrfs_balance_control *bctl)
3177 struct btrfs_root *root = fs_info->tree_root;
3178 struct btrfs_trans_handle *trans;
3179 struct btrfs_balance_item *item;
3180 struct btrfs_disk_balance_args disk_bargs;
3181 struct btrfs_path *path;
3182 struct extent_buffer *leaf;
3183 struct btrfs_key key;
3186 path = btrfs_alloc_path();
3190 trans = btrfs_start_transaction(root, 0);
3191 if (IS_ERR(trans)) {
3192 btrfs_free_path(path);
3193 return PTR_ERR(trans);
3196 key.objectid = BTRFS_BALANCE_OBJECTID;
3197 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3200 ret = btrfs_insert_empty_item(trans, root, path, &key,
3205 leaf = path->nodes[0];
3206 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3208 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3210 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3211 btrfs_set_balance_data(leaf, item, &disk_bargs);
3212 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3213 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3214 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3215 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3217 btrfs_set_balance_flags(leaf, item, bctl->flags);
3219 btrfs_mark_buffer_dirty(leaf);
3221 btrfs_free_path(path);
3222 err = btrfs_commit_transaction(trans);
3228 static int del_balance_item(struct btrfs_fs_info *fs_info)
3230 struct btrfs_root *root = fs_info->tree_root;
3231 struct btrfs_trans_handle *trans;
3232 struct btrfs_path *path;
3233 struct btrfs_key key;
3236 path = btrfs_alloc_path();
3240 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3241 if (IS_ERR(trans)) {
3242 btrfs_free_path(path);
3243 return PTR_ERR(trans);
3246 key.objectid = BTRFS_BALANCE_OBJECTID;
3247 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3250 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3258 ret = btrfs_del_item(trans, root, path);
3260 btrfs_free_path(path);
3261 err = btrfs_commit_transaction(trans);
3268 * This is a heuristic used to reduce the number of chunks balanced on
3269 * resume after balance was interrupted.
3271 static void update_balance_args(struct btrfs_balance_control *bctl)
3274 * Turn on soft mode for chunk types that were being converted.
3276 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3277 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3278 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3279 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3280 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3281 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3284 * Turn on usage filter if is not already used. The idea is
3285 * that chunks that we have already balanced should be
3286 * reasonably full. Don't do it for chunks that are being
3287 * converted - that will keep us from relocating unconverted
3288 * (albeit full) chunks.
3290 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3291 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3292 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3293 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3294 bctl->data.usage = 90;
3296 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3297 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3298 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3299 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3300 bctl->sys.usage = 90;
3302 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3303 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3304 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3305 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3306 bctl->meta.usage = 90;
3311 * Clear the balance status in fs_info and delete the balance item from disk.
3313 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3315 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3318 BUG_ON(!fs_info->balance_ctl);
3320 spin_lock(&fs_info->balance_lock);
3321 fs_info->balance_ctl = NULL;
3322 spin_unlock(&fs_info->balance_lock);
3325 ret = del_balance_item(fs_info);
3327 btrfs_handle_fs_error(fs_info, ret, NULL);
3331 * Balance filters. Return 1 if chunk should be filtered out
3332 * (should not be balanced).
3334 static int chunk_profiles_filter(u64 chunk_type,
3335 struct btrfs_balance_args *bargs)
3337 chunk_type = chunk_to_extended(chunk_type) &
3338 BTRFS_EXTENDED_PROFILE_MASK;
3340 if (bargs->profiles & chunk_type)
3346 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3347 struct btrfs_balance_args *bargs)
3349 struct btrfs_block_group *cache;
3351 u64 user_thresh_min;
3352 u64 user_thresh_max;
3355 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3356 chunk_used = cache->used;
3358 if (bargs->usage_min == 0)
3359 user_thresh_min = 0;
3361 user_thresh_min = div_factor_fine(cache->length,
3364 if (bargs->usage_max == 0)
3365 user_thresh_max = 1;
3366 else if (bargs->usage_max > 100)
3367 user_thresh_max = cache->length;
3369 user_thresh_max = div_factor_fine(cache->length,
3372 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3375 btrfs_put_block_group(cache);
3379 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3380 u64 chunk_offset, struct btrfs_balance_args *bargs)
3382 struct btrfs_block_group *cache;
3383 u64 chunk_used, user_thresh;
3386 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3387 chunk_used = cache->used;
3389 if (bargs->usage_min == 0)
3391 else if (bargs->usage > 100)
3392 user_thresh = cache->length;
3394 user_thresh = div_factor_fine(cache->length, bargs->usage);
3396 if (chunk_used < user_thresh)
3399 btrfs_put_block_group(cache);
3403 static int chunk_devid_filter(struct extent_buffer *leaf,
3404 struct btrfs_chunk *chunk,
3405 struct btrfs_balance_args *bargs)
3407 struct btrfs_stripe *stripe;
3408 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3411 for (i = 0; i < num_stripes; i++) {
3412 stripe = btrfs_stripe_nr(chunk, i);
3413 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3420 static u64 calc_data_stripes(u64 type, int num_stripes)
3422 const int index = btrfs_bg_flags_to_raid_index(type);
3423 const int ncopies = btrfs_raid_array[index].ncopies;
3424 const int nparity = btrfs_raid_array[index].nparity;
3427 return num_stripes - nparity;
3429 return num_stripes / ncopies;
3432 /* [pstart, pend) */
3433 static int chunk_drange_filter(struct extent_buffer *leaf,
3434 struct btrfs_chunk *chunk,
3435 struct btrfs_balance_args *bargs)
3437 struct btrfs_stripe *stripe;
3438 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3445 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3448 type = btrfs_chunk_type(leaf, chunk);
3449 factor = calc_data_stripes(type, num_stripes);
3451 for (i = 0; i < num_stripes; i++) {
3452 stripe = btrfs_stripe_nr(chunk, i);
3453 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3456 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3457 stripe_length = btrfs_chunk_length(leaf, chunk);
3458 stripe_length = div_u64(stripe_length, factor);
3460 if (stripe_offset < bargs->pend &&
3461 stripe_offset + stripe_length > bargs->pstart)
3468 /* [vstart, vend) */
3469 static int chunk_vrange_filter(struct extent_buffer *leaf,
3470 struct btrfs_chunk *chunk,
3472 struct btrfs_balance_args *bargs)
3474 if (chunk_offset < bargs->vend &&
3475 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3476 /* at least part of the chunk is inside this vrange */
3482 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3483 struct btrfs_chunk *chunk,
3484 struct btrfs_balance_args *bargs)
3486 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3488 if (bargs->stripes_min <= num_stripes
3489 && num_stripes <= bargs->stripes_max)
3495 static int chunk_soft_convert_filter(u64 chunk_type,
3496 struct btrfs_balance_args *bargs)
3498 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3501 chunk_type = chunk_to_extended(chunk_type) &
3502 BTRFS_EXTENDED_PROFILE_MASK;
3504 if (bargs->target == chunk_type)
3510 static int should_balance_chunk(struct extent_buffer *leaf,
3511 struct btrfs_chunk *chunk, u64 chunk_offset)
3513 struct btrfs_fs_info *fs_info = leaf->fs_info;
3514 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3515 struct btrfs_balance_args *bargs = NULL;
3516 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3519 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3520 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3524 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3525 bargs = &bctl->data;
3526 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3528 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3529 bargs = &bctl->meta;
3531 /* profiles filter */
3532 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3533 chunk_profiles_filter(chunk_type, bargs)) {
3538 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3539 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3541 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3542 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3547 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3548 chunk_devid_filter(leaf, chunk, bargs)) {
3552 /* drange filter, makes sense only with devid filter */
3553 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3554 chunk_drange_filter(leaf, chunk, bargs)) {
3559 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3560 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3564 /* stripes filter */
3565 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3566 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3570 /* soft profile changing mode */
3571 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3572 chunk_soft_convert_filter(chunk_type, bargs)) {
3577 * limited by count, must be the last filter
3579 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3580 if (bargs->limit == 0)
3584 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3586 * Same logic as the 'limit' filter; the minimum cannot be
3587 * determined here because we do not have the global information
3588 * about the count of all chunks that satisfy the filters.
3590 if (bargs->limit_max == 0)
3599 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3601 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3602 struct btrfs_root *chunk_root = fs_info->chunk_root;
3604 struct btrfs_chunk *chunk;
3605 struct btrfs_path *path = NULL;
3606 struct btrfs_key key;
3607 struct btrfs_key found_key;
3608 struct extent_buffer *leaf;
3611 int enospc_errors = 0;
3612 bool counting = true;
3613 /* The single value limit and min/max limits use the same bytes in the */
3614 u64 limit_data = bctl->data.limit;
3615 u64 limit_meta = bctl->meta.limit;
3616 u64 limit_sys = bctl->sys.limit;
3620 int chunk_reserved = 0;
3622 path = btrfs_alloc_path();
3628 /* zero out stat counters */
3629 spin_lock(&fs_info->balance_lock);
3630 memset(&bctl->stat, 0, sizeof(bctl->stat));
3631 spin_unlock(&fs_info->balance_lock);
3635 * The single value limit and min/max limits use the same bytes
3638 bctl->data.limit = limit_data;
3639 bctl->meta.limit = limit_meta;
3640 bctl->sys.limit = limit_sys;
3642 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3643 key.offset = (u64)-1;
3644 key.type = BTRFS_CHUNK_ITEM_KEY;
3647 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3648 atomic_read(&fs_info->balance_cancel_req)) {
3653 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3654 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3656 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3661 * this shouldn't happen, it means the last relocate
3665 BUG(); /* FIXME break ? */
3667 ret = btrfs_previous_item(chunk_root, path, 0,
3668 BTRFS_CHUNK_ITEM_KEY);
3670 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3675 leaf = path->nodes[0];
3676 slot = path->slots[0];
3677 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3679 if (found_key.objectid != key.objectid) {
3680 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3684 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3685 chunk_type = btrfs_chunk_type(leaf, chunk);
3688 spin_lock(&fs_info->balance_lock);
3689 bctl->stat.considered++;
3690 spin_unlock(&fs_info->balance_lock);
3693 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3695 btrfs_release_path(path);
3697 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3702 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3703 spin_lock(&fs_info->balance_lock);
3704 bctl->stat.expected++;
3705 spin_unlock(&fs_info->balance_lock);
3707 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3709 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3711 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3718 * Apply limit_min filter, no need to check if the LIMITS
3719 * filter is used, limit_min is 0 by default
3721 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3722 count_data < bctl->data.limit_min)
3723 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3724 count_meta < bctl->meta.limit_min)
3725 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3726 count_sys < bctl->sys.limit_min)) {
3727 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3731 if (!chunk_reserved) {
3733 * We may be relocating the only data chunk we have,
3734 * which could potentially end up with losing data's
3735 * raid profile, so lets allocate an empty one in
3738 ret = btrfs_may_alloc_data_chunk(fs_info,
3741 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3743 } else if (ret == 1) {
3748 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3749 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3750 if (ret == -ENOSPC) {
3752 } else if (ret == -ETXTBSY) {
3754 "skipping relocation of block group %llu due to active swapfile",
3760 spin_lock(&fs_info->balance_lock);
3761 bctl->stat.completed++;
3762 spin_unlock(&fs_info->balance_lock);
3765 if (found_key.offset == 0)
3767 key.offset = found_key.offset - 1;
3771 btrfs_release_path(path);
3776 btrfs_free_path(path);
3777 if (enospc_errors) {
3778 btrfs_info(fs_info, "%d enospc errors during balance",
3788 * alloc_profile_is_valid - see if a given profile is valid and reduced
3789 * @flags: profile to validate
3790 * @extended: if true @flags is treated as an extended profile
3792 static int alloc_profile_is_valid(u64 flags, int extended)
3794 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3795 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3797 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3799 /* 1) check that all other bits are zeroed */
3803 /* 2) see if profile is reduced */
3805 return !extended; /* "0" is valid for usual profiles */
3807 return has_single_bit_set(flags);
3810 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3812 /* cancel requested || normal exit path */
3813 return atomic_read(&fs_info->balance_cancel_req) ||
3814 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3815 atomic_read(&fs_info->balance_cancel_req) == 0);
3819 * Validate target profile against allowed profiles and return true if it's OK.
3820 * Otherwise print the error message and return false.
3822 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
3823 const struct btrfs_balance_args *bargs,
3824 u64 allowed, const char *type)
3826 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3829 /* Profile is valid and does not have bits outside of the allowed set */
3830 if (alloc_profile_is_valid(bargs->target, 1) &&
3831 (bargs->target & ~allowed) == 0)
3834 btrfs_err(fs_info, "balance: invalid convert %s profile %s",
3835 type, btrfs_bg_type_to_raid_name(bargs->target));
3840 * Fill @buf with textual description of balance filter flags @bargs, up to
3841 * @size_buf including the terminating null. The output may be trimmed if it
3842 * does not fit into the provided buffer.
3844 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3848 u32 size_bp = size_buf;
3850 u64 flags = bargs->flags;
3851 char tmp_buf[128] = {'\0'};
3856 #define CHECK_APPEND_NOARG(a) \
3858 ret = snprintf(bp, size_bp, (a)); \
3859 if (ret < 0 || ret >= size_bp) \
3860 goto out_overflow; \
3865 #define CHECK_APPEND_1ARG(a, v1) \
3867 ret = snprintf(bp, size_bp, (a), (v1)); \
3868 if (ret < 0 || ret >= size_bp) \
3869 goto out_overflow; \
3874 #define CHECK_APPEND_2ARG(a, v1, v2) \
3876 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3877 if (ret < 0 || ret >= size_bp) \
3878 goto out_overflow; \
3883 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
3884 CHECK_APPEND_1ARG("convert=%s,",
3885 btrfs_bg_type_to_raid_name(bargs->target));
3887 if (flags & BTRFS_BALANCE_ARGS_SOFT)
3888 CHECK_APPEND_NOARG("soft,");
3890 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
3891 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
3893 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
3896 if (flags & BTRFS_BALANCE_ARGS_USAGE)
3897 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
3899 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
3900 CHECK_APPEND_2ARG("usage=%u..%u,",
3901 bargs->usage_min, bargs->usage_max);
3903 if (flags & BTRFS_BALANCE_ARGS_DEVID)
3904 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
3906 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
3907 CHECK_APPEND_2ARG("drange=%llu..%llu,",
3908 bargs->pstart, bargs->pend);
3910 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
3911 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
3912 bargs->vstart, bargs->vend);
3914 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
3915 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
3917 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
3918 CHECK_APPEND_2ARG("limit=%u..%u,",
3919 bargs->limit_min, bargs->limit_max);
3921 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
3922 CHECK_APPEND_2ARG("stripes=%u..%u,",
3923 bargs->stripes_min, bargs->stripes_max);
3925 #undef CHECK_APPEND_2ARG
3926 #undef CHECK_APPEND_1ARG
3927 #undef CHECK_APPEND_NOARG
3931 if (size_bp < size_buf)
3932 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
3937 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
3939 u32 size_buf = 1024;
3940 char tmp_buf[192] = {'\0'};
3943 u32 size_bp = size_buf;
3945 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3947 buf = kzalloc(size_buf, GFP_KERNEL);
3953 #define CHECK_APPEND_1ARG(a, v1) \
3955 ret = snprintf(bp, size_bp, (a), (v1)); \
3956 if (ret < 0 || ret >= size_bp) \
3957 goto out_overflow; \
3962 if (bctl->flags & BTRFS_BALANCE_FORCE)
3963 CHECK_APPEND_1ARG("%s", "-f ");
3965 if (bctl->flags & BTRFS_BALANCE_DATA) {
3966 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
3967 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
3970 if (bctl->flags & BTRFS_BALANCE_METADATA) {
3971 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
3972 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
3975 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
3976 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
3977 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
3980 #undef CHECK_APPEND_1ARG
3984 if (size_bp < size_buf)
3985 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
3986 btrfs_info(fs_info, "balance: %s %s",
3987 (bctl->flags & BTRFS_BALANCE_RESUME) ?
3988 "resume" : "start", buf);
3994 * Should be called with balance mutexe held
3996 int btrfs_balance(struct btrfs_fs_info *fs_info,
3997 struct btrfs_balance_control *bctl,
3998 struct btrfs_ioctl_balance_args *bargs)
4000 u64 meta_target, data_target;
4006 bool reducing_redundancy;
4009 if (btrfs_fs_closing(fs_info) ||
4010 atomic_read(&fs_info->balance_pause_req) ||
4011 btrfs_should_cancel_balance(fs_info)) {
4016 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4017 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4021 * In case of mixed groups both data and meta should be picked,
4022 * and identical options should be given for both of them.
4024 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4025 if (mixed && (bctl->flags & allowed)) {
4026 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4027 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4028 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4030 "balance: mixed groups data and metadata options must be the same");
4037 * rw_devices will not change at the moment, device add/delete/replace
4040 num_devices = fs_info->fs_devices->rw_devices;
4043 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4044 * special bit for it, to make it easier to distinguish. Thus we need
4045 * to set it manually, or balance would refuse the profile.
4047 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4048 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4049 if (num_devices >= btrfs_raid_array[i].devs_min)
4050 allowed |= btrfs_raid_array[i].bg_flag;
4052 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4053 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4054 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) {
4060 * Allow to reduce metadata or system integrity only if force set for
4061 * profiles with redundancy (copies, parity)
4064 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4065 if (btrfs_raid_array[i].ncopies >= 2 ||
4066 btrfs_raid_array[i].tolerated_failures >= 1)
4067 allowed |= btrfs_raid_array[i].bg_flag;
4070 seq = read_seqbegin(&fs_info->profiles_lock);
4072 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4073 (fs_info->avail_system_alloc_bits & allowed) &&
4074 !(bctl->sys.target & allowed)) ||
4075 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4076 (fs_info->avail_metadata_alloc_bits & allowed) &&
4077 !(bctl->meta.target & allowed)))
4078 reducing_redundancy = true;
4080 reducing_redundancy = false;
4082 /* if we're not converting, the target field is uninitialized */
4083 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4084 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4085 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4086 bctl->data.target : fs_info->avail_data_alloc_bits;
4087 } while (read_seqretry(&fs_info->profiles_lock, seq));
4089 if (reducing_redundancy) {
4090 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4092 "balance: force reducing metadata redundancy");
4095 "balance: reduces metadata redundancy, use --force if you want this");
4101 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4102 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4104 "balance: metadata profile %s has lower redundancy than data profile %s",
4105 btrfs_bg_type_to_raid_name(meta_target),
4106 btrfs_bg_type_to_raid_name(data_target));
4109 if (fs_info->send_in_progress) {
4110 btrfs_warn_rl(fs_info,
4111 "cannot run balance while send operations are in progress (%d in progress)",
4112 fs_info->send_in_progress);
4117 ret = insert_balance_item(fs_info, bctl);
4118 if (ret && ret != -EEXIST)
4121 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4122 BUG_ON(ret == -EEXIST);
4123 BUG_ON(fs_info->balance_ctl);
4124 spin_lock(&fs_info->balance_lock);
4125 fs_info->balance_ctl = bctl;
4126 spin_unlock(&fs_info->balance_lock);
4128 BUG_ON(ret != -EEXIST);
4129 spin_lock(&fs_info->balance_lock);
4130 update_balance_args(bctl);
4131 spin_unlock(&fs_info->balance_lock);
4134 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4135 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4136 describe_balance_start_or_resume(fs_info);
4137 mutex_unlock(&fs_info->balance_mutex);
4139 ret = __btrfs_balance(fs_info);
4141 mutex_lock(&fs_info->balance_mutex);
4142 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4143 btrfs_info(fs_info, "balance: paused");
4145 * Balance can be canceled by:
4147 * - Regular cancel request
4148 * Then ret == -ECANCELED and balance_cancel_req > 0
4150 * - Fatal signal to "btrfs" process
4151 * Either the signal caught by wait_reserve_ticket() and callers
4152 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4154 * Either way, in this case balance_cancel_req = 0, and
4155 * ret == -EINTR or ret == -ECANCELED.
4157 * So here we only check the return value to catch canceled balance.
4159 else if (ret == -ECANCELED || ret == -EINTR)
4160 btrfs_info(fs_info, "balance: canceled");
4162 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4164 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4167 memset(bargs, 0, sizeof(*bargs));
4168 btrfs_update_ioctl_balance_args(fs_info, bargs);
4171 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4172 balance_need_close(fs_info)) {
4173 reset_balance_state(fs_info);
4174 btrfs_exclop_finish(fs_info);
4177 wake_up(&fs_info->balance_wait_q);
4181 if (bctl->flags & BTRFS_BALANCE_RESUME)
4182 reset_balance_state(fs_info);
4185 btrfs_exclop_finish(fs_info);
4190 static int balance_kthread(void *data)
4192 struct btrfs_fs_info *fs_info = data;
4195 mutex_lock(&fs_info->balance_mutex);
4196 if (fs_info->balance_ctl)
4197 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4198 mutex_unlock(&fs_info->balance_mutex);
4203 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4205 struct task_struct *tsk;
4207 mutex_lock(&fs_info->balance_mutex);
4208 if (!fs_info->balance_ctl) {
4209 mutex_unlock(&fs_info->balance_mutex);
4212 mutex_unlock(&fs_info->balance_mutex);
4214 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4215 btrfs_info(fs_info, "balance: resume skipped");
4220 * A ro->rw remount sequence should continue with the paused balance
4221 * regardless of who pauses it, system or the user as of now, so set
4224 spin_lock(&fs_info->balance_lock);
4225 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4226 spin_unlock(&fs_info->balance_lock);
4228 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4229 return PTR_ERR_OR_ZERO(tsk);
4232 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4234 struct btrfs_balance_control *bctl;
4235 struct btrfs_balance_item *item;
4236 struct btrfs_disk_balance_args disk_bargs;
4237 struct btrfs_path *path;
4238 struct extent_buffer *leaf;
4239 struct btrfs_key key;
4242 path = btrfs_alloc_path();
4246 key.objectid = BTRFS_BALANCE_OBJECTID;
4247 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4250 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4253 if (ret > 0) { /* ret = -ENOENT; */
4258 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4264 leaf = path->nodes[0];
4265 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4267 bctl->flags = btrfs_balance_flags(leaf, item);
4268 bctl->flags |= BTRFS_BALANCE_RESUME;
4270 btrfs_balance_data(leaf, item, &disk_bargs);
4271 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4272 btrfs_balance_meta(leaf, item, &disk_bargs);
4273 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4274 btrfs_balance_sys(leaf, item, &disk_bargs);
4275 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4278 * This should never happen, as the paused balance state is recovered
4279 * during mount without any chance of other exclusive ops to collide.
4281 * This gives the exclusive op status to balance and keeps in paused
4282 * state until user intervention (cancel or umount). If the ownership
4283 * cannot be assigned, show a message but do not fail. The balance
4284 * is in a paused state and must have fs_info::balance_ctl properly
4287 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
4289 "balance: cannot set exclusive op status, resume manually");
4291 mutex_lock(&fs_info->balance_mutex);
4292 BUG_ON(fs_info->balance_ctl);
4293 spin_lock(&fs_info->balance_lock);
4294 fs_info->balance_ctl = bctl;
4295 spin_unlock(&fs_info->balance_lock);
4296 mutex_unlock(&fs_info->balance_mutex);
4298 btrfs_free_path(path);
4302 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4306 mutex_lock(&fs_info->balance_mutex);
4307 if (!fs_info->balance_ctl) {
4308 mutex_unlock(&fs_info->balance_mutex);
4312 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4313 atomic_inc(&fs_info->balance_pause_req);
4314 mutex_unlock(&fs_info->balance_mutex);
4316 wait_event(fs_info->balance_wait_q,
4317 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4319 mutex_lock(&fs_info->balance_mutex);
4320 /* we are good with balance_ctl ripped off from under us */
4321 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4322 atomic_dec(&fs_info->balance_pause_req);
4327 mutex_unlock(&fs_info->balance_mutex);
4331 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4333 mutex_lock(&fs_info->balance_mutex);
4334 if (!fs_info->balance_ctl) {
4335 mutex_unlock(&fs_info->balance_mutex);
4340 * A paused balance with the item stored on disk can be resumed at
4341 * mount time if the mount is read-write. Otherwise it's still paused
4342 * and we must not allow cancelling as it deletes the item.
4344 if (sb_rdonly(fs_info->sb)) {
4345 mutex_unlock(&fs_info->balance_mutex);
4349 atomic_inc(&fs_info->balance_cancel_req);
4351 * if we are running just wait and return, balance item is
4352 * deleted in btrfs_balance in this case
4354 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4355 mutex_unlock(&fs_info->balance_mutex);
4356 wait_event(fs_info->balance_wait_q,
4357 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4358 mutex_lock(&fs_info->balance_mutex);
4360 mutex_unlock(&fs_info->balance_mutex);
4362 * Lock released to allow other waiters to continue, we'll
4363 * reexamine the status again.
4365 mutex_lock(&fs_info->balance_mutex);
4367 if (fs_info->balance_ctl) {
4368 reset_balance_state(fs_info);
4369 btrfs_exclop_finish(fs_info);
4370 btrfs_info(fs_info, "balance: canceled");
4374 BUG_ON(fs_info->balance_ctl ||
4375 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4376 atomic_dec(&fs_info->balance_cancel_req);
4377 mutex_unlock(&fs_info->balance_mutex);
4381 int btrfs_uuid_scan_kthread(void *data)
4383 struct btrfs_fs_info *fs_info = data;
4384 struct btrfs_root *root = fs_info->tree_root;
4385 struct btrfs_key key;
4386 struct btrfs_path *path = NULL;
4388 struct extent_buffer *eb;
4390 struct btrfs_root_item root_item;
4392 struct btrfs_trans_handle *trans = NULL;
4393 bool closing = false;
4395 path = btrfs_alloc_path();
4402 key.type = BTRFS_ROOT_ITEM_KEY;
4406 if (btrfs_fs_closing(fs_info)) {
4410 ret = btrfs_search_forward(root, &key, path,
4411 BTRFS_OLDEST_GENERATION);
4418 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4419 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4420 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4421 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4424 eb = path->nodes[0];
4425 slot = path->slots[0];
4426 item_size = btrfs_item_size_nr(eb, slot);
4427 if (item_size < sizeof(root_item))
4430 read_extent_buffer(eb, &root_item,
4431 btrfs_item_ptr_offset(eb, slot),
4432 (int)sizeof(root_item));
4433 if (btrfs_root_refs(&root_item) == 0)
4436 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4437 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4441 btrfs_release_path(path);
4443 * 1 - subvol uuid item
4444 * 1 - received_subvol uuid item
4446 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4447 if (IS_ERR(trans)) {
4448 ret = PTR_ERR(trans);
4456 btrfs_release_path(path);
4457 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4458 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4459 BTRFS_UUID_KEY_SUBVOL,
4462 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4468 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4469 ret = btrfs_uuid_tree_add(trans,
4470 root_item.received_uuid,
4471 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4474 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4481 btrfs_release_path(path);
4483 ret = btrfs_end_transaction(trans);
4489 if (key.offset < (u64)-1) {
4491 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4493 key.type = BTRFS_ROOT_ITEM_KEY;
4494 } else if (key.objectid < (u64)-1) {
4496 key.type = BTRFS_ROOT_ITEM_KEY;
4505 btrfs_free_path(path);
4506 if (trans && !IS_ERR(trans))
4507 btrfs_end_transaction(trans);
4509 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4511 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4512 up(&fs_info->uuid_tree_rescan_sem);
4516 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4518 struct btrfs_trans_handle *trans;
4519 struct btrfs_root *tree_root = fs_info->tree_root;
4520 struct btrfs_root *uuid_root;
4521 struct task_struct *task;
4528 trans = btrfs_start_transaction(tree_root, 2);
4530 return PTR_ERR(trans);
4532 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4533 if (IS_ERR(uuid_root)) {
4534 ret = PTR_ERR(uuid_root);
4535 btrfs_abort_transaction(trans, ret);
4536 btrfs_end_transaction(trans);
4540 fs_info->uuid_root = uuid_root;
4542 ret = btrfs_commit_transaction(trans);
4546 down(&fs_info->uuid_tree_rescan_sem);
4547 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4549 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4550 btrfs_warn(fs_info, "failed to start uuid_scan task");
4551 up(&fs_info->uuid_tree_rescan_sem);
4552 return PTR_ERR(task);
4559 * shrinking a device means finding all of the device extents past
4560 * the new size, and then following the back refs to the chunks.
4561 * The chunk relocation code actually frees the device extent
4563 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4565 struct btrfs_fs_info *fs_info = device->fs_info;
4566 struct btrfs_root *root = fs_info->dev_root;
4567 struct btrfs_trans_handle *trans;
4568 struct btrfs_dev_extent *dev_extent = NULL;
4569 struct btrfs_path *path;
4575 bool retried = false;
4576 struct extent_buffer *l;
4577 struct btrfs_key key;
4578 struct btrfs_super_block *super_copy = fs_info->super_copy;
4579 u64 old_total = btrfs_super_total_bytes(super_copy);
4580 u64 old_size = btrfs_device_get_total_bytes(device);
4584 new_size = round_down(new_size, fs_info->sectorsize);
4586 diff = round_down(old_size - new_size, fs_info->sectorsize);
4588 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4591 path = btrfs_alloc_path();
4595 path->reada = READA_BACK;
4597 trans = btrfs_start_transaction(root, 0);
4598 if (IS_ERR(trans)) {
4599 btrfs_free_path(path);
4600 return PTR_ERR(trans);
4603 mutex_lock(&fs_info->chunk_mutex);
4605 btrfs_device_set_total_bytes(device, new_size);
4606 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4607 device->fs_devices->total_rw_bytes -= diff;
4608 atomic64_sub(diff, &fs_info->free_chunk_space);
4612 * Once the device's size has been set to the new size, ensure all
4613 * in-memory chunks are synced to disk so that the loop below sees them
4614 * and relocates them accordingly.
4616 if (contains_pending_extent(device, &start, diff)) {
4617 mutex_unlock(&fs_info->chunk_mutex);
4618 ret = btrfs_commit_transaction(trans);
4622 mutex_unlock(&fs_info->chunk_mutex);
4623 btrfs_end_transaction(trans);
4627 key.objectid = device->devid;
4628 key.offset = (u64)-1;
4629 key.type = BTRFS_DEV_EXTENT_KEY;
4632 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4633 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4635 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4639 ret = btrfs_previous_item(root, path, 0, key.type);
4641 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4646 btrfs_release_path(path);
4651 slot = path->slots[0];
4652 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4654 if (key.objectid != device->devid) {
4655 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4656 btrfs_release_path(path);
4660 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4661 length = btrfs_dev_extent_length(l, dev_extent);
4663 if (key.offset + length <= new_size) {
4664 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4665 btrfs_release_path(path);
4669 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4670 btrfs_release_path(path);
4673 * We may be relocating the only data chunk we have,
4674 * which could potentially end up with losing data's
4675 * raid profile, so lets allocate an empty one in
4678 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4680 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4684 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4685 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4686 if (ret == -ENOSPC) {
4689 if (ret == -ETXTBSY) {
4691 "could not shrink block group %llu due to active swapfile",
4696 } while (key.offset-- > 0);
4698 if (failed && !retried) {
4702 } else if (failed && retried) {
4707 /* Shrinking succeeded, else we would be at "done". */
4708 trans = btrfs_start_transaction(root, 0);
4709 if (IS_ERR(trans)) {
4710 ret = PTR_ERR(trans);
4714 mutex_lock(&fs_info->chunk_mutex);
4715 /* Clear all state bits beyond the shrunk device size */
4716 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4719 btrfs_device_set_disk_total_bytes(device, new_size);
4720 if (list_empty(&device->post_commit_list))
4721 list_add_tail(&device->post_commit_list,
4722 &trans->transaction->dev_update_list);
4724 WARN_ON(diff > old_total);
4725 btrfs_set_super_total_bytes(super_copy,
4726 round_down(old_total - diff, fs_info->sectorsize));
4727 mutex_unlock(&fs_info->chunk_mutex);
4729 /* Now btrfs_update_device() will change the on-disk size. */
4730 ret = btrfs_update_device(trans, device);
4732 btrfs_abort_transaction(trans, ret);
4733 btrfs_end_transaction(trans);
4735 ret = btrfs_commit_transaction(trans);
4738 btrfs_free_path(path);
4740 mutex_lock(&fs_info->chunk_mutex);
4741 btrfs_device_set_total_bytes(device, old_size);
4742 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4743 device->fs_devices->total_rw_bytes += diff;
4744 atomic64_add(diff, &fs_info->free_chunk_space);
4745 mutex_unlock(&fs_info->chunk_mutex);
4750 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4751 struct btrfs_key *key,
4752 struct btrfs_chunk *chunk, int item_size)
4754 struct btrfs_super_block *super_copy = fs_info->super_copy;
4755 struct btrfs_disk_key disk_key;
4759 mutex_lock(&fs_info->chunk_mutex);
4760 array_size = btrfs_super_sys_array_size(super_copy);
4761 if (array_size + item_size + sizeof(disk_key)
4762 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4763 mutex_unlock(&fs_info->chunk_mutex);
4767 ptr = super_copy->sys_chunk_array + array_size;
4768 btrfs_cpu_key_to_disk(&disk_key, key);
4769 memcpy(ptr, &disk_key, sizeof(disk_key));
4770 ptr += sizeof(disk_key);
4771 memcpy(ptr, chunk, item_size);
4772 item_size += sizeof(disk_key);
4773 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4774 mutex_unlock(&fs_info->chunk_mutex);
4780 * sort the devices in descending order by max_avail, total_avail
4782 static int btrfs_cmp_device_info(const void *a, const void *b)
4784 const struct btrfs_device_info *di_a = a;
4785 const struct btrfs_device_info *di_b = b;
4787 if (di_a->max_avail > di_b->max_avail)
4789 if (di_a->max_avail < di_b->max_avail)
4791 if (di_a->total_avail > di_b->total_avail)
4793 if (di_a->total_avail < di_b->total_avail)
4798 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4800 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4803 btrfs_set_fs_incompat(info, RAID56);
4806 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
4808 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
4811 btrfs_set_fs_incompat(info, RAID1C34);
4815 * Structure used internally for __btrfs_alloc_chunk() function.
4816 * Wraps needed parameters.
4818 struct alloc_chunk_ctl {
4821 /* Total number of stripes to allocate */
4823 /* sub_stripes info for map */
4825 /* Stripes per device */
4827 /* Maximum number of devices to use */
4829 /* Minimum number of devices to use */
4831 /* ndevs has to be a multiple of this */
4833 /* Number of copies */
4835 /* Number of stripes worth of bytes to store parity information */
4837 u64 max_stripe_size;
4845 static void init_alloc_chunk_ctl_policy_regular(
4846 struct btrfs_fs_devices *fs_devices,
4847 struct alloc_chunk_ctl *ctl)
4849 u64 type = ctl->type;
4851 if (type & BTRFS_BLOCK_GROUP_DATA) {
4852 ctl->max_stripe_size = SZ_1G;
4853 ctl->max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4854 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4855 /* For larger filesystems, use larger metadata chunks */
4856 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4857 ctl->max_stripe_size = SZ_1G;
4859 ctl->max_stripe_size = SZ_256M;
4860 ctl->max_chunk_size = ctl->max_stripe_size;
4861 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4862 ctl->max_stripe_size = SZ_32M;
4863 ctl->max_chunk_size = 2 * ctl->max_stripe_size;
4864 ctl->devs_max = min_t(int, ctl->devs_max,
4865 BTRFS_MAX_DEVS_SYS_CHUNK);
4870 /* We don't want a chunk larger than 10% of writable space */
4871 ctl->max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4872 ctl->max_chunk_size);
4873 ctl->dev_extent_min = BTRFS_STRIPE_LEN * ctl->dev_stripes;
4876 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
4877 struct alloc_chunk_ctl *ctl)
4879 int index = btrfs_bg_flags_to_raid_index(ctl->type);
4881 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
4882 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
4883 ctl->devs_max = btrfs_raid_array[index].devs_max;
4885 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
4886 ctl->devs_min = btrfs_raid_array[index].devs_min;
4887 ctl->devs_increment = btrfs_raid_array[index].devs_increment;
4888 ctl->ncopies = btrfs_raid_array[index].ncopies;
4889 ctl->nparity = btrfs_raid_array[index].nparity;
4892 switch (fs_devices->chunk_alloc_policy) {
4893 case BTRFS_CHUNK_ALLOC_REGULAR:
4894 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
4901 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
4902 struct alloc_chunk_ctl *ctl,
4903 struct btrfs_device_info *devices_info)
4905 struct btrfs_fs_info *info = fs_devices->fs_info;
4906 struct btrfs_device *device;
4908 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
4915 * in the first pass through the devices list, we gather information
4916 * about the available holes on each device.
4918 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4919 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4921 "BTRFS: read-only device in alloc_list\n");
4925 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4926 &device->dev_state) ||
4927 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4930 if (device->total_bytes > device->bytes_used)
4931 total_avail = device->total_bytes - device->bytes_used;
4935 /* If there is no space on this device, skip it. */
4936 if (total_avail < ctl->dev_extent_min)
4939 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
4941 if (ret && ret != -ENOSPC)
4945 max_avail = dev_extent_want;
4947 if (max_avail < ctl->dev_extent_min) {
4948 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4950 "%s: devid %llu has no free space, have=%llu want=%llu",
4951 __func__, device->devid, max_avail,
4952 ctl->dev_extent_min);
4956 if (ndevs == fs_devices->rw_devices) {
4957 WARN(1, "%s: found more than %llu devices\n",
4958 __func__, fs_devices->rw_devices);
4961 devices_info[ndevs].dev_offset = dev_offset;
4962 devices_info[ndevs].max_avail = max_avail;
4963 devices_info[ndevs].total_avail = total_avail;
4964 devices_info[ndevs].dev = device;
4970 * now sort the devices by hole size / available space
4972 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4973 btrfs_cmp_device_info, NULL);
4978 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
4979 struct btrfs_device_info *devices_info)
4981 /* Number of stripes that count for block group size */
4985 * The primary goal is to maximize the number of stripes, so use as
4986 * many devices as possible, even if the stripes are not maximum sized.
4988 * The DUP profile stores more than one stripe per device, the
4989 * max_avail is the total size so we have to adjust.
4991 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
4993 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
4995 /* This will have to be fixed for RAID1 and RAID10 over more drives */
4996 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
4999 * Use the number of data stripes to figure out how big this chunk is
5000 * really going to be in terms of logical address space, and compare
5001 * that answer with the max chunk size. If it's higher, we try to
5002 * reduce stripe_size.
5004 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5006 * Reduce stripe_size, round it up to a 16MB boundary again and
5007 * then use it, unless it ends up being even bigger than the
5008 * previous value we had already.
5010 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5011 data_stripes), SZ_16M),
5015 /* Align to BTRFS_STRIPE_LEN */
5016 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5017 ctl->chunk_size = ctl->stripe_size * data_stripes;
5022 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5023 struct alloc_chunk_ctl *ctl,
5024 struct btrfs_device_info *devices_info)
5026 struct btrfs_fs_info *info = fs_devices->fs_info;
5029 * Round down to number of usable stripes, devs_increment can be any
5030 * number so we can't use round_down() that requires power of 2, while
5031 * rounddown is safe.
5033 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5035 if (ctl->ndevs < ctl->devs_min) {
5036 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5038 "%s: not enough devices with free space: have=%d minimum required=%d",
5039 __func__, ctl->ndevs, ctl->devs_min);
5044 ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5046 switch (fs_devices->chunk_alloc_policy) {
5047 case BTRFS_CHUNK_ALLOC_REGULAR:
5048 return decide_stripe_size_regular(ctl, devices_info);
5054 static int create_chunk(struct btrfs_trans_handle *trans,
5055 struct alloc_chunk_ctl *ctl,
5056 struct btrfs_device_info *devices_info)
5058 struct btrfs_fs_info *info = trans->fs_info;
5059 struct map_lookup *map = NULL;
5060 struct extent_map_tree *em_tree;
5061 struct extent_map *em;
5062 u64 start = ctl->start;
5063 u64 type = ctl->type;
5068 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS);
5071 map->num_stripes = ctl->num_stripes;
5073 for (i = 0; i < ctl->ndevs; ++i) {
5074 for (j = 0; j < ctl->dev_stripes; ++j) {
5075 int s = i * ctl->dev_stripes + j;
5076 map->stripes[s].dev = devices_info[i].dev;
5077 map->stripes[s].physical = devices_info[i].dev_offset +
5078 j * ctl->stripe_size;
5081 map->stripe_len = BTRFS_STRIPE_LEN;
5082 map->io_align = BTRFS_STRIPE_LEN;
5083 map->io_width = BTRFS_STRIPE_LEN;
5085 map->sub_stripes = ctl->sub_stripes;
5087 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5089 em = alloc_extent_map();
5094 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5095 em->map_lookup = map;
5097 em->len = ctl->chunk_size;
5098 em->block_start = 0;
5099 em->block_len = em->len;
5100 em->orig_block_len = ctl->stripe_size;
5102 em_tree = &info->mapping_tree;
5103 write_lock(&em_tree->lock);
5104 ret = add_extent_mapping(em_tree, em, 0);
5106 write_unlock(&em_tree->lock);
5107 free_extent_map(em);
5110 write_unlock(&em_tree->lock);
5112 ret = btrfs_make_block_group(trans, 0, type, start, ctl->chunk_size);
5114 goto error_del_extent;
5116 for (i = 0; i < map->num_stripes; i++) {
5117 struct btrfs_device *dev = map->stripes[i].dev;
5119 btrfs_device_set_bytes_used(dev,
5120 dev->bytes_used + ctl->stripe_size);
5121 if (list_empty(&dev->post_commit_list))
5122 list_add_tail(&dev->post_commit_list,
5123 &trans->transaction->dev_update_list);
5126 atomic64_sub(ctl->stripe_size * map->num_stripes,
5127 &info->free_chunk_space);
5129 free_extent_map(em);
5130 check_raid56_incompat_flag(info, type);
5131 check_raid1c34_incompat_flag(info, type);
5136 write_lock(&em_tree->lock);
5137 remove_extent_mapping(em_tree, em);
5138 write_unlock(&em_tree->lock);
5140 /* One for our allocation */
5141 free_extent_map(em);
5142 /* One for the tree reference */
5143 free_extent_map(em);
5148 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5150 struct btrfs_fs_info *info = trans->fs_info;
5151 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5152 struct btrfs_device_info *devices_info = NULL;
5153 struct alloc_chunk_ctl ctl;
5156 lockdep_assert_held(&info->chunk_mutex);
5158 if (!alloc_profile_is_valid(type, 0)) {
5163 if (list_empty(&fs_devices->alloc_list)) {
5164 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5165 btrfs_debug(info, "%s: no writable device", __func__);
5169 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5170 btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5175 ctl.start = find_next_chunk(info);
5177 init_alloc_chunk_ctl(fs_devices, &ctl);
5179 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5184 ret = gather_device_info(fs_devices, &ctl, devices_info);
5188 ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5192 ret = create_chunk(trans, &ctl, devices_info);
5195 kfree(devices_info);
5200 * Chunk allocation falls into two parts. The first part does work
5201 * that makes the new allocated chunk usable, but does not do any operation
5202 * that modifies the chunk tree. The second part does the work that
5203 * requires modifying the chunk tree. This division is important for the
5204 * bootstrap process of adding storage to a seed btrfs.
5206 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5207 u64 chunk_offset, u64 chunk_size)
5209 struct btrfs_fs_info *fs_info = trans->fs_info;
5210 struct btrfs_root *extent_root = fs_info->extent_root;
5211 struct btrfs_root *chunk_root = fs_info->chunk_root;
5212 struct btrfs_key key;
5213 struct btrfs_device *device;
5214 struct btrfs_chunk *chunk;
5215 struct btrfs_stripe *stripe;
5216 struct extent_map *em;
5217 struct map_lookup *map;
5224 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5228 map = em->map_lookup;
5229 item_size = btrfs_chunk_item_size(map->num_stripes);
5230 stripe_size = em->orig_block_len;
5232 chunk = kzalloc(item_size, GFP_NOFS);
5239 * Take the device list mutex to prevent races with the final phase of
5240 * a device replace operation that replaces the device object associated
5241 * with the map's stripes, because the device object's id can change
5242 * at any time during that final phase of the device replace operation
5243 * (dev-replace.c:btrfs_dev_replace_finishing()).
5245 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5246 for (i = 0; i < map->num_stripes; i++) {
5247 device = map->stripes[i].dev;
5248 dev_offset = map->stripes[i].physical;
5250 ret = btrfs_update_device(trans, device);
5253 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5254 dev_offset, stripe_size);
5259 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5263 stripe = &chunk->stripe;
5264 for (i = 0; i < map->num_stripes; i++) {
5265 device = map->stripes[i].dev;
5266 dev_offset = map->stripes[i].physical;
5268 btrfs_set_stack_stripe_devid(stripe, device->devid);
5269 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5270 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5273 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5275 btrfs_set_stack_chunk_length(chunk, chunk_size);
5276 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5277 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5278 btrfs_set_stack_chunk_type(chunk, map->type);
5279 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5280 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5281 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5282 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5283 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5285 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5286 key.type = BTRFS_CHUNK_ITEM_KEY;
5287 key.offset = chunk_offset;
5289 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5290 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5292 * TODO: Cleanup of inserted chunk root in case of
5295 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5300 free_extent_map(em);
5304 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5306 struct btrfs_fs_info *fs_info = trans->fs_info;
5310 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5311 ret = btrfs_alloc_chunk(trans, alloc_profile);
5315 alloc_profile = btrfs_system_alloc_profile(fs_info);
5316 ret = btrfs_alloc_chunk(trans, alloc_profile);
5320 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5322 const int index = btrfs_bg_flags_to_raid_index(map->type);
5324 return btrfs_raid_array[index].tolerated_failures;
5327 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5329 struct extent_map *em;
5330 struct map_lookup *map;
5335 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5339 map = em->map_lookup;
5340 for (i = 0; i < map->num_stripes; i++) {
5341 if (test_bit(BTRFS_DEV_STATE_MISSING,
5342 &map->stripes[i].dev->dev_state)) {
5346 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5347 &map->stripes[i].dev->dev_state)) {
5354 * If the number of missing devices is larger than max errors,
5355 * we can not write the data into that chunk successfully, so
5358 if (miss_ndevs > btrfs_chunk_max_errors(map))
5361 free_extent_map(em);
5365 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5367 struct extent_map *em;
5370 write_lock(&tree->lock);
5371 em = lookup_extent_mapping(tree, 0, (u64)-1);
5373 remove_extent_mapping(tree, em);
5374 write_unlock(&tree->lock);
5378 free_extent_map(em);
5379 /* once for the tree */
5380 free_extent_map(em);
5384 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5386 struct extent_map *em;
5387 struct map_lookup *map;
5390 em = btrfs_get_chunk_map(fs_info, logical, len);
5393 * We could return errors for these cases, but that could get
5394 * ugly and we'd probably do the same thing which is just not do
5395 * anything else and exit, so return 1 so the callers don't try
5396 * to use other copies.
5400 map = em->map_lookup;
5401 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5402 ret = map->num_stripes;
5403 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5404 ret = map->sub_stripes;
5405 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5407 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5409 * There could be two corrupted data stripes, we need
5410 * to loop retry in order to rebuild the correct data.
5412 * Fail a stripe at a time on every retry except the
5413 * stripe under reconstruction.
5415 ret = map->num_stripes;
5418 free_extent_map(em);
5420 down_read(&fs_info->dev_replace.rwsem);
5421 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5422 fs_info->dev_replace.tgtdev)
5424 up_read(&fs_info->dev_replace.rwsem);
5429 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5432 struct extent_map *em;
5433 struct map_lookup *map;
5434 unsigned long len = fs_info->sectorsize;
5436 em = btrfs_get_chunk_map(fs_info, logical, len);
5438 if (!WARN_ON(IS_ERR(em))) {
5439 map = em->map_lookup;
5440 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5441 len = map->stripe_len * nr_data_stripes(map);
5442 free_extent_map(em);
5447 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5449 struct extent_map *em;
5450 struct map_lookup *map;
5453 em = btrfs_get_chunk_map(fs_info, logical, len);
5455 if(!WARN_ON(IS_ERR(em))) {
5456 map = em->map_lookup;
5457 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5459 free_extent_map(em);
5464 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5465 struct map_lookup *map, int first,
5466 int dev_replace_is_ongoing)
5470 int preferred_mirror;
5472 struct btrfs_device *srcdev;
5475 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5477 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5478 num_stripes = map->sub_stripes;
5480 num_stripes = map->num_stripes;
5482 preferred_mirror = first + current->pid % num_stripes;
5484 if (dev_replace_is_ongoing &&
5485 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5486 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5487 srcdev = fs_info->dev_replace.srcdev;
5492 * try to avoid the drive that is the source drive for a
5493 * dev-replace procedure, only choose it if no other non-missing
5494 * mirror is available
5496 for (tolerance = 0; tolerance < 2; tolerance++) {
5497 if (map->stripes[preferred_mirror].dev->bdev &&
5498 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5499 return preferred_mirror;
5500 for (i = first; i < first + num_stripes; i++) {
5501 if (map->stripes[i].dev->bdev &&
5502 (tolerance || map->stripes[i].dev != srcdev))
5507 /* we couldn't find one that doesn't fail. Just return something
5508 * and the io error handling code will clean up eventually
5510 return preferred_mirror;
5513 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5514 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5521 for (i = 0; i < num_stripes - 1; i++) {
5522 /* Swap if parity is on a smaller index */
5523 if (bbio->raid_map[i] > bbio->raid_map[i + 1]) {
5524 swap(bbio->stripes[i], bbio->stripes[i + 1]);
5525 swap(bbio->raid_map[i], bbio->raid_map[i + 1]);
5532 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5534 struct btrfs_bio *bbio = kzalloc(
5535 /* the size of the btrfs_bio */
5536 sizeof(struct btrfs_bio) +
5537 /* plus the variable array for the stripes */
5538 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5539 /* plus the variable array for the tgt dev */
5540 sizeof(int) * (real_stripes) +
5542 * plus the raid_map, which includes both the tgt dev
5545 sizeof(u64) * (total_stripes),
5546 GFP_NOFS|__GFP_NOFAIL);
5548 atomic_set(&bbio->error, 0);
5549 refcount_set(&bbio->refs, 1);
5551 bbio->tgtdev_map = (int *)(bbio->stripes + total_stripes);
5552 bbio->raid_map = (u64 *)(bbio->tgtdev_map + real_stripes);
5557 void btrfs_get_bbio(struct btrfs_bio *bbio)
5559 WARN_ON(!refcount_read(&bbio->refs));
5560 refcount_inc(&bbio->refs);
5563 void btrfs_put_bbio(struct btrfs_bio *bbio)
5567 if (refcount_dec_and_test(&bbio->refs))
5571 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5573 * Please note that, discard won't be sent to target device of device
5576 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5577 u64 logical, u64 *length_ret,
5578 struct btrfs_bio **bbio_ret)
5580 struct extent_map *em;
5581 struct map_lookup *map;
5582 struct btrfs_bio *bbio;
5583 u64 length = *length_ret;
5587 u64 stripe_end_offset;
5594 u32 sub_stripes = 0;
5595 u64 stripes_per_dev = 0;
5596 u32 remaining_stripes = 0;
5597 u32 last_stripe = 0;
5601 /* discard always return a bbio */
5604 em = btrfs_get_chunk_map(fs_info, logical, length);
5608 map = em->map_lookup;
5609 /* we don't discard raid56 yet */
5610 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5615 offset = logical - em->start;
5616 length = min_t(u64, em->start + em->len - logical, length);
5617 *length_ret = length;
5619 stripe_len = map->stripe_len;
5621 * stripe_nr counts the total number of stripes we have to stride
5622 * to get to this block
5624 stripe_nr = div64_u64(offset, stripe_len);
5626 /* stripe_offset is the offset of this block in its stripe */
5627 stripe_offset = offset - stripe_nr * stripe_len;
5629 stripe_nr_end = round_up(offset + length, map->stripe_len);
5630 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5631 stripe_cnt = stripe_nr_end - stripe_nr;
5632 stripe_end_offset = stripe_nr_end * map->stripe_len -
5635 * after this, stripe_nr is the number of stripes on this
5636 * device we have to walk to find the data, and stripe_index is
5637 * the number of our device in the stripe array
5641 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5642 BTRFS_BLOCK_GROUP_RAID10)) {
5643 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5646 sub_stripes = map->sub_stripes;
5648 factor = map->num_stripes / sub_stripes;
5649 num_stripes = min_t(u64, map->num_stripes,
5650 sub_stripes * stripe_cnt);
5651 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5652 stripe_index *= sub_stripes;
5653 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5654 &remaining_stripes);
5655 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5656 last_stripe *= sub_stripes;
5657 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5658 BTRFS_BLOCK_GROUP_DUP)) {
5659 num_stripes = map->num_stripes;
5661 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5665 bbio = alloc_btrfs_bio(num_stripes, 0);
5671 for (i = 0; i < num_stripes; i++) {
5672 bbio->stripes[i].physical =
5673 map->stripes[stripe_index].physical +
5674 stripe_offset + stripe_nr * map->stripe_len;
5675 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5677 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5678 BTRFS_BLOCK_GROUP_RAID10)) {
5679 bbio->stripes[i].length = stripes_per_dev *
5682 if (i / sub_stripes < remaining_stripes)
5683 bbio->stripes[i].length +=
5687 * Special for the first stripe and
5690 * |-------|...|-------|
5694 if (i < sub_stripes)
5695 bbio->stripes[i].length -=
5698 if (stripe_index >= last_stripe &&
5699 stripe_index <= (last_stripe +
5701 bbio->stripes[i].length -=
5704 if (i == sub_stripes - 1)
5707 bbio->stripes[i].length = length;
5711 if (stripe_index == map->num_stripes) {
5718 bbio->map_type = map->type;
5719 bbio->num_stripes = num_stripes;
5721 free_extent_map(em);
5726 * In dev-replace case, for repair case (that's the only case where the mirror
5727 * is selected explicitly when calling btrfs_map_block), blocks left of the
5728 * left cursor can also be read from the target drive.
5730 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5732 * For READ, it also needs to be supported using the same mirror number.
5734 * If the requested block is not left of the left cursor, EIO is returned. This
5735 * can happen because btrfs_num_copies() returns one more in the dev-replace
5738 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5739 u64 logical, u64 length,
5740 u64 srcdev_devid, int *mirror_num,
5743 struct btrfs_bio *bbio = NULL;
5745 int index_srcdev = 0;
5747 u64 physical_of_found = 0;
5751 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5752 logical, &length, &bbio, 0, 0);
5754 ASSERT(bbio == NULL);
5758 num_stripes = bbio->num_stripes;
5759 if (*mirror_num > num_stripes) {
5761 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5762 * that means that the requested area is not left of the left
5765 btrfs_put_bbio(bbio);
5770 * process the rest of the function using the mirror_num of the source
5771 * drive. Therefore look it up first. At the end, patch the device
5772 * pointer to the one of the target drive.
5774 for (i = 0; i < num_stripes; i++) {
5775 if (bbio->stripes[i].dev->devid != srcdev_devid)
5779 * In case of DUP, in order to keep it simple, only add the
5780 * mirror with the lowest physical address
5783 physical_of_found <= bbio->stripes[i].physical)
5788 physical_of_found = bbio->stripes[i].physical;
5791 btrfs_put_bbio(bbio);
5797 *mirror_num = index_srcdev + 1;
5798 *physical = physical_of_found;
5802 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5803 struct btrfs_bio **bbio_ret,
5804 struct btrfs_dev_replace *dev_replace,
5805 int *num_stripes_ret, int *max_errors_ret)
5807 struct btrfs_bio *bbio = *bbio_ret;
5808 u64 srcdev_devid = dev_replace->srcdev->devid;
5809 int tgtdev_indexes = 0;
5810 int num_stripes = *num_stripes_ret;
5811 int max_errors = *max_errors_ret;
5814 if (op == BTRFS_MAP_WRITE) {
5815 int index_where_to_add;
5818 * duplicate the write operations while the dev replace
5819 * procedure is running. Since the copying of the old disk to
5820 * the new disk takes place at run time while the filesystem is
5821 * mounted writable, the regular write operations to the old
5822 * disk have to be duplicated to go to the new disk as well.
5824 * Note that device->missing is handled by the caller, and that
5825 * the write to the old disk is already set up in the stripes
5828 index_where_to_add = num_stripes;
5829 for (i = 0; i < num_stripes; i++) {
5830 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5831 /* write to new disk, too */
5832 struct btrfs_bio_stripe *new =
5833 bbio->stripes + index_where_to_add;
5834 struct btrfs_bio_stripe *old =
5837 new->physical = old->physical;
5838 new->length = old->length;
5839 new->dev = dev_replace->tgtdev;
5840 bbio->tgtdev_map[i] = index_where_to_add;
5841 index_where_to_add++;
5846 num_stripes = index_where_to_add;
5847 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5848 int index_srcdev = 0;
5850 u64 physical_of_found = 0;
5853 * During the dev-replace procedure, the target drive can also
5854 * be used to read data in case it is needed to repair a corrupt
5855 * block elsewhere. This is possible if the requested area is
5856 * left of the left cursor. In this area, the target drive is a
5857 * full copy of the source drive.
5859 for (i = 0; i < num_stripes; i++) {
5860 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5862 * In case of DUP, in order to keep it simple,
5863 * only add the mirror with the lowest physical
5867 physical_of_found <=
5868 bbio->stripes[i].physical)
5872 physical_of_found = bbio->stripes[i].physical;
5876 struct btrfs_bio_stripe *tgtdev_stripe =
5877 bbio->stripes + num_stripes;
5879 tgtdev_stripe->physical = physical_of_found;
5880 tgtdev_stripe->length =
5881 bbio->stripes[index_srcdev].length;
5882 tgtdev_stripe->dev = dev_replace->tgtdev;
5883 bbio->tgtdev_map[index_srcdev] = num_stripes;
5890 *num_stripes_ret = num_stripes;
5891 *max_errors_ret = max_errors;
5892 bbio->num_tgtdevs = tgtdev_indexes;
5896 static bool need_full_stripe(enum btrfs_map_op op)
5898 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5902 * btrfs_get_io_geometry - calculates the geomery of a particular (address, len)
5903 * tuple. This information is used to calculate how big a
5904 * particular bio can get before it straddles a stripe.
5906 * @fs_info - the filesystem
5907 * @logical - address that we want to figure out the geometry of
5908 * @len - the length of IO we are going to perform, starting at @logical
5909 * @op - type of operation - write or read
5910 * @io_geom - pointer used to return values
5912 * Returns < 0 in case a chunk for the given logical address cannot be found,
5913 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
5915 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5916 u64 logical, u64 len, struct btrfs_io_geometry *io_geom)
5918 struct extent_map *em;
5919 struct map_lookup *map;
5924 u64 raid56_full_stripe_start = (u64)-1;
5928 ASSERT(op != BTRFS_MAP_DISCARD);
5930 em = btrfs_get_chunk_map(fs_info, logical, len);
5934 map = em->map_lookup;
5935 /* Offset of this logical address in the chunk */
5936 offset = logical - em->start;
5937 /* Len of a stripe in a chunk */
5938 stripe_len = map->stripe_len;
5939 /* Stripe wher this block falls in */
5940 stripe_nr = div64_u64(offset, stripe_len);
5941 /* Offset of stripe in the chunk */
5942 stripe_offset = stripe_nr * stripe_len;
5943 if (offset < stripe_offset) {
5945 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
5946 stripe_offset, offset, em->start, logical, stripe_len);
5951 /* stripe_offset is the offset of this block in its stripe */
5952 stripe_offset = offset - stripe_offset;
5953 data_stripes = nr_data_stripes(map);
5955 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5956 u64 max_len = stripe_len - stripe_offset;
5959 * In case of raid56, we need to know the stripe aligned start
5961 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5962 unsigned long full_stripe_len = stripe_len * data_stripes;
5963 raid56_full_stripe_start = offset;
5966 * Allow a write of a full stripe, but make sure we
5967 * don't allow straddling of stripes
5969 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5971 raid56_full_stripe_start *= full_stripe_len;
5974 * For writes to RAID[56], allow a full stripeset across
5975 * all disks. For other RAID types and for RAID[56]
5976 * reads, just allow a single stripe (on a single disk).
5978 if (op == BTRFS_MAP_WRITE) {
5979 max_len = stripe_len * data_stripes -
5980 (offset - raid56_full_stripe_start);
5983 len = min_t(u64, em->len - offset, max_len);
5985 len = em->len - offset;
5989 io_geom->offset = offset;
5990 io_geom->stripe_len = stripe_len;
5991 io_geom->stripe_nr = stripe_nr;
5992 io_geom->stripe_offset = stripe_offset;
5993 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
5997 free_extent_map(em);
6001 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6002 enum btrfs_map_op op,
6003 u64 logical, u64 *length,
6004 struct btrfs_bio **bbio_ret,
6005 int mirror_num, int need_raid_map)
6007 struct extent_map *em;
6008 struct map_lookup *map;
6018 int tgtdev_indexes = 0;
6019 struct btrfs_bio *bbio = NULL;
6020 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6021 int dev_replace_is_ongoing = 0;
6022 int num_alloc_stripes;
6023 int patch_the_first_stripe_for_dev_replace = 0;
6024 u64 physical_to_patch_in_first_stripe = 0;
6025 u64 raid56_full_stripe_start = (u64)-1;
6026 struct btrfs_io_geometry geom;
6029 ASSERT(op != BTRFS_MAP_DISCARD);
6031 ret = btrfs_get_io_geometry(fs_info, op, logical, *length, &geom);
6035 em = btrfs_get_chunk_map(fs_info, logical, *length);
6036 ASSERT(!IS_ERR(em));
6037 map = em->map_lookup;
6040 stripe_len = geom.stripe_len;
6041 stripe_nr = geom.stripe_nr;
6042 stripe_offset = geom.stripe_offset;
6043 raid56_full_stripe_start = geom.raid56_stripe_offset;
6044 data_stripes = nr_data_stripes(map);
6046 down_read(&dev_replace->rwsem);
6047 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6049 * Hold the semaphore for read during the whole operation, write is
6050 * requested at commit time but must wait.
6052 if (!dev_replace_is_ongoing)
6053 up_read(&dev_replace->rwsem);
6055 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6056 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6057 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6058 dev_replace->srcdev->devid,
6060 &physical_to_patch_in_first_stripe);
6064 patch_the_first_stripe_for_dev_replace = 1;
6065 } else if (mirror_num > map->num_stripes) {
6071 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6072 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6074 if (!need_full_stripe(op))
6076 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6077 if (need_full_stripe(op))
6078 num_stripes = map->num_stripes;
6079 else if (mirror_num)
6080 stripe_index = mirror_num - 1;
6082 stripe_index = find_live_mirror(fs_info, map, 0,
6083 dev_replace_is_ongoing);
6084 mirror_num = stripe_index + 1;
6087 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6088 if (need_full_stripe(op)) {
6089 num_stripes = map->num_stripes;
6090 } else if (mirror_num) {
6091 stripe_index = mirror_num - 1;
6096 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6097 u32 factor = map->num_stripes / map->sub_stripes;
6099 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6100 stripe_index *= map->sub_stripes;
6102 if (need_full_stripe(op))
6103 num_stripes = map->sub_stripes;
6104 else if (mirror_num)
6105 stripe_index += mirror_num - 1;
6107 int old_stripe_index = stripe_index;
6108 stripe_index = find_live_mirror(fs_info, map,
6110 dev_replace_is_ongoing);
6111 mirror_num = stripe_index - old_stripe_index + 1;
6114 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6115 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6116 /* push stripe_nr back to the start of the full stripe */
6117 stripe_nr = div64_u64(raid56_full_stripe_start,
6118 stripe_len * data_stripes);
6120 /* RAID[56] write or recovery. Return all stripes */
6121 num_stripes = map->num_stripes;
6122 max_errors = nr_parity_stripes(map);
6124 *length = map->stripe_len;
6129 * Mirror #0 or #1 means the original data block.
6130 * Mirror #2 is RAID5 parity block.
6131 * Mirror #3 is RAID6 Q block.
6133 stripe_nr = div_u64_rem(stripe_nr,
6134 data_stripes, &stripe_index);
6136 stripe_index = data_stripes + mirror_num - 2;
6138 /* We distribute the parity blocks across stripes */
6139 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6141 if (!need_full_stripe(op) && mirror_num <= 1)
6146 * after this, stripe_nr is the number of stripes on this
6147 * device we have to walk to find the data, and stripe_index is
6148 * the number of our device in the stripe array
6150 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6152 mirror_num = stripe_index + 1;
6154 if (stripe_index >= map->num_stripes) {
6156 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6157 stripe_index, map->num_stripes);
6162 num_alloc_stripes = num_stripes;
6163 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6164 if (op == BTRFS_MAP_WRITE)
6165 num_alloc_stripes <<= 1;
6166 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6167 num_alloc_stripes++;
6168 tgtdev_indexes = num_stripes;
6171 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6177 for (i = 0; i < num_stripes; i++) {
6178 bbio->stripes[i].physical = map->stripes[stripe_index].physical +
6179 stripe_offset + stripe_nr * map->stripe_len;
6180 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
6184 /* build raid_map */
6185 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6186 (need_full_stripe(op) || mirror_num > 1)) {
6190 /* Work out the disk rotation on this stripe-set */
6191 div_u64_rem(stripe_nr, num_stripes, &rot);
6193 /* Fill in the logical address of each stripe */
6194 tmp = stripe_nr * data_stripes;
6195 for (i = 0; i < data_stripes; i++)
6196 bbio->raid_map[(i+rot) % num_stripes] =
6197 em->start + (tmp + i) * map->stripe_len;
6199 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6200 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6201 bbio->raid_map[(i+rot+1) % num_stripes] =
6204 sort_parity_stripes(bbio, num_stripes);
6207 if (need_full_stripe(op))
6208 max_errors = btrfs_chunk_max_errors(map);
6210 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6211 need_full_stripe(op)) {
6212 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6217 bbio->map_type = map->type;
6218 bbio->num_stripes = num_stripes;
6219 bbio->max_errors = max_errors;
6220 bbio->mirror_num = mirror_num;
6223 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6224 * mirror_num == num_stripes + 1 && dev_replace target drive is
6225 * available as a mirror
6227 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6228 WARN_ON(num_stripes > 1);
6229 bbio->stripes[0].dev = dev_replace->tgtdev;
6230 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6231 bbio->mirror_num = map->num_stripes + 1;
6234 if (dev_replace_is_ongoing) {
6235 lockdep_assert_held(&dev_replace->rwsem);
6236 /* Unlock and let waiting writers proceed */
6237 up_read(&dev_replace->rwsem);
6239 free_extent_map(em);
6243 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6244 u64 logical, u64 *length,
6245 struct btrfs_bio **bbio_ret, int mirror_num)
6247 if (op == BTRFS_MAP_DISCARD)
6248 return __btrfs_map_block_for_discard(fs_info, logical,
6251 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6255 /* For Scrub/replace */
6256 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6257 u64 logical, u64 *length,
6258 struct btrfs_bio **bbio_ret)
6260 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6263 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6265 bio->bi_private = bbio->private;
6266 bio->bi_end_io = bbio->end_io;
6269 btrfs_put_bbio(bbio);
6272 static void btrfs_end_bio(struct bio *bio)
6274 struct btrfs_bio *bbio = bio->bi_private;
6275 int is_orig_bio = 0;
6277 if (bio->bi_status) {
6278 atomic_inc(&bbio->error);
6279 if (bio->bi_status == BLK_STS_IOERR ||
6280 bio->bi_status == BLK_STS_TARGET) {
6281 struct btrfs_device *dev = btrfs_io_bio(bio)->device;
6284 if (bio_op(bio) == REQ_OP_WRITE)
6285 btrfs_dev_stat_inc_and_print(dev,
6286 BTRFS_DEV_STAT_WRITE_ERRS);
6287 else if (!(bio->bi_opf & REQ_RAHEAD))
6288 btrfs_dev_stat_inc_and_print(dev,
6289 BTRFS_DEV_STAT_READ_ERRS);
6290 if (bio->bi_opf & REQ_PREFLUSH)
6291 btrfs_dev_stat_inc_and_print(dev,
6292 BTRFS_DEV_STAT_FLUSH_ERRS);
6296 if (bio == bbio->orig_bio)
6299 btrfs_bio_counter_dec(bbio->fs_info);
6301 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6304 bio = bbio->orig_bio;
6307 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6308 /* only send an error to the higher layers if it is
6309 * beyond the tolerance of the btrfs bio
6311 if (atomic_read(&bbio->error) > bbio->max_errors) {
6312 bio->bi_status = BLK_STS_IOERR;
6315 * this bio is actually up to date, we didn't
6316 * go over the max number of errors
6318 bio->bi_status = BLK_STS_OK;
6321 btrfs_end_bbio(bbio, bio);
6322 } else if (!is_orig_bio) {
6327 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6328 u64 physical, struct btrfs_device *dev)
6330 struct btrfs_fs_info *fs_info = bbio->fs_info;
6332 bio->bi_private = bbio;
6333 btrfs_io_bio(bio)->device = dev;
6334 bio->bi_end_io = btrfs_end_bio;
6335 bio->bi_iter.bi_sector = physical >> 9;
6336 btrfs_debug_in_rcu(fs_info,
6337 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6338 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6339 (unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6340 dev->devid, bio->bi_iter.bi_size);
6341 bio_set_dev(bio, dev->bdev);
6343 btrfs_bio_counter_inc_noblocked(fs_info);
6345 btrfsic_submit_bio(bio);
6348 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6350 atomic_inc(&bbio->error);
6351 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6352 /* Should be the original bio. */
6353 WARN_ON(bio != bbio->orig_bio);
6355 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6356 bio->bi_iter.bi_sector = logical >> 9;
6357 if (atomic_read(&bbio->error) > bbio->max_errors)
6358 bio->bi_status = BLK_STS_IOERR;
6360 bio->bi_status = BLK_STS_OK;
6361 btrfs_end_bbio(bbio, bio);
6365 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6368 struct btrfs_device *dev;
6369 struct bio *first_bio = bio;
6370 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6376 struct btrfs_bio *bbio = NULL;
6378 length = bio->bi_iter.bi_size;
6379 map_length = length;
6381 btrfs_bio_counter_inc_blocked(fs_info);
6382 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6383 &map_length, &bbio, mirror_num, 1);
6385 btrfs_bio_counter_dec(fs_info);
6386 return errno_to_blk_status(ret);
6389 total_devs = bbio->num_stripes;
6390 bbio->orig_bio = first_bio;
6391 bbio->private = first_bio->bi_private;
6392 bbio->end_io = first_bio->bi_end_io;
6393 bbio->fs_info = fs_info;
6394 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6396 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6397 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6398 /* In this case, map_length has been set to the length of
6399 a single stripe; not the whole write */
6400 if (bio_op(bio) == REQ_OP_WRITE) {
6401 ret = raid56_parity_write(fs_info, bio, bbio,
6404 ret = raid56_parity_recover(fs_info, bio, bbio,
6405 map_length, mirror_num, 1);
6408 btrfs_bio_counter_dec(fs_info);
6409 return errno_to_blk_status(ret);
6412 if (map_length < length) {
6414 "mapping failed logical %llu bio len %llu len %llu",
6415 logical, length, map_length);
6419 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6420 dev = bbio->stripes[dev_nr].dev;
6421 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6423 (bio_op(first_bio) == REQ_OP_WRITE &&
6424 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6425 bbio_error(bbio, first_bio, logical);
6429 if (dev_nr < total_devs - 1)
6430 bio = btrfs_bio_clone(first_bio);
6434 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical, dev);
6436 btrfs_bio_counter_dec(fs_info);
6441 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6444 * If devid and uuid are both specified, the match must be exact, otherwise
6445 * only devid is used.
6447 * If @seed is true, traverse through the seed devices.
6449 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6450 u64 devid, u8 *uuid, u8 *fsid,
6453 struct btrfs_device *device;
6454 struct btrfs_fs_devices *seed_devs;
6456 if (!fsid || !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6457 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6458 if (device->devid == devid &&
6459 (!uuid || memcmp(device->uuid, uuid,
6460 BTRFS_UUID_SIZE) == 0))
6465 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6467 !memcmp(seed_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6468 list_for_each_entry(device, &seed_devs->devices,
6470 if (device->devid == devid &&
6471 (!uuid || memcmp(device->uuid, uuid,
6472 BTRFS_UUID_SIZE) == 0))
6481 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6482 u64 devid, u8 *dev_uuid)
6484 struct btrfs_device *device;
6485 unsigned int nofs_flag;
6488 * We call this under the chunk_mutex, so we want to use NOFS for this
6489 * allocation, however we don't want to change btrfs_alloc_device() to
6490 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6493 nofs_flag = memalloc_nofs_save();
6494 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6495 memalloc_nofs_restore(nofs_flag);
6499 list_add(&device->dev_list, &fs_devices->devices);
6500 device->fs_devices = fs_devices;
6501 fs_devices->num_devices++;
6503 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6504 fs_devices->missing_devices++;
6510 * btrfs_alloc_device - allocate struct btrfs_device
6511 * @fs_info: used only for generating a new devid, can be NULL if
6512 * devid is provided (i.e. @devid != NULL).
6513 * @devid: a pointer to devid for this device. If NULL a new devid
6515 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6518 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6519 * on error. Returned struct is not linked onto any lists and must be
6520 * destroyed with btrfs_free_device.
6522 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6526 struct btrfs_device *dev;
6529 if (WARN_ON(!devid && !fs_info))
6530 return ERR_PTR(-EINVAL);
6532 dev = __alloc_device(fs_info);
6541 ret = find_next_devid(fs_info, &tmp);
6543 btrfs_free_device(dev);
6544 return ERR_PTR(ret);
6550 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6552 generate_random_uuid(dev->uuid);
6557 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6558 u64 devid, u8 *uuid, bool error)
6561 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6564 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6568 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6570 int index = btrfs_bg_flags_to_raid_index(type);
6571 int ncopies = btrfs_raid_array[index].ncopies;
6572 const int nparity = btrfs_raid_array[index].nparity;
6576 data_stripes = num_stripes - nparity;
6578 data_stripes = num_stripes / ncopies;
6580 return div_u64(chunk_len, data_stripes);
6583 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6584 struct btrfs_chunk *chunk)
6586 struct btrfs_fs_info *fs_info = leaf->fs_info;
6587 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6588 struct map_lookup *map;
6589 struct extent_map *em;
6593 u8 uuid[BTRFS_UUID_SIZE];
6598 logical = key->offset;
6599 length = btrfs_chunk_length(leaf, chunk);
6600 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6603 * Only need to verify chunk item if we're reading from sys chunk array,
6604 * as chunk item in tree block is already verified by tree-checker.
6606 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6607 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6612 read_lock(&map_tree->lock);
6613 em = lookup_extent_mapping(map_tree, logical, 1);
6614 read_unlock(&map_tree->lock);
6616 /* already mapped? */
6617 if (em && em->start <= logical && em->start + em->len > logical) {
6618 free_extent_map(em);
6621 free_extent_map(em);
6624 em = alloc_extent_map();
6627 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6629 free_extent_map(em);
6633 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6634 em->map_lookup = map;
6635 em->start = logical;
6638 em->block_start = 0;
6639 em->block_len = em->len;
6641 map->num_stripes = num_stripes;
6642 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6643 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6644 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6645 map->type = btrfs_chunk_type(leaf, chunk);
6646 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6647 map->verified_stripes = 0;
6648 em->orig_block_len = calc_stripe_length(map->type, em->len,
6650 for (i = 0; i < num_stripes; i++) {
6651 map->stripes[i].physical =
6652 btrfs_stripe_offset_nr(leaf, chunk, i);
6653 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6654 read_extent_buffer(leaf, uuid, (unsigned long)
6655 btrfs_stripe_dev_uuid_nr(chunk, i),
6657 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6658 devid, uuid, NULL, true);
6659 if (!map->stripes[i].dev &&
6660 !btrfs_test_opt(fs_info, DEGRADED)) {
6661 free_extent_map(em);
6662 btrfs_report_missing_device(fs_info, devid, uuid, true);
6665 if (!map->stripes[i].dev) {
6666 map->stripes[i].dev =
6667 add_missing_dev(fs_info->fs_devices, devid,
6669 if (IS_ERR(map->stripes[i].dev)) {
6670 free_extent_map(em);
6672 "failed to init missing dev %llu: %ld",
6673 devid, PTR_ERR(map->stripes[i].dev));
6674 return PTR_ERR(map->stripes[i].dev);
6676 btrfs_report_missing_device(fs_info, devid, uuid, false);
6678 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6679 &(map->stripes[i].dev->dev_state));
6683 write_lock(&map_tree->lock);
6684 ret = add_extent_mapping(map_tree, em, 0);
6685 write_unlock(&map_tree->lock);
6688 "failed to add chunk map, start=%llu len=%llu: %d",
6689 em->start, em->len, ret);
6691 free_extent_map(em);
6696 static void fill_device_from_item(struct extent_buffer *leaf,
6697 struct btrfs_dev_item *dev_item,
6698 struct btrfs_device *device)
6702 device->devid = btrfs_device_id(leaf, dev_item);
6703 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6704 device->total_bytes = device->disk_total_bytes;
6705 device->commit_total_bytes = device->disk_total_bytes;
6706 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6707 device->commit_bytes_used = device->bytes_used;
6708 device->type = btrfs_device_type(leaf, dev_item);
6709 device->io_align = btrfs_device_io_align(leaf, dev_item);
6710 device->io_width = btrfs_device_io_width(leaf, dev_item);
6711 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6712 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6713 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6715 ptr = btrfs_device_uuid(dev_item);
6716 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6719 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6722 struct btrfs_fs_devices *fs_devices;
6725 lockdep_assert_held(&uuid_mutex);
6728 /* This will match only for multi-device seed fs */
6729 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
6730 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6734 fs_devices = find_fsid(fsid, NULL);
6736 if (!btrfs_test_opt(fs_info, DEGRADED))
6737 return ERR_PTR(-ENOENT);
6739 fs_devices = alloc_fs_devices(fsid, NULL);
6740 if (IS_ERR(fs_devices))
6743 fs_devices->seeding = true;
6744 fs_devices->opened = 1;
6749 * Upon first call for a seed fs fsid, just create a private copy of the
6750 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
6752 fs_devices = clone_fs_devices(fs_devices);
6753 if (IS_ERR(fs_devices))
6756 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6758 free_fs_devices(fs_devices);
6759 return ERR_PTR(ret);
6762 if (!fs_devices->seeding) {
6763 close_fs_devices(fs_devices);
6764 free_fs_devices(fs_devices);
6765 return ERR_PTR(-EINVAL);
6768 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
6773 static int read_one_dev(struct extent_buffer *leaf,
6774 struct btrfs_dev_item *dev_item)
6776 struct btrfs_fs_info *fs_info = leaf->fs_info;
6777 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6778 struct btrfs_device *device;
6781 u8 fs_uuid[BTRFS_FSID_SIZE];
6782 u8 dev_uuid[BTRFS_UUID_SIZE];
6784 devid = btrfs_device_id(leaf, dev_item);
6785 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6787 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6790 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6791 fs_devices = open_seed_devices(fs_info, fs_uuid);
6792 if (IS_ERR(fs_devices))
6793 return PTR_ERR(fs_devices);
6796 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6799 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6800 btrfs_report_missing_device(fs_info, devid,
6805 device = add_missing_dev(fs_devices, devid, dev_uuid);
6806 if (IS_ERR(device)) {
6808 "failed to add missing dev %llu: %ld",
6809 devid, PTR_ERR(device));
6810 return PTR_ERR(device);
6812 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6814 if (!device->bdev) {
6815 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6816 btrfs_report_missing_device(fs_info,
6817 devid, dev_uuid, true);
6820 btrfs_report_missing_device(fs_info, devid,
6824 if (!device->bdev &&
6825 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6827 * this happens when a device that was properly setup
6828 * in the device info lists suddenly goes bad.
6829 * device->bdev is NULL, and so we have to set
6830 * device->missing to one here
6832 device->fs_devices->missing_devices++;
6833 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6836 /* Move the device to its own fs_devices */
6837 if (device->fs_devices != fs_devices) {
6838 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6839 &device->dev_state));
6841 list_move(&device->dev_list, &fs_devices->devices);
6842 device->fs_devices->num_devices--;
6843 fs_devices->num_devices++;
6845 device->fs_devices->missing_devices--;
6846 fs_devices->missing_devices++;
6848 device->fs_devices = fs_devices;
6852 if (device->fs_devices != fs_info->fs_devices) {
6853 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6854 if (device->generation !=
6855 btrfs_device_generation(leaf, dev_item))
6859 fill_device_from_item(leaf, dev_item, device);
6860 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6861 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6862 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6863 device->fs_devices->total_rw_bytes += device->total_bytes;
6864 atomic64_add(device->total_bytes - device->bytes_used,
6865 &fs_info->free_chunk_space);
6871 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6873 struct btrfs_root *root = fs_info->tree_root;
6874 struct btrfs_super_block *super_copy = fs_info->super_copy;
6875 struct extent_buffer *sb;
6876 struct btrfs_disk_key *disk_key;
6877 struct btrfs_chunk *chunk;
6879 unsigned long sb_array_offset;
6886 struct btrfs_key key;
6888 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6890 * This will create extent buffer of nodesize, superblock size is
6891 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6892 * overallocate but we can keep it as-is, only the first page is used.
6894 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6897 set_extent_buffer_uptodate(sb);
6898 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6900 * The sb extent buffer is artificial and just used to read the system array.
6901 * set_extent_buffer_uptodate() call does not properly mark all it's
6902 * pages up-to-date when the page is larger: extent does not cover the
6903 * whole page and consequently check_page_uptodate does not find all
6904 * the page's extents up-to-date (the hole beyond sb),
6905 * write_extent_buffer then triggers a WARN_ON.
6907 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6908 * but sb spans only this function. Add an explicit SetPageUptodate call
6909 * to silence the warning eg. on PowerPC 64.
6911 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6912 SetPageUptodate(sb->pages[0]);
6914 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6915 array_size = btrfs_super_sys_array_size(super_copy);
6917 array_ptr = super_copy->sys_chunk_array;
6918 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6921 while (cur_offset < array_size) {
6922 disk_key = (struct btrfs_disk_key *)array_ptr;
6923 len = sizeof(*disk_key);
6924 if (cur_offset + len > array_size)
6925 goto out_short_read;
6927 btrfs_disk_key_to_cpu(&key, disk_key);
6930 sb_array_offset += len;
6933 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
6935 "unexpected item type %u in sys_array at offset %u",
6936 (u32)key.type, cur_offset);
6941 chunk = (struct btrfs_chunk *)sb_array_offset;
6943 * At least one btrfs_chunk with one stripe must be present,
6944 * exact stripe count check comes afterwards
6946 len = btrfs_chunk_item_size(1);
6947 if (cur_offset + len > array_size)
6948 goto out_short_read;
6950 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6953 "invalid number of stripes %u in sys_array at offset %u",
6954 num_stripes, cur_offset);
6959 type = btrfs_chunk_type(sb, chunk);
6960 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6962 "invalid chunk type %llu in sys_array at offset %u",
6968 len = btrfs_chunk_item_size(num_stripes);
6969 if (cur_offset + len > array_size)
6970 goto out_short_read;
6972 ret = read_one_chunk(&key, sb, chunk);
6977 sb_array_offset += len;
6980 clear_extent_buffer_uptodate(sb);
6981 free_extent_buffer_stale(sb);
6985 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6987 clear_extent_buffer_uptodate(sb);
6988 free_extent_buffer_stale(sb);
6993 * Check if all chunks in the fs are OK for read-write degraded mount
6995 * If the @failing_dev is specified, it's accounted as missing.
6997 * Return true if all chunks meet the minimal RW mount requirements.
6998 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7000 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7001 struct btrfs_device *failing_dev)
7003 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7004 struct extent_map *em;
7008 read_lock(&map_tree->lock);
7009 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7010 read_unlock(&map_tree->lock);
7011 /* No chunk at all? Return false anyway */
7017 struct map_lookup *map;
7022 map = em->map_lookup;
7024 btrfs_get_num_tolerated_disk_barrier_failures(
7026 for (i = 0; i < map->num_stripes; i++) {
7027 struct btrfs_device *dev = map->stripes[i].dev;
7029 if (!dev || !dev->bdev ||
7030 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7031 dev->last_flush_error)
7033 else if (failing_dev && failing_dev == dev)
7036 if (missing > max_tolerated) {
7039 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7040 em->start, missing, max_tolerated);
7041 free_extent_map(em);
7045 next_start = extent_map_end(em);
7046 free_extent_map(em);
7048 read_lock(&map_tree->lock);
7049 em = lookup_extent_mapping(map_tree, next_start,
7050 (u64)(-1) - next_start);
7051 read_unlock(&map_tree->lock);
7057 static void readahead_tree_node_children(struct extent_buffer *node)
7060 const int nr_items = btrfs_header_nritems(node);
7062 for (i = 0; i < nr_items; i++) {
7065 start = btrfs_node_blockptr(node, i);
7066 readahead_tree_block(node->fs_info, start);
7070 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7072 struct btrfs_root *root = fs_info->chunk_root;
7073 struct btrfs_path *path;
7074 struct extent_buffer *leaf;
7075 struct btrfs_key key;
7076 struct btrfs_key found_key;
7080 u64 last_ra_node = 0;
7082 path = btrfs_alloc_path();
7087 * uuid_mutex is needed only if we are mounting a sprout FS
7088 * otherwise we don't need it.
7090 mutex_lock(&uuid_mutex);
7093 * It is possible for mount and umount to race in such a way that
7094 * we execute this code path, but open_fs_devices failed to clear
7095 * total_rw_bytes. We certainly want it cleared before reading the
7096 * device items, so clear it here.
7098 fs_info->fs_devices->total_rw_bytes = 0;
7101 * Read all device items, and then all the chunk items. All
7102 * device items are found before any chunk item (their object id
7103 * is smaller than the lowest possible object id for a chunk
7104 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7106 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7109 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7113 struct extent_buffer *node;
7115 leaf = path->nodes[0];
7116 slot = path->slots[0];
7117 if (slot >= btrfs_header_nritems(leaf)) {
7118 ret = btrfs_next_leaf(root, path);
7126 * The nodes on level 1 are not locked but we don't need to do
7127 * that during mount time as nothing else can access the tree
7129 node = path->nodes[1];
7131 if (last_ra_node != node->start) {
7132 readahead_tree_node_children(node);
7133 last_ra_node = node->start;
7136 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7137 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7138 struct btrfs_dev_item *dev_item;
7139 dev_item = btrfs_item_ptr(leaf, slot,
7140 struct btrfs_dev_item);
7141 ret = read_one_dev(leaf, dev_item);
7145 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7146 struct btrfs_chunk *chunk;
7147 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7148 mutex_lock(&fs_info->chunk_mutex);
7149 ret = read_one_chunk(&found_key, leaf, chunk);
7150 mutex_unlock(&fs_info->chunk_mutex);
7158 * After loading chunk tree, we've got all device information,
7159 * do another round of validation checks.
7161 if (total_dev != fs_info->fs_devices->total_devices) {
7163 "super_num_devices %llu mismatch with num_devices %llu found here",
7164 btrfs_super_num_devices(fs_info->super_copy),
7169 if (btrfs_super_total_bytes(fs_info->super_copy) <
7170 fs_info->fs_devices->total_rw_bytes) {
7172 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7173 btrfs_super_total_bytes(fs_info->super_copy),
7174 fs_info->fs_devices->total_rw_bytes);
7180 mutex_unlock(&uuid_mutex);
7182 btrfs_free_path(path);
7186 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7188 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7189 struct btrfs_device *device;
7191 fs_devices->fs_info = fs_info;
7193 mutex_lock(&fs_devices->device_list_mutex);
7194 list_for_each_entry(device, &fs_devices->devices, dev_list)
7195 device->fs_info = fs_info;
7197 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7198 list_for_each_entry(device, &seed_devs->devices, dev_list)
7199 device->fs_info = fs_info;
7201 seed_devs->fs_info = fs_info;
7203 mutex_unlock(&fs_devices->device_list_mutex);
7206 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7207 const struct btrfs_dev_stats_item *ptr,
7212 read_extent_buffer(eb, &val,
7213 offsetof(struct btrfs_dev_stats_item, values) +
7214 ((unsigned long)ptr) + (index * sizeof(u64)),
7219 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7220 struct btrfs_dev_stats_item *ptr,
7223 write_extent_buffer(eb, &val,
7224 offsetof(struct btrfs_dev_stats_item, values) +
7225 ((unsigned long)ptr) + (index * sizeof(u64)),
7229 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7230 struct btrfs_path *path)
7232 struct btrfs_dev_stats_item *ptr;
7233 struct extent_buffer *eb;
7234 struct btrfs_key key;
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, device->fs_info->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);
7247 return ret < 0 ? ret : 0;
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, struct btrfs_dev_stats_item);
7255 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7256 if (item_size >= (1 + i) * sizeof(__le64))
7257 btrfs_dev_stat_set(device, i,
7258 btrfs_dev_stats_value(eb, ptr, i));
7260 btrfs_dev_stat_set(device, i, 0);
7263 device->dev_stats_valid = 1;
7264 btrfs_dev_stat_print_on_load(device);
7265 btrfs_release_path(path);
7270 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7272 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7273 struct btrfs_device *device;
7274 struct btrfs_path *path = NULL;
7277 path = btrfs_alloc_path();
7281 mutex_lock(&fs_devices->device_list_mutex);
7282 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7283 ret = btrfs_device_init_dev_stats(device, path);
7287 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7288 list_for_each_entry(device, &seed_devs->devices, dev_list) {
7289 ret = btrfs_device_init_dev_stats(device, path);
7295 mutex_unlock(&fs_devices->device_list_mutex);
7297 btrfs_free_path(path);
7301 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7302 struct btrfs_device *device)
7304 struct btrfs_fs_info *fs_info = trans->fs_info;
7305 struct btrfs_root *dev_root = fs_info->dev_root;
7306 struct btrfs_path *path;
7307 struct btrfs_key key;
7308 struct extent_buffer *eb;
7309 struct btrfs_dev_stats_item *ptr;
7313 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7314 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7315 key.offset = device->devid;
7317 path = btrfs_alloc_path();
7320 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7322 btrfs_warn_in_rcu(fs_info,
7323 "error %d while searching for dev_stats item for device %s",
7324 ret, rcu_str_deref(device->name));
7329 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7330 /* need to delete old one and insert a new one */
7331 ret = btrfs_del_item(trans, dev_root, path);
7333 btrfs_warn_in_rcu(fs_info,
7334 "delete too small dev_stats item for device %s failed %d",
7335 rcu_str_deref(device->name), ret);
7342 /* need to insert a new item */
7343 btrfs_release_path(path);
7344 ret = btrfs_insert_empty_item(trans, dev_root, path,
7345 &key, sizeof(*ptr));
7347 btrfs_warn_in_rcu(fs_info,
7348 "insert dev_stats item for device %s failed %d",
7349 rcu_str_deref(device->name), ret);
7354 eb = path->nodes[0];
7355 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7356 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7357 btrfs_set_dev_stats_value(eb, ptr, i,
7358 btrfs_dev_stat_read(device, i));
7359 btrfs_mark_buffer_dirty(eb);
7362 btrfs_free_path(path);
7367 * called from commit_transaction. Writes all changed device stats to disk.
7369 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7371 struct btrfs_fs_info *fs_info = trans->fs_info;
7372 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7373 struct btrfs_device *device;
7377 mutex_lock(&fs_devices->device_list_mutex);
7378 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7379 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7380 if (!device->dev_stats_valid || stats_cnt == 0)
7385 * There is a LOAD-LOAD control dependency between the value of
7386 * dev_stats_ccnt and updating the on-disk values which requires
7387 * reading the in-memory counters. Such control dependencies
7388 * require explicit read memory barriers.
7390 * This memory barriers pairs with smp_mb__before_atomic in
7391 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7392 * barrier implied by atomic_xchg in
7393 * btrfs_dev_stats_read_and_reset
7397 ret = update_dev_stat_item(trans, device);
7399 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7401 mutex_unlock(&fs_devices->device_list_mutex);
7406 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7408 btrfs_dev_stat_inc(dev, index);
7409 btrfs_dev_stat_print_on_error(dev);
7412 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7414 if (!dev->dev_stats_valid)
7416 btrfs_err_rl_in_rcu(dev->fs_info,
7417 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7418 rcu_str_deref(dev->name),
7419 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7420 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7421 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7422 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7423 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7426 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7430 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7431 if (btrfs_dev_stat_read(dev, i) != 0)
7433 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7434 return; /* all values == 0, suppress message */
7436 btrfs_info_in_rcu(dev->fs_info,
7437 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7438 rcu_str_deref(dev->name),
7439 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7440 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7441 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7442 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7443 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7446 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7447 struct btrfs_ioctl_get_dev_stats *stats)
7449 struct btrfs_device *dev;
7450 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7453 mutex_lock(&fs_devices->device_list_mutex);
7454 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7456 mutex_unlock(&fs_devices->device_list_mutex);
7459 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7461 } else if (!dev->dev_stats_valid) {
7462 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7464 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7465 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7466 if (stats->nr_items > i)
7468 btrfs_dev_stat_read_and_reset(dev, i);
7470 btrfs_dev_stat_set(dev, i, 0);
7472 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7473 current->comm, task_pid_nr(current));
7475 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7476 if (stats->nr_items > i)
7477 stats->values[i] = btrfs_dev_stat_read(dev, i);
7479 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7480 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7485 * Update the size and bytes used for each device where it changed. This is
7486 * delayed since we would otherwise get errors while writing out the
7489 * Must be invoked during transaction commit.
7491 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7493 struct btrfs_device *curr, *next;
7495 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7497 if (list_empty(&trans->dev_update_list))
7501 * We don't need the device_list_mutex here. This list is owned by the
7502 * transaction and the transaction must complete before the device is
7505 mutex_lock(&trans->fs_info->chunk_mutex);
7506 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7508 list_del_init(&curr->post_commit_list);
7509 curr->commit_total_bytes = curr->disk_total_bytes;
7510 curr->commit_bytes_used = curr->bytes_used;
7512 mutex_unlock(&trans->fs_info->chunk_mutex);
7516 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7518 int btrfs_bg_type_to_factor(u64 flags)
7520 const int index = btrfs_bg_flags_to_raid_index(flags);
7522 return btrfs_raid_array[index].ncopies;
7527 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7528 u64 chunk_offset, u64 devid,
7529 u64 physical_offset, u64 physical_len)
7531 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7532 struct extent_map *em;
7533 struct map_lookup *map;
7534 struct btrfs_device *dev;
7540 read_lock(&em_tree->lock);
7541 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7542 read_unlock(&em_tree->lock);
7546 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7547 physical_offset, devid);
7552 map = em->map_lookup;
7553 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7554 if (physical_len != stripe_len) {
7556 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7557 physical_offset, devid, em->start, physical_len,
7563 for (i = 0; i < map->num_stripes; i++) {
7564 if (map->stripes[i].dev->devid == devid &&
7565 map->stripes[i].physical == physical_offset) {
7567 if (map->verified_stripes >= map->num_stripes) {
7569 "too many dev extents for chunk %llu found",
7574 map->verified_stripes++;
7580 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7581 physical_offset, devid);
7585 /* Make sure no dev extent is beyond device bondary */
7586 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7588 btrfs_err(fs_info, "failed to find devid %llu", devid);
7593 /* It's possible this device is a dummy for seed device */
7594 if (dev->disk_total_bytes == 0) {
7595 struct btrfs_fs_devices *devs;
7597 devs = list_first_entry(&fs_info->fs_devices->seed_list,
7598 struct btrfs_fs_devices, seed_list);
7599 dev = btrfs_find_device(devs, devid, NULL, NULL, false);
7601 btrfs_err(fs_info, "failed to find seed devid %llu",
7608 if (physical_offset + physical_len > dev->disk_total_bytes) {
7610 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7611 devid, physical_offset, physical_len,
7612 dev->disk_total_bytes);
7617 free_extent_map(em);
7621 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7623 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7624 struct extent_map *em;
7625 struct rb_node *node;
7628 read_lock(&em_tree->lock);
7629 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7630 em = rb_entry(node, struct extent_map, rb_node);
7631 if (em->map_lookup->num_stripes !=
7632 em->map_lookup->verified_stripes) {
7634 "chunk %llu has missing dev extent, have %d expect %d",
7635 em->start, em->map_lookup->verified_stripes,
7636 em->map_lookup->num_stripes);
7642 read_unlock(&em_tree->lock);
7647 * Ensure that all dev extents are mapped to correct chunk, otherwise
7648 * later chunk allocation/free would cause unexpected behavior.
7650 * NOTE: This will iterate through the whole device tree, which should be of
7651 * the same size level as the chunk tree. This slightly increases mount time.
7653 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7655 struct btrfs_path *path;
7656 struct btrfs_root *root = fs_info->dev_root;
7657 struct btrfs_key key;
7659 u64 prev_dev_ext_end = 0;
7663 key.type = BTRFS_DEV_EXTENT_KEY;
7666 path = btrfs_alloc_path();
7670 path->reada = READA_FORWARD;
7671 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7675 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7676 ret = btrfs_next_item(root, path);
7679 /* No dev extents at all? Not good */
7686 struct extent_buffer *leaf = path->nodes[0];
7687 struct btrfs_dev_extent *dext;
7688 int slot = path->slots[0];
7690 u64 physical_offset;
7694 btrfs_item_key_to_cpu(leaf, &key, slot);
7695 if (key.type != BTRFS_DEV_EXTENT_KEY)
7697 devid = key.objectid;
7698 physical_offset = key.offset;
7700 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7701 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7702 physical_len = btrfs_dev_extent_length(leaf, dext);
7704 /* Check if this dev extent overlaps with the previous one */
7705 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7707 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7708 devid, physical_offset, prev_dev_ext_end);
7713 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7714 physical_offset, physical_len);
7718 prev_dev_ext_end = physical_offset + physical_len;
7720 ret = btrfs_next_item(root, path);
7729 /* Ensure all chunks have corresponding dev extents */
7730 ret = verify_chunk_dev_extent_mapping(fs_info);
7732 btrfs_free_path(path);
7737 * Check whether the given block group or device is pinned by any inode being
7738 * used as a swapfile.
7740 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7742 struct btrfs_swapfile_pin *sp;
7743 struct rb_node *node;
7745 spin_lock(&fs_info->swapfile_pins_lock);
7746 node = fs_info->swapfile_pins.rb_node;
7748 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7750 node = node->rb_left;
7751 else if (ptr > sp->ptr)
7752 node = node->rb_right;
7756 spin_unlock(&fs_info->swapfile_pins_lock);
7757 return node != NULL;