1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
8 #include <linux/slab.h>
9 #include <linux/buffer_head.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!
251 * btrfs_device::name - renames (write side), read is RCU
253 * fs_devices::device_list_mutex (per-fs, with RCU)
254 * ------------------------------------------------
255 * protects updates to fs_devices::devices, ie. adding and deleting
257 * simple list traversal with read-only actions can be done with RCU protection
259 * may be used to exclude some operations from running concurrently without any
260 * modifications to the list (see write_all_supers)
264 * protects balance structures (status, state) and context accessed from
265 * several places (internally, ioctl)
269 * protects chunks, adding or removing during allocation, trim or when a new
270 * device is added/removed. Additionally it also protects post_commit_list of
271 * individual devices, since they can be added to the transaction's
272 * post_commit_list only with chunk_mutex held.
276 * a big lock that is held by the cleaner thread and prevents running subvolume
277 * cleaning together with relocation or delayed iputs
290 * Exclusive operations, BTRFS_FS_EXCL_OP
291 * ======================================
293 * Maintains the exclusivity of the following operations that apply to the
294 * whole filesystem and cannot run in parallel.
299 * - Device replace (*)
302 * The device operations (as above) can be in one of the following states:
308 * Only device operations marked with (*) can go into the Paused state for the
311 * - ioctl (only Balance can be Paused through ioctl)
312 * - filesystem remounted as read-only
313 * - filesystem unmounted and mounted as read-only
314 * - system power-cycle and filesystem mounted as read-only
315 * - filesystem or device errors leading to forced read-only
317 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
318 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
319 * A device operation in Paused or Running state can be canceled or resumed
320 * either by ioctl (Balance only) or when remounted as read-write.
321 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
325 DEFINE_MUTEX(uuid_mutex);
326 static LIST_HEAD(fs_uuids);
327 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
333 * alloc_fs_devices - allocate struct btrfs_fs_devices
334 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
335 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
337 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
338 * The returned struct is not linked onto any lists and can be destroyed with
339 * kfree() right away.
341 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
342 const u8 *metadata_fsid)
344 struct btrfs_fs_devices *fs_devs;
346 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
348 return ERR_PTR(-ENOMEM);
350 mutex_init(&fs_devs->device_list_mutex);
352 INIT_LIST_HEAD(&fs_devs->devices);
353 INIT_LIST_HEAD(&fs_devs->alloc_list);
354 INIT_LIST_HEAD(&fs_devs->fs_list);
356 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
359 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
361 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
366 void btrfs_free_device(struct btrfs_device *device)
368 WARN_ON(!list_empty(&device->post_commit_list));
369 rcu_string_free(device->name);
370 extent_io_tree_release(&device->alloc_state);
371 bio_put(device->flush_bio);
375 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
377 struct btrfs_device *device;
378 WARN_ON(fs_devices->opened);
379 while (!list_empty(&fs_devices->devices)) {
380 device = list_entry(fs_devices->devices.next,
381 struct btrfs_device, dev_list);
382 list_del(&device->dev_list);
383 btrfs_free_device(device);
388 void __exit btrfs_cleanup_fs_uuids(void)
390 struct btrfs_fs_devices *fs_devices;
392 while (!list_empty(&fs_uuids)) {
393 fs_devices = list_entry(fs_uuids.next,
394 struct btrfs_fs_devices, fs_list);
395 list_del(&fs_devices->fs_list);
396 free_fs_devices(fs_devices);
401 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
402 * Returned struct is not linked onto any lists and must be destroyed using
405 static struct btrfs_device *__alloc_device(void)
407 struct btrfs_device *dev;
409 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
411 return ERR_PTR(-ENOMEM);
414 * Preallocate a bio that's always going to be used for flushing device
415 * barriers and matches the device lifespan
417 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
418 if (!dev->flush_bio) {
420 return ERR_PTR(-ENOMEM);
423 INIT_LIST_HEAD(&dev->dev_list);
424 INIT_LIST_HEAD(&dev->dev_alloc_list);
425 INIT_LIST_HEAD(&dev->post_commit_list);
427 atomic_set(&dev->reada_in_flight, 0);
428 atomic_set(&dev->dev_stats_ccnt, 0);
429 btrfs_device_data_ordered_init(dev);
430 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
431 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
432 extent_io_tree_init(NULL, &dev->alloc_state, 0, NULL);
437 static noinline struct btrfs_fs_devices *find_fsid(
438 const u8 *fsid, const u8 *metadata_fsid)
440 struct btrfs_fs_devices *fs_devices;
444 /* Handle non-split brain cases */
445 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
447 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
448 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
449 BTRFS_FSID_SIZE) == 0)
452 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
459 static struct btrfs_fs_devices *find_fsid_with_metadata_uuid(
460 struct btrfs_super_block *disk_super)
463 struct btrfs_fs_devices *fs_devices;
466 * Handle scanned device having completed its fsid change but
467 * belonging to a fs_devices that was created by first scanning
468 * a device which didn't have its fsid/metadata_uuid changed
469 * at all and the CHANGING_FSID_V2 flag set.
471 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
472 if (fs_devices->fsid_change &&
473 memcmp(disk_super->metadata_uuid, fs_devices->fsid,
474 BTRFS_FSID_SIZE) == 0 &&
475 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
476 BTRFS_FSID_SIZE) == 0) {
481 * Handle scanned device having completed its fsid change but
482 * belonging to a fs_devices that was created by a device that
483 * has an outdated pair of fsid/metadata_uuid and
484 * CHANGING_FSID_V2 flag set.
486 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
487 if (fs_devices->fsid_change &&
488 memcmp(fs_devices->metadata_uuid,
489 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
490 memcmp(disk_super->metadata_uuid, fs_devices->metadata_uuid,
491 BTRFS_FSID_SIZE) == 0) {
496 return find_fsid(disk_super->fsid, disk_super->metadata_uuid);
501 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
502 int flush, struct block_device **bdev,
503 struct buffer_head **bh)
507 *bdev = blkdev_get_by_path(device_path, flags, holder);
510 ret = PTR_ERR(*bdev);
515 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
516 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
518 blkdev_put(*bdev, flags);
521 invalidate_bdev(*bdev);
522 *bh = btrfs_read_dev_super(*bdev);
525 blkdev_put(*bdev, flags);
537 static bool device_path_matched(const char *path, struct btrfs_device *device)
542 found = strcmp(rcu_str_deref(device->name), path);
549 * Search and remove all stale (devices which are not mounted) devices.
550 * When both inputs are NULL, it will search and release all stale devices.
551 * path: Optional. When provided will it release all unmounted devices
552 * matching this path only.
553 * skip_dev: Optional. Will skip this device when searching for the stale
555 * Return: 0 for success or if @path is NULL.
556 * -EBUSY if @path is a mounted device.
557 * -ENOENT if @path does not match any device in the list.
559 static int btrfs_free_stale_devices(const char *path,
560 struct btrfs_device *skip_device)
562 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
563 struct btrfs_device *device, *tmp_device;
569 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
571 mutex_lock(&fs_devices->device_list_mutex);
572 list_for_each_entry_safe(device, tmp_device,
573 &fs_devices->devices, dev_list) {
574 if (skip_device && skip_device == device)
576 if (path && !device->name)
578 if (path && !device_path_matched(path, device))
580 if (fs_devices->opened) {
581 /* for an already deleted device return 0 */
582 if (path && ret != 0)
587 /* delete the stale device */
588 fs_devices->num_devices--;
589 list_del(&device->dev_list);
590 btrfs_free_device(device);
593 if (fs_devices->num_devices == 0)
596 mutex_unlock(&fs_devices->device_list_mutex);
598 if (fs_devices->num_devices == 0) {
599 btrfs_sysfs_remove_fsid(fs_devices);
600 list_del(&fs_devices->fs_list);
601 free_fs_devices(fs_devices);
608 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
609 struct btrfs_device *device, fmode_t flags,
612 struct request_queue *q;
613 struct block_device *bdev;
614 struct buffer_head *bh;
615 struct btrfs_super_block *disk_super;
624 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
629 disk_super = (struct btrfs_super_block *)bh->b_data;
630 devid = btrfs_stack_device_id(&disk_super->dev_item);
631 if (devid != device->devid)
634 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
637 device->generation = btrfs_super_generation(disk_super);
639 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
640 if (btrfs_super_incompat_flags(disk_super) &
641 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
643 "BTRFS: Invalid seeding and uuid-changed device detected\n");
647 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
648 fs_devices->seeding = true;
650 if (bdev_read_only(bdev))
651 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
653 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
656 q = bdev_get_queue(bdev);
657 if (!blk_queue_nonrot(q))
658 fs_devices->rotating = true;
661 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
662 device->mode = flags;
664 fs_devices->open_devices++;
665 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
666 device->devid != BTRFS_DEV_REPLACE_DEVID) {
667 fs_devices->rw_devices++;
668 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
676 blkdev_put(bdev, flags);
682 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
683 * being created with a disk that has already completed its fsid change. Such
684 * disk can belong to an fs which has its FSID changed or to one which doesn't.
685 * Handle both cases here.
687 static struct btrfs_fs_devices *find_fsid_inprogress(
688 struct btrfs_super_block *disk_super)
690 struct btrfs_fs_devices *fs_devices;
692 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
693 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
694 BTRFS_FSID_SIZE) != 0 &&
695 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
696 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
701 return find_fsid(disk_super->fsid, NULL);
705 static struct btrfs_fs_devices *find_fsid_changed(
706 struct btrfs_super_block *disk_super)
708 struct btrfs_fs_devices *fs_devices;
711 * Handles the case where scanned device is part of an fs that had
712 * multiple successful changes of FSID but curently device didn't
713 * observe it. Meaning our fsid will be different than theirs.
715 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
716 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
717 BTRFS_FSID_SIZE) != 0 &&
718 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
719 BTRFS_FSID_SIZE) == 0 &&
720 memcmp(fs_devices->fsid, disk_super->fsid,
721 BTRFS_FSID_SIZE) != 0) {
729 * Add new device to list of registered devices
732 * device pointer which was just added or updated when successful
733 * error pointer when failed
735 static noinline struct btrfs_device *device_list_add(const char *path,
736 struct btrfs_super_block *disk_super,
737 bool *new_device_added)
739 struct btrfs_device *device;
740 struct btrfs_fs_devices *fs_devices = NULL;
741 struct rcu_string *name;
742 u64 found_transid = btrfs_super_generation(disk_super);
743 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
744 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
745 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
746 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
747 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
749 if (fsid_change_in_progress) {
750 if (!has_metadata_uuid)
751 fs_devices = find_fsid_inprogress(disk_super);
753 fs_devices = find_fsid_changed(disk_super);
754 } else if (has_metadata_uuid) {
755 fs_devices = find_fsid_with_metadata_uuid(disk_super);
757 fs_devices = find_fsid(disk_super->fsid, NULL);
762 if (has_metadata_uuid)
763 fs_devices = alloc_fs_devices(disk_super->fsid,
764 disk_super->metadata_uuid);
766 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
768 if (IS_ERR(fs_devices))
769 return ERR_CAST(fs_devices);
771 fs_devices->fsid_change = fsid_change_in_progress;
773 mutex_lock(&fs_devices->device_list_mutex);
774 list_add(&fs_devices->fs_list, &fs_uuids);
778 mutex_lock(&fs_devices->device_list_mutex);
779 device = btrfs_find_device(fs_devices, devid,
780 disk_super->dev_item.uuid, NULL, false);
783 * If this disk has been pulled into an fs devices created by
784 * a device which had the CHANGING_FSID_V2 flag then replace the
785 * metadata_uuid/fsid values of the fs_devices.
787 if (has_metadata_uuid && fs_devices->fsid_change &&
788 found_transid > fs_devices->latest_generation) {
789 memcpy(fs_devices->fsid, disk_super->fsid,
791 memcpy(fs_devices->metadata_uuid,
792 disk_super->metadata_uuid, BTRFS_FSID_SIZE);
794 fs_devices->fsid_change = false;
799 if (fs_devices->opened) {
800 mutex_unlock(&fs_devices->device_list_mutex);
801 return ERR_PTR(-EBUSY);
804 device = btrfs_alloc_device(NULL, &devid,
805 disk_super->dev_item.uuid);
806 if (IS_ERR(device)) {
807 mutex_unlock(&fs_devices->device_list_mutex);
808 /* we can safely leave the fs_devices entry around */
812 name = rcu_string_strdup(path, GFP_NOFS);
814 btrfs_free_device(device);
815 mutex_unlock(&fs_devices->device_list_mutex);
816 return ERR_PTR(-ENOMEM);
818 rcu_assign_pointer(device->name, name);
820 list_add_rcu(&device->dev_list, &fs_devices->devices);
821 fs_devices->num_devices++;
823 device->fs_devices = fs_devices;
824 *new_device_added = true;
826 if (disk_super->label[0])
828 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n",
829 disk_super->label, devid, found_transid, path,
830 current->comm, task_pid_nr(current));
833 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n",
834 disk_super->fsid, devid, found_transid, path,
835 current->comm, task_pid_nr(current));
837 } else if (!device->name || strcmp(device->name->str, path)) {
839 * When FS is already mounted.
840 * 1. If you are here and if the device->name is NULL that
841 * means this device was missing at time of FS mount.
842 * 2. If you are here and if the device->name is different
843 * from 'path' that means either
844 * a. The same device disappeared and reappeared with
846 * b. The missing-disk-which-was-replaced, has
849 * We must allow 1 and 2a above. But 2b would be a spurious
852 * Further in case of 1 and 2a above, the disk at 'path'
853 * would have missed some transaction when it was away and
854 * in case of 2a the stale bdev has to be updated as well.
855 * 2b must not be allowed at all time.
859 * For now, we do allow update to btrfs_fs_device through the
860 * btrfs dev scan cli after FS has been mounted. We're still
861 * tracking a problem where systems fail mount by subvolume id
862 * when we reject replacement on a mounted FS.
864 if (!fs_devices->opened && found_transid < device->generation) {
866 * That is if the FS is _not_ mounted and if you
867 * are here, that means there is more than one
868 * disk with same uuid and devid.We keep the one
869 * with larger generation number or the last-in if
870 * generation are equal.
872 mutex_unlock(&fs_devices->device_list_mutex);
873 return ERR_PTR(-EEXIST);
877 * We are going to replace the device path for a given devid,
878 * make sure it's the same device if the device is mounted
881 struct block_device *path_bdev;
883 path_bdev = lookup_bdev(path);
884 if (IS_ERR(path_bdev)) {
885 mutex_unlock(&fs_devices->device_list_mutex);
886 return ERR_CAST(path_bdev);
889 if (device->bdev != path_bdev) {
891 mutex_unlock(&fs_devices->device_list_mutex);
892 btrfs_warn_in_rcu(device->fs_info,
893 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
894 disk_super->fsid, devid,
895 rcu_str_deref(device->name), path);
896 return ERR_PTR(-EEXIST);
899 btrfs_info_in_rcu(device->fs_info,
900 "device fsid %pU devid %llu moved old:%s new:%s",
901 disk_super->fsid, devid,
902 rcu_str_deref(device->name), path);
905 name = rcu_string_strdup(path, GFP_NOFS);
907 mutex_unlock(&fs_devices->device_list_mutex);
908 return ERR_PTR(-ENOMEM);
910 rcu_string_free(device->name);
911 rcu_assign_pointer(device->name, name);
912 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
913 fs_devices->missing_devices--;
914 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
919 * Unmount does not free the btrfs_device struct but would zero
920 * generation along with most of the other members. So just update
921 * it back. We need it to pick the disk with largest generation
924 if (!fs_devices->opened) {
925 device->generation = found_transid;
926 fs_devices->latest_generation = max_t(u64, found_transid,
927 fs_devices->latest_generation);
930 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
932 mutex_unlock(&fs_devices->device_list_mutex);
936 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
938 struct btrfs_fs_devices *fs_devices;
939 struct btrfs_device *device;
940 struct btrfs_device *orig_dev;
943 fs_devices = alloc_fs_devices(orig->fsid, NULL);
944 if (IS_ERR(fs_devices))
947 mutex_lock(&orig->device_list_mutex);
948 fs_devices->total_devices = orig->total_devices;
950 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
951 struct rcu_string *name;
953 device = btrfs_alloc_device(NULL, &orig_dev->devid,
955 if (IS_ERR(device)) {
956 ret = PTR_ERR(device);
961 * This is ok to do without rcu read locked because we hold the
962 * uuid mutex so nothing we touch in here is going to disappear.
964 if (orig_dev->name) {
965 name = rcu_string_strdup(orig_dev->name->str,
968 btrfs_free_device(device);
972 rcu_assign_pointer(device->name, name);
975 list_add(&device->dev_list, &fs_devices->devices);
976 device->fs_devices = fs_devices;
977 fs_devices->num_devices++;
979 mutex_unlock(&orig->device_list_mutex);
982 mutex_unlock(&orig->device_list_mutex);
983 free_fs_devices(fs_devices);
988 * After we have read the system tree and know devids belonging to
989 * this filesystem, remove the device which does not belong there.
991 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
993 struct btrfs_device *device, *next;
994 struct btrfs_device *latest_dev = NULL;
996 mutex_lock(&uuid_mutex);
998 /* This is the initialized path, it is safe to release the devices. */
999 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1000 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1001 &device->dev_state)) {
1002 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1003 &device->dev_state) &&
1005 device->generation > latest_dev->generation)) {
1006 latest_dev = device;
1011 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1013 * In the first step, keep the device which has
1014 * the correct fsid and the devid that is used
1015 * for the dev_replace procedure.
1016 * In the second step, the dev_replace state is
1017 * read from the device tree and it is known
1018 * whether the procedure is really active or
1019 * not, which means whether this device is
1020 * used or whether it should be removed.
1022 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1023 &device->dev_state)) {
1028 blkdev_put(device->bdev, device->mode);
1029 device->bdev = NULL;
1030 fs_devices->open_devices--;
1032 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1033 list_del_init(&device->dev_alloc_list);
1034 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1035 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1036 &device->dev_state))
1037 fs_devices->rw_devices--;
1039 list_del_init(&device->dev_list);
1040 fs_devices->num_devices--;
1041 btrfs_free_device(device);
1044 if (fs_devices->seed) {
1045 fs_devices = fs_devices->seed;
1049 fs_devices->latest_bdev = latest_dev->bdev;
1051 mutex_unlock(&uuid_mutex);
1054 static void btrfs_close_bdev(struct btrfs_device *device)
1059 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1060 sync_blockdev(device->bdev);
1061 invalidate_bdev(device->bdev);
1064 blkdev_put(device->bdev, device->mode);
1067 static void btrfs_close_one_device(struct btrfs_device *device)
1069 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1071 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1072 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1073 list_del_init(&device->dev_alloc_list);
1074 fs_devices->rw_devices--;
1077 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1078 fs_devices->missing_devices--;
1080 btrfs_close_bdev(device);
1082 fs_devices->open_devices--;
1083 device->bdev = NULL;
1085 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1087 device->fs_info = NULL;
1088 atomic_set(&device->dev_stats_ccnt, 0);
1089 extent_io_tree_release(&device->alloc_state);
1091 /* Verify the device is back in a pristine state */
1092 ASSERT(!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1093 ASSERT(!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1094 ASSERT(list_empty(&device->dev_alloc_list));
1095 ASSERT(list_empty(&device->post_commit_list));
1096 ASSERT(atomic_read(&device->reada_in_flight) == 0);
1099 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1101 struct btrfs_device *device, *tmp;
1103 if (--fs_devices->opened > 0)
1106 mutex_lock(&fs_devices->device_list_mutex);
1107 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1108 btrfs_close_one_device(device);
1110 mutex_unlock(&fs_devices->device_list_mutex);
1112 WARN_ON(fs_devices->open_devices);
1113 WARN_ON(fs_devices->rw_devices);
1114 fs_devices->opened = 0;
1115 fs_devices->seeding = false;
1120 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1122 struct btrfs_fs_devices *seed_devices = NULL;
1125 mutex_lock(&uuid_mutex);
1126 ret = close_fs_devices(fs_devices);
1127 if (!fs_devices->opened) {
1128 seed_devices = fs_devices->seed;
1129 fs_devices->seed = NULL;
1131 mutex_unlock(&uuid_mutex);
1133 while (seed_devices) {
1134 fs_devices = seed_devices;
1135 seed_devices = fs_devices->seed;
1136 close_fs_devices(fs_devices);
1137 free_fs_devices(fs_devices);
1142 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1143 fmode_t flags, void *holder)
1145 struct btrfs_device *device;
1146 struct btrfs_device *latest_dev = NULL;
1149 flags |= FMODE_EXCL;
1151 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1152 /* Just open everything we can; ignore failures here */
1153 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1157 device->generation > latest_dev->generation)
1158 latest_dev = device;
1160 if (fs_devices->open_devices == 0) {
1164 fs_devices->opened = 1;
1165 fs_devices->latest_bdev = latest_dev->bdev;
1166 fs_devices->total_rw_bytes = 0;
1171 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1173 struct btrfs_device *dev1, *dev2;
1175 dev1 = list_entry(a, struct btrfs_device, dev_list);
1176 dev2 = list_entry(b, struct btrfs_device, dev_list);
1178 if (dev1->devid < dev2->devid)
1180 else if (dev1->devid > dev2->devid)
1185 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1186 fmode_t flags, void *holder)
1190 lockdep_assert_held(&uuid_mutex);
1192 mutex_lock(&fs_devices->device_list_mutex);
1193 if (fs_devices->opened) {
1194 fs_devices->opened++;
1197 list_sort(NULL, &fs_devices->devices, devid_cmp);
1198 ret = open_fs_devices(fs_devices, flags, holder);
1200 mutex_unlock(&fs_devices->device_list_mutex);
1205 static void btrfs_release_disk_super(struct page *page)
1211 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1213 struct btrfs_super_block **disk_super)
1218 /* make sure our super fits in the device */
1219 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1222 /* make sure our super fits in the page */
1223 if (sizeof(**disk_super) > PAGE_SIZE)
1226 /* make sure our super doesn't straddle pages on disk */
1227 index = bytenr >> PAGE_SHIFT;
1228 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1231 /* pull in the page with our super */
1232 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1235 if (IS_ERR_OR_NULL(*page))
1240 /* align our pointer to the offset of the super block */
1241 *disk_super = p + offset_in_page(bytenr);
1243 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1244 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1245 btrfs_release_disk_super(*page);
1249 if ((*disk_super)->label[0] &&
1250 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1251 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1256 int btrfs_forget_devices(const char *path)
1260 mutex_lock(&uuid_mutex);
1261 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1262 mutex_unlock(&uuid_mutex);
1268 * Look for a btrfs signature on a device. This may be called out of the mount path
1269 * and we are not allowed to call set_blocksize during the scan. The superblock
1270 * is read via pagecache
1272 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1275 struct btrfs_super_block *disk_super;
1276 bool new_device_added = false;
1277 struct btrfs_device *device = NULL;
1278 struct block_device *bdev;
1282 lockdep_assert_held(&uuid_mutex);
1285 * we would like to check all the supers, but that would make
1286 * a btrfs mount succeed after a mkfs from a different FS.
1287 * So, we need to add a special mount option to scan for
1288 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1290 bytenr = btrfs_sb_offset(0);
1291 flags |= FMODE_EXCL;
1293 bdev = blkdev_get_by_path(path, flags, holder);
1295 return ERR_CAST(bdev);
1297 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1298 device = ERR_PTR(-EINVAL);
1299 goto error_bdev_put;
1302 device = device_list_add(path, disk_super, &new_device_added);
1303 if (!IS_ERR(device)) {
1304 if (new_device_added)
1305 btrfs_free_stale_devices(path, device);
1308 btrfs_release_disk_super(page);
1311 blkdev_put(bdev, flags);
1317 * Try to find a chunk that intersects [start, start + len] range and when one
1318 * such is found, record the end of it in *start
1320 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1323 u64 physical_start, physical_end;
1325 lockdep_assert_held(&device->fs_info->chunk_mutex);
1327 if (!find_first_extent_bit(&device->alloc_state, *start,
1328 &physical_start, &physical_end,
1329 CHUNK_ALLOCATED, NULL)) {
1331 if (in_range(physical_start, *start, len) ||
1332 in_range(*start, physical_start,
1333 physical_end - physical_start)) {
1334 *start = physical_end + 1;
1343 * find_free_dev_extent_start - find free space in the specified device
1344 * @device: the device which we search the free space in
1345 * @num_bytes: the size of the free space that we need
1346 * @search_start: the position from which to begin the search
1347 * @start: store the start of the free space.
1348 * @len: the size of the free space. that we find, or the size
1349 * of the max free space if we don't find suitable free space
1351 * this uses a pretty simple search, the expectation is that it is
1352 * called very infrequently and that a given device has a small number
1355 * @start is used to store the start of the free space if we find. But if we
1356 * don't find suitable free space, it will be used to store the start position
1357 * of the max free space.
1359 * @len is used to store the size of the free space that we find.
1360 * But if we don't find suitable free space, it is used to store the size of
1361 * the max free space.
1363 * NOTE: This function will search *commit* root of device tree, and does extra
1364 * check to ensure dev extents are not double allocated.
1365 * This makes the function safe to allocate dev extents but may not report
1366 * correct usable device space, as device extent freed in current transaction
1367 * is not reported as avaiable.
1369 static int find_free_dev_extent_start(struct btrfs_device *device,
1370 u64 num_bytes, u64 search_start, u64 *start,
1373 struct btrfs_fs_info *fs_info = device->fs_info;
1374 struct btrfs_root *root = fs_info->dev_root;
1375 struct btrfs_key key;
1376 struct btrfs_dev_extent *dev_extent;
1377 struct btrfs_path *path;
1382 u64 search_end = device->total_bytes;
1385 struct extent_buffer *l;
1388 * We don't want to overwrite the superblock on the drive nor any area
1389 * used by the boot loader (grub for example), so we make sure to start
1390 * at an offset of at least 1MB.
1392 search_start = max_t(u64, search_start, SZ_1M);
1394 path = btrfs_alloc_path();
1398 max_hole_start = search_start;
1402 if (search_start >= search_end ||
1403 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1408 path->reada = READA_FORWARD;
1409 path->search_commit_root = 1;
1410 path->skip_locking = 1;
1412 key.objectid = device->devid;
1413 key.offset = search_start;
1414 key.type = BTRFS_DEV_EXTENT_KEY;
1416 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1420 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1427 slot = path->slots[0];
1428 if (slot >= btrfs_header_nritems(l)) {
1429 ret = btrfs_next_leaf(root, path);
1437 btrfs_item_key_to_cpu(l, &key, slot);
1439 if (key.objectid < device->devid)
1442 if (key.objectid > device->devid)
1445 if (key.type != BTRFS_DEV_EXTENT_KEY)
1448 if (key.offset > search_start) {
1449 hole_size = key.offset - search_start;
1452 * Have to check before we set max_hole_start, otherwise
1453 * we could end up sending back this offset anyway.
1455 if (contains_pending_extent(device, &search_start,
1457 if (key.offset >= search_start)
1458 hole_size = key.offset - search_start;
1463 if (hole_size > max_hole_size) {
1464 max_hole_start = search_start;
1465 max_hole_size = hole_size;
1469 * If this free space is greater than which we need,
1470 * it must be the max free space that we have found
1471 * until now, so max_hole_start must point to the start
1472 * of this free space and the length of this free space
1473 * is stored in max_hole_size. Thus, we return
1474 * max_hole_start and max_hole_size and go back to the
1477 if (hole_size >= num_bytes) {
1483 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1484 extent_end = key.offset + btrfs_dev_extent_length(l,
1486 if (extent_end > search_start)
1487 search_start = extent_end;
1494 * At this point, search_start should be the end of
1495 * allocated dev extents, and when shrinking the device,
1496 * search_end may be smaller than search_start.
1498 if (search_end > search_start) {
1499 hole_size = search_end - search_start;
1501 if (contains_pending_extent(device, &search_start, hole_size)) {
1502 btrfs_release_path(path);
1506 if (hole_size > max_hole_size) {
1507 max_hole_start = search_start;
1508 max_hole_size = hole_size;
1513 if (max_hole_size < num_bytes)
1519 btrfs_free_path(path);
1520 *start = max_hole_start;
1522 *len = max_hole_size;
1526 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1527 u64 *start, u64 *len)
1529 /* FIXME use last free of some kind */
1530 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1533 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1534 struct btrfs_device *device,
1535 u64 start, u64 *dev_extent_len)
1537 struct btrfs_fs_info *fs_info = device->fs_info;
1538 struct btrfs_root *root = fs_info->dev_root;
1540 struct btrfs_path *path;
1541 struct btrfs_key key;
1542 struct btrfs_key found_key;
1543 struct extent_buffer *leaf = NULL;
1544 struct btrfs_dev_extent *extent = NULL;
1546 path = btrfs_alloc_path();
1550 key.objectid = device->devid;
1552 key.type = BTRFS_DEV_EXTENT_KEY;
1554 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1556 ret = btrfs_previous_item(root, path, key.objectid,
1557 BTRFS_DEV_EXTENT_KEY);
1560 leaf = path->nodes[0];
1561 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1562 extent = btrfs_item_ptr(leaf, path->slots[0],
1563 struct btrfs_dev_extent);
1564 BUG_ON(found_key.offset > start || found_key.offset +
1565 btrfs_dev_extent_length(leaf, extent) < start);
1567 btrfs_release_path(path);
1569 } else if (ret == 0) {
1570 leaf = path->nodes[0];
1571 extent = btrfs_item_ptr(leaf, path->slots[0],
1572 struct btrfs_dev_extent);
1574 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1578 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1580 ret = btrfs_del_item(trans, root, path);
1582 btrfs_handle_fs_error(fs_info, ret,
1583 "Failed to remove dev extent item");
1585 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1588 btrfs_free_path(path);
1592 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1593 struct btrfs_device *device,
1594 u64 chunk_offset, u64 start, u64 num_bytes)
1597 struct btrfs_path *path;
1598 struct btrfs_fs_info *fs_info = device->fs_info;
1599 struct btrfs_root *root = fs_info->dev_root;
1600 struct btrfs_dev_extent *extent;
1601 struct extent_buffer *leaf;
1602 struct btrfs_key key;
1604 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1605 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1606 path = btrfs_alloc_path();
1610 key.objectid = device->devid;
1612 key.type = BTRFS_DEV_EXTENT_KEY;
1613 ret = btrfs_insert_empty_item(trans, root, path, &key,
1618 leaf = path->nodes[0];
1619 extent = btrfs_item_ptr(leaf, path->slots[0],
1620 struct btrfs_dev_extent);
1621 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1622 BTRFS_CHUNK_TREE_OBJECTID);
1623 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1624 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1625 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1627 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1628 btrfs_mark_buffer_dirty(leaf);
1630 btrfs_free_path(path);
1634 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1636 struct extent_map_tree *em_tree;
1637 struct extent_map *em;
1641 em_tree = &fs_info->mapping_tree;
1642 read_lock(&em_tree->lock);
1643 n = rb_last(&em_tree->map.rb_root);
1645 em = rb_entry(n, struct extent_map, rb_node);
1646 ret = em->start + em->len;
1648 read_unlock(&em_tree->lock);
1653 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1657 struct btrfs_key key;
1658 struct btrfs_key found_key;
1659 struct btrfs_path *path;
1661 path = btrfs_alloc_path();
1665 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1666 key.type = BTRFS_DEV_ITEM_KEY;
1667 key.offset = (u64)-1;
1669 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1675 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1680 ret = btrfs_previous_item(fs_info->chunk_root, path,
1681 BTRFS_DEV_ITEMS_OBJECTID,
1682 BTRFS_DEV_ITEM_KEY);
1686 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1688 *devid_ret = found_key.offset + 1;
1692 btrfs_free_path(path);
1697 * the device information is stored in the chunk root
1698 * the btrfs_device struct should be fully filled in
1700 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1701 struct btrfs_device *device)
1704 struct btrfs_path *path;
1705 struct btrfs_dev_item *dev_item;
1706 struct extent_buffer *leaf;
1707 struct btrfs_key key;
1710 path = btrfs_alloc_path();
1714 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1715 key.type = BTRFS_DEV_ITEM_KEY;
1716 key.offset = device->devid;
1718 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1719 &key, sizeof(*dev_item));
1723 leaf = path->nodes[0];
1724 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1726 btrfs_set_device_id(leaf, dev_item, device->devid);
1727 btrfs_set_device_generation(leaf, dev_item, 0);
1728 btrfs_set_device_type(leaf, dev_item, device->type);
1729 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1730 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1731 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1732 btrfs_set_device_total_bytes(leaf, dev_item,
1733 btrfs_device_get_disk_total_bytes(device));
1734 btrfs_set_device_bytes_used(leaf, dev_item,
1735 btrfs_device_get_bytes_used(device));
1736 btrfs_set_device_group(leaf, dev_item, 0);
1737 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1738 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1739 btrfs_set_device_start_offset(leaf, dev_item, 0);
1741 ptr = btrfs_device_uuid(dev_item);
1742 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1743 ptr = btrfs_device_fsid(dev_item);
1744 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1745 ptr, BTRFS_FSID_SIZE);
1746 btrfs_mark_buffer_dirty(leaf);
1750 btrfs_free_path(path);
1755 * Function to update ctime/mtime for a given device path.
1756 * Mainly used for ctime/mtime based probe like libblkid.
1758 static void update_dev_time(const char *path_name)
1762 filp = filp_open(path_name, O_RDWR, 0);
1765 file_update_time(filp);
1766 filp_close(filp, NULL);
1769 static int btrfs_rm_dev_item(struct btrfs_device *device)
1771 struct btrfs_root *root = device->fs_info->chunk_root;
1773 struct btrfs_path *path;
1774 struct btrfs_key key;
1775 struct btrfs_trans_handle *trans;
1777 path = btrfs_alloc_path();
1781 trans = btrfs_start_transaction(root, 0);
1782 if (IS_ERR(trans)) {
1783 btrfs_free_path(path);
1784 return PTR_ERR(trans);
1786 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1787 key.type = BTRFS_DEV_ITEM_KEY;
1788 key.offset = device->devid;
1790 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1794 btrfs_abort_transaction(trans, ret);
1795 btrfs_end_transaction(trans);
1799 ret = btrfs_del_item(trans, root, path);
1801 btrfs_abort_transaction(trans, ret);
1802 btrfs_end_transaction(trans);
1806 btrfs_free_path(path);
1808 ret = btrfs_commit_transaction(trans);
1813 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1814 * filesystem. It's up to the caller to adjust that number regarding eg. device
1817 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1825 seq = read_seqbegin(&fs_info->profiles_lock);
1827 all_avail = fs_info->avail_data_alloc_bits |
1828 fs_info->avail_system_alloc_bits |
1829 fs_info->avail_metadata_alloc_bits;
1830 } while (read_seqretry(&fs_info->profiles_lock, seq));
1832 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1833 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1836 if (num_devices < btrfs_raid_array[i].devs_min) {
1837 int ret = btrfs_raid_array[i].mindev_error;
1847 static struct btrfs_device * btrfs_find_next_active_device(
1848 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1850 struct btrfs_device *next_device;
1852 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1853 if (next_device != device &&
1854 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1855 && next_device->bdev)
1863 * Helper function to check if the given device is part of s_bdev / latest_bdev
1864 * and replace it with the provided or the next active device, in the context
1865 * where this function called, there should be always be another device (or
1866 * this_dev) which is active.
1868 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
1869 struct btrfs_device *this_dev)
1871 struct btrfs_fs_info *fs_info = device->fs_info;
1872 struct btrfs_device *next_device;
1875 next_device = this_dev;
1877 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1879 ASSERT(next_device);
1881 if (fs_info->sb->s_bdev &&
1882 (fs_info->sb->s_bdev == device->bdev))
1883 fs_info->sb->s_bdev = next_device->bdev;
1885 if (fs_info->fs_devices->latest_bdev == device->bdev)
1886 fs_info->fs_devices->latest_bdev = next_device->bdev;
1890 * Return btrfs_fs_devices::num_devices excluding the device that's being
1891 * currently replaced.
1893 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1895 u64 num_devices = fs_info->fs_devices->num_devices;
1897 down_read(&fs_info->dev_replace.rwsem);
1898 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1899 ASSERT(num_devices > 1);
1902 up_read(&fs_info->dev_replace.rwsem);
1907 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1910 struct btrfs_device *device;
1911 struct btrfs_fs_devices *cur_devices;
1912 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1916 mutex_lock(&uuid_mutex);
1918 num_devices = btrfs_num_devices(fs_info);
1920 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1924 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
1926 if (IS_ERR(device)) {
1927 if (PTR_ERR(device) == -ENOENT &&
1928 strcmp(device_path, "missing") == 0)
1929 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1931 ret = PTR_ERR(device);
1935 if (btrfs_pinned_by_swapfile(fs_info, device)) {
1936 btrfs_warn_in_rcu(fs_info,
1937 "cannot remove device %s (devid %llu) due to active swapfile",
1938 rcu_str_deref(device->name), device->devid);
1943 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1944 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1948 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1949 fs_info->fs_devices->rw_devices == 1) {
1950 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1954 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1955 mutex_lock(&fs_info->chunk_mutex);
1956 list_del_init(&device->dev_alloc_list);
1957 device->fs_devices->rw_devices--;
1958 mutex_unlock(&fs_info->chunk_mutex);
1961 mutex_unlock(&uuid_mutex);
1962 ret = btrfs_shrink_device(device, 0);
1963 mutex_lock(&uuid_mutex);
1968 * TODO: the superblock still includes this device in its num_devices
1969 * counter although write_all_supers() is not locked out. This
1970 * could give a filesystem state which requires a degraded mount.
1972 ret = btrfs_rm_dev_item(device);
1976 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
1977 btrfs_scrub_cancel_dev(device);
1980 * the device list mutex makes sure that we don't change
1981 * the device list while someone else is writing out all
1982 * the device supers. Whoever is writing all supers, should
1983 * lock the device list mutex before getting the number of
1984 * devices in the super block (super_copy). Conversely,
1985 * whoever updates the number of devices in the super block
1986 * (super_copy) should hold the device list mutex.
1990 * In normal cases the cur_devices == fs_devices. But in case
1991 * of deleting a seed device, the cur_devices should point to
1992 * its own fs_devices listed under the fs_devices->seed.
1994 cur_devices = device->fs_devices;
1995 mutex_lock(&fs_devices->device_list_mutex);
1996 list_del_rcu(&device->dev_list);
1998 cur_devices->num_devices--;
1999 cur_devices->total_devices--;
2000 /* Update total_devices of the parent fs_devices if it's seed */
2001 if (cur_devices != fs_devices)
2002 fs_devices->total_devices--;
2004 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2005 cur_devices->missing_devices--;
2007 btrfs_assign_next_active_device(device, NULL);
2010 cur_devices->open_devices--;
2011 /* remove sysfs entry */
2012 btrfs_sysfs_rm_device_link(fs_devices, device);
2015 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2016 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2017 mutex_unlock(&fs_devices->device_list_mutex);
2020 * at this point, the device is zero sized and detached from
2021 * the devices list. All that's left is to zero out the old
2022 * supers and free the device.
2024 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2025 btrfs_scratch_superblocks(device->bdev, device->name->str);
2027 btrfs_close_bdev(device);
2029 btrfs_free_device(device);
2031 if (cur_devices->open_devices == 0) {
2032 while (fs_devices) {
2033 if (fs_devices->seed == cur_devices) {
2034 fs_devices->seed = cur_devices->seed;
2037 fs_devices = fs_devices->seed;
2039 cur_devices->seed = NULL;
2040 close_fs_devices(cur_devices);
2041 free_fs_devices(cur_devices);
2045 mutex_unlock(&uuid_mutex);
2049 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2050 mutex_lock(&fs_info->chunk_mutex);
2051 list_add(&device->dev_alloc_list,
2052 &fs_devices->alloc_list);
2053 device->fs_devices->rw_devices++;
2054 mutex_unlock(&fs_info->chunk_mutex);
2059 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2061 struct btrfs_fs_devices *fs_devices;
2063 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2066 * in case of fs with no seed, srcdev->fs_devices will point
2067 * to fs_devices of fs_info. However when the dev being replaced is
2068 * a seed dev it will point to the seed's local fs_devices. In short
2069 * srcdev will have its correct fs_devices in both the cases.
2071 fs_devices = srcdev->fs_devices;
2073 list_del_rcu(&srcdev->dev_list);
2074 list_del(&srcdev->dev_alloc_list);
2075 fs_devices->num_devices--;
2076 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2077 fs_devices->missing_devices--;
2079 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2080 fs_devices->rw_devices--;
2083 fs_devices->open_devices--;
2086 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2088 struct btrfs_fs_info *fs_info = srcdev->fs_info;
2089 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2091 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2092 /* zero out the old super if it is writable */
2093 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2096 btrfs_close_bdev(srcdev);
2098 btrfs_free_device(srcdev);
2100 /* if this is no devs we rather delete the fs_devices */
2101 if (!fs_devices->num_devices) {
2102 struct btrfs_fs_devices *tmp_fs_devices;
2105 * On a mounted FS, num_devices can't be zero unless it's a
2106 * seed. In case of a seed device being replaced, the replace
2107 * target added to the sprout FS, so there will be no more
2108 * device left under the seed FS.
2110 ASSERT(fs_devices->seeding);
2112 tmp_fs_devices = fs_info->fs_devices;
2113 while (tmp_fs_devices) {
2114 if (tmp_fs_devices->seed == fs_devices) {
2115 tmp_fs_devices->seed = fs_devices->seed;
2118 tmp_fs_devices = tmp_fs_devices->seed;
2120 fs_devices->seed = NULL;
2121 close_fs_devices(fs_devices);
2122 free_fs_devices(fs_devices);
2126 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2128 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2130 mutex_lock(&fs_devices->device_list_mutex);
2132 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2135 fs_devices->open_devices--;
2137 fs_devices->num_devices--;
2139 btrfs_assign_next_active_device(tgtdev, NULL);
2141 list_del_rcu(&tgtdev->dev_list);
2143 mutex_unlock(&fs_devices->device_list_mutex);
2146 * The update_dev_time() with in btrfs_scratch_superblocks()
2147 * may lead to a call to btrfs_show_devname() which will try
2148 * to hold device_list_mutex. And here this device
2149 * is already out of device list, so we don't have to hold
2150 * the device_list_mutex lock.
2152 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2154 btrfs_close_bdev(tgtdev);
2156 btrfs_free_device(tgtdev);
2159 static struct btrfs_device *btrfs_find_device_by_path(
2160 struct btrfs_fs_info *fs_info, const char *device_path)
2163 struct btrfs_super_block *disk_super;
2166 struct block_device *bdev;
2167 struct buffer_head *bh;
2168 struct btrfs_device *device;
2170 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2171 fs_info->bdev_holder, 0, &bdev, &bh);
2173 return ERR_PTR(ret);
2174 disk_super = (struct btrfs_super_block *)bh->b_data;
2175 devid = btrfs_stack_device_id(&disk_super->dev_item);
2176 dev_uuid = disk_super->dev_item.uuid;
2177 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2178 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2179 disk_super->metadata_uuid, true);
2181 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2182 disk_super->fsid, true);
2186 device = ERR_PTR(-ENOENT);
2187 blkdev_put(bdev, FMODE_READ);
2192 * Lookup a device given by device id, or the path if the id is 0.
2194 struct btrfs_device *btrfs_find_device_by_devspec(
2195 struct btrfs_fs_info *fs_info, u64 devid,
2196 const char *device_path)
2198 struct btrfs_device *device;
2201 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2204 return ERR_PTR(-ENOENT);
2208 if (!device_path || !device_path[0])
2209 return ERR_PTR(-EINVAL);
2211 if (strcmp(device_path, "missing") == 0) {
2212 /* Find first missing device */
2213 list_for_each_entry(device, &fs_info->fs_devices->devices,
2215 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2216 &device->dev_state) && !device->bdev)
2219 return ERR_PTR(-ENOENT);
2222 return btrfs_find_device_by_path(fs_info, device_path);
2226 * does all the dirty work required for changing file system's UUID.
2228 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2230 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2231 struct btrfs_fs_devices *old_devices;
2232 struct btrfs_fs_devices *seed_devices;
2233 struct btrfs_super_block *disk_super = fs_info->super_copy;
2234 struct btrfs_device *device;
2237 lockdep_assert_held(&uuid_mutex);
2238 if (!fs_devices->seeding)
2241 seed_devices = alloc_fs_devices(NULL, NULL);
2242 if (IS_ERR(seed_devices))
2243 return PTR_ERR(seed_devices);
2245 old_devices = clone_fs_devices(fs_devices);
2246 if (IS_ERR(old_devices)) {
2247 kfree(seed_devices);
2248 return PTR_ERR(old_devices);
2251 list_add(&old_devices->fs_list, &fs_uuids);
2253 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2254 seed_devices->opened = 1;
2255 INIT_LIST_HEAD(&seed_devices->devices);
2256 INIT_LIST_HEAD(&seed_devices->alloc_list);
2257 mutex_init(&seed_devices->device_list_mutex);
2259 mutex_lock(&fs_devices->device_list_mutex);
2260 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2262 list_for_each_entry(device, &seed_devices->devices, dev_list)
2263 device->fs_devices = seed_devices;
2265 mutex_lock(&fs_info->chunk_mutex);
2266 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2267 mutex_unlock(&fs_info->chunk_mutex);
2269 fs_devices->seeding = false;
2270 fs_devices->num_devices = 0;
2271 fs_devices->open_devices = 0;
2272 fs_devices->missing_devices = 0;
2273 fs_devices->rotating = false;
2274 fs_devices->seed = seed_devices;
2276 generate_random_uuid(fs_devices->fsid);
2277 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2278 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2279 mutex_unlock(&fs_devices->device_list_mutex);
2281 super_flags = btrfs_super_flags(disk_super) &
2282 ~BTRFS_SUPER_FLAG_SEEDING;
2283 btrfs_set_super_flags(disk_super, super_flags);
2289 * Store the expected generation for seed devices in device items.
2291 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2293 struct btrfs_fs_info *fs_info = trans->fs_info;
2294 struct btrfs_root *root = fs_info->chunk_root;
2295 struct btrfs_path *path;
2296 struct extent_buffer *leaf;
2297 struct btrfs_dev_item *dev_item;
2298 struct btrfs_device *device;
2299 struct btrfs_key key;
2300 u8 fs_uuid[BTRFS_FSID_SIZE];
2301 u8 dev_uuid[BTRFS_UUID_SIZE];
2305 path = btrfs_alloc_path();
2309 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2311 key.type = BTRFS_DEV_ITEM_KEY;
2314 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2318 leaf = path->nodes[0];
2320 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2321 ret = btrfs_next_leaf(root, path);
2326 leaf = path->nodes[0];
2327 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2328 btrfs_release_path(path);
2332 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2333 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2334 key.type != BTRFS_DEV_ITEM_KEY)
2337 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2338 struct btrfs_dev_item);
2339 devid = btrfs_device_id(leaf, dev_item);
2340 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2342 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2344 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2346 BUG_ON(!device); /* Logic error */
2348 if (device->fs_devices->seeding) {
2349 btrfs_set_device_generation(leaf, dev_item,
2350 device->generation);
2351 btrfs_mark_buffer_dirty(leaf);
2359 btrfs_free_path(path);
2363 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2365 struct btrfs_root *root = fs_info->dev_root;
2366 struct request_queue *q;
2367 struct btrfs_trans_handle *trans;
2368 struct btrfs_device *device;
2369 struct block_device *bdev;
2370 struct super_block *sb = fs_info->sb;
2371 struct rcu_string *name;
2372 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2373 u64 orig_super_total_bytes;
2374 u64 orig_super_num_devices;
2375 int seeding_dev = 0;
2377 bool unlocked = false;
2379 if (sb_rdonly(sb) && !fs_devices->seeding)
2382 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2383 fs_info->bdev_holder);
2385 return PTR_ERR(bdev);
2387 if (fs_devices->seeding) {
2389 down_write(&sb->s_umount);
2390 mutex_lock(&uuid_mutex);
2393 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2395 mutex_lock(&fs_devices->device_list_mutex);
2396 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2397 if (device->bdev == bdev) {
2400 &fs_devices->device_list_mutex);
2404 mutex_unlock(&fs_devices->device_list_mutex);
2406 device = btrfs_alloc_device(fs_info, NULL, NULL);
2407 if (IS_ERR(device)) {
2408 /* we can safely leave the fs_devices entry around */
2409 ret = PTR_ERR(device);
2413 name = rcu_string_strdup(device_path, GFP_KERNEL);
2416 goto error_free_device;
2418 rcu_assign_pointer(device->name, name);
2420 trans = btrfs_start_transaction(root, 0);
2421 if (IS_ERR(trans)) {
2422 ret = PTR_ERR(trans);
2423 goto error_free_device;
2426 q = bdev_get_queue(bdev);
2427 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2428 device->generation = trans->transid;
2429 device->io_width = fs_info->sectorsize;
2430 device->io_align = fs_info->sectorsize;
2431 device->sector_size = fs_info->sectorsize;
2432 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2433 fs_info->sectorsize);
2434 device->disk_total_bytes = device->total_bytes;
2435 device->commit_total_bytes = device->total_bytes;
2436 device->fs_info = fs_info;
2437 device->bdev = bdev;
2438 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2439 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2440 device->mode = FMODE_EXCL;
2441 device->dev_stats_valid = 1;
2442 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2445 sb->s_flags &= ~SB_RDONLY;
2446 ret = btrfs_prepare_sprout(fs_info);
2448 btrfs_abort_transaction(trans, ret);
2453 device->fs_devices = fs_devices;
2455 mutex_lock(&fs_devices->device_list_mutex);
2456 mutex_lock(&fs_info->chunk_mutex);
2457 list_add_rcu(&device->dev_list, &fs_devices->devices);
2458 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2459 fs_devices->num_devices++;
2460 fs_devices->open_devices++;
2461 fs_devices->rw_devices++;
2462 fs_devices->total_devices++;
2463 fs_devices->total_rw_bytes += device->total_bytes;
2465 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2467 if (!blk_queue_nonrot(q))
2468 fs_devices->rotating = true;
2470 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2471 btrfs_set_super_total_bytes(fs_info->super_copy,
2472 round_down(orig_super_total_bytes + device->total_bytes,
2473 fs_info->sectorsize));
2475 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2476 btrfs_set_super_num_devices(fs_info->super_copy,
2477 orig_super_num_devices + 1);
2479 /* add sysfs device entry */
2480 btrfs_sysfs_add_device_link(fs_devices, device);
2483 * we've got more storage, clear any full flags on the space
2486 btrfs_clear_space_info_full(fs_info);
2488 mutex_unlock(&fs_info->chunk_mutex);
2489 mutex_unlock(&fs_devices->device_list_mutex);
2492 mutex_lock(&fs_info->chunk_mutex);
2493 ret = init_first_rw_device(trans);
2494 mutex_unlock(&fs_info->chunk_mutex);
2496 btrfs_abort_transaction(trans, ret);
2501 ret = btrfs_add_dev_item(trans, device);
2503 btrfs_abort_transaction(trans, ret);
2508 ret = btrfs_finish_sprout(trans);
2510 btrfs_abort_transaction(trans, ret);
2514 btrfs_sysfs_update_sprout_fsid(fs_devices,
2515 fs_info->fs_devices->fsid);
2518 ret = btrfs_commit_transaction(trans);
2521 mutex_unlock(&uuid_mutex);
2522 up_write(&sb->s_umount);
2525 if (ret) /* transaction commit */
2528 ret = btrfs_relocate_sys_chunks(fs_info);
2530 btrfs_handle_fs_error(fs_info, ret,
2531 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2532 trans = btrfs_attach_transaction(root);
2533 if (IS_ERR(trans)) {
2534 if (PTR_ERR(trans) == -ENOENT)
2536 ret = PTR_ERR(trans);
2540 ret = btrfs_commit_transaction(trans);
2543 /* Update ctime/mtime for libblkid */
2544 update_dev_time(device_path);
2548 btrfs_sysfs_rm_device_link(fs_devices, device);
2549 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2550 mutex_lock(&fs_info->chunk_mutex);
2551 list_del_rcu(&device->dev_list);
2552 list_del(&device->dev_alloc_list);
2553 fs_info->fs_devices->num_devices--;
2554 fs_info->fs_devices->open_devices--;
2555 fs_info->fs_devices->rw_devices--;
2556 fs_info->fs_devices->total_devices--;
2557 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2558 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2559 btrfs_set_super_total_bytes(fs_info->super_copy,
2560 orig_super_total_bytes);
2561 btrfs_set_super_num_devices(fs_info->super_copy,
2562 orig_super_num_devices);
2563 mutex_unlock(&fs_info->chunk_mutex);
2564 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2567 sb->s_flags |= SB_RDONLY;
2569 btrfs_end_transaction(trans);
2571 btrfs_free_device(device);
2573 blkdev_put(bdev, FMODE_EXCL);
2574 if (seeding_dev && !unlocked) {
2575 mutex_unlock(&uuid_mutex);
2576 up_write(&sb->s_umount);
2581 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2582 struct btrfs_device *device)
2585 struct btrfs_path *path;
2586 struct btrfs_root *root = device->fs_info->chunk_root;
2587 struct btrfs_dev_item *dev_item;
2588 struct extent_buffer *leaf;
2589 struct btrfs_key key;
2591 path = btrfs_alloc_path();
2595 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2596 key.type = BTRFS_DEV_ITEM_KEY;
2597 key.offset = device->devid;
2599 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2608 leaf = path->nodes[0];
2609 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2611 btrfs_set_device_id(leaf, dev_item, device->devid);
2612 btrfs_set_device_type(leaf, dev_item, device->type);
2613 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2614 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2615 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2616 btrfs_set_device_total_bytes(leaf, dev_item,
2617 btrfs_device_get_disk_total_bytes(device));
2618 btrfs_set_device_bytes_used(leaf, dev_item,
2619 btrfs_device_get_bytes_used(device));
2620 btrfs_mark_buffer_dirty(leaf);
2623 btrfs_free_path(path);
2627 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2628 struct btrfs_device *device, u64 new_size)
2630 struct btrfs_fs_info *fs_info = device->fs_info;
2631 struct btrfs_super_block *super_copy = fs_info->super_copy;
2635 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2638 new_size = round_down(new_size, fs_info->sectorsize);
2640 mutex_lock(&fs_info->chunk_mutex);
2641 old_total = btrfs_super_total_bytes(super_copy);
2642 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2644 if (new_size <= device->total_bytes ||
2645 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2646 mutex_unlock(&fs_info->chunk_mutex);
2650 btrfs_set_super_total_bytes(super_copy,
2651 round_down(old_total + diff, fs_info->sectorsize));
2652 device->fs_devices->total_rw_bytes += diff;
2654 btrfs_device_set_total_bytes(device, new_size);
2655 btrfs_device_set_disk_total_bytes(device, new_size);
2656 btrfs_clear_space_info_full(device->fs_info);
2657 if (list_empty(&device->post_commit_list))
2658 list_add_tail(&device->post_commit_list,
2659 &trans->transaction->dev_update_list);
2660 mutex_unlock(&fs_info->chunk_mutex);
2662 return btrfs_update_device(trans, device);
2665 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2667 struct btrfs_fs_info *fs_info = trans->fs_info;
2668 struct btrfs_root *root = fs_info->chunk_root;
2670 struct btrfs_path *path;
2671 struct btrfs_key key;
2673 path = btrfs_alloc_path();
2677 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2678 key.offset = chunk_offset;
2679 key.type = BTRFS_CHUNK_ITEM_KEY;
2681 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2684 else if (ret > 0) { /* Logic error or corruption */
2685 btrfs_handle_fs_error(fs_info, -ENOENT,
2686 "Failed lookup while freeing chunk.");
2691 ret = btrfs_del_item(trans, root, path);
2693 btrfs_handle_fs_error(fs_info, ret,
2694 "Failed to delete chunk item.");
2696 btrfs_free_path(path);
2700 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2702 struct btrfs_super_block *super_copy = fs_info->super_copy;
2703 struct btrfs_disk_key *disk_key;
2704 struct btrfs_chunk *chunk;
2711 struct btrfs_key key;
2713 mutex_lock(&fs_info->chunk_mutex);
2714 array_size = btrfs_super_sys_array_size(super_copy);
2716 ptr = super_copy->sys_chunk_array;
2719 while (cur < array_size) {
2720 disk_key = (struct btrfs_disk_key *)ptr;
2721 btrfs_disk_key_to_cpu(&key, disk_key);
2723 len = sizeof(*disk_key);
2725 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2726 chunk = (struct btrfs_chunk *)(ptr + len);
2727 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2728 len += btrfs_chunk_item_size(num_stripes);
2733 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2734 key.offset == chunk_offset) {
2735 memmove(ptr, ptr + len, array_size - (cur + len));
2737 btrfs_set_super_sys_array_size(super_copy, array_size);
2743 mutex_unlock(&fs_info->chunk_mutex);
2748 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2749 * @logical: Logical block offset in bytes.
2750 * @length: Length of extent in bytes.
2752 * Return: Chunk mapping or ERR_PTR.
2754 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2755 u64 logical, u64 length)
2757 struct extent_map_tree *em_tree;
2758 struct extent_map *em;
2760 em_tree = &fs_info->mapping_tree;
2761 read_lock(&em_tree->lock);
2762 em = lookup_extent_mapping(em_tree, logical, length);
2763 read_unlock(&em_tree->lock);
2766 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2768 return ERR_PTR(-EINVAL);
2771 if (em->start > logical || em->start + em->len < logical) {
2773 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2774 logical, length, em->start, em->start + em->len);
2775 free_extent_map(em);
2776 return ERR_PTR(-EINVAL);
2779 /* callers are responsible for dropping em's ref. */
2783 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2785 struct btrfs_fs_info *fs_info = trans->fs_info;
2786 struct extent_map *em;
2787 struct map_lookup *map;
2788 u64 dev_extent_len = 0;
2790 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2792 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2795 * This is a logic error, but we don't want to just rely on the
2796 * user having built with ASSERT enabled, so if ASSERT doesn't
2797 * do anything we still error out.
2802 map = em->map_lookup;
2803 mutex_lock(&fs_info->chunk_mutex);
2804 check_system_chunk(trans, map->type);
2805 mutex_unlock(&fs_info->chunk_mutex);
2808 * Take the device list mutex to prevent races with the final phase of
2809 * a device replace operation that replaces the device object associated
2810 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2812 mutex_lock(&fs_devices->device_list_mutex);
2813 for (i = 0; i < map->num_stripes; i++) {
2814 struct btrfs_device *device = map->stripes[i].dev;
2815 ret = btrfs_free_dev_extent(trans, device,
2816 map->stripes[i].physical,
2819 mutex_unlock(&fs_devices->device_list_mutex);
2820 btrfs_abort_transaction(trans, ret);
2824 if (device->bytes_used > 0) {
2825 mutex_lock(&fs_info->chunk_mutex);
2826 btrfs_device_set_bytes_used(device,
2827 device->bytes_used - dev_extent_len);
2828 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2829 btrfs_clear_space_info_full(fs_info);
2830 mutex_unlock(&fs_info->chunk_mutex);
2833 ret = btrfs_update_device(trans, device);
2835 mutex_unlock(&fs_devices->device_list_mutex);
2836 btrfs_abort_transaction(trans, ret);
2840 mutex_unlock(&fs_devices->device_list_mutex);
2842 ret = btrfs_free_chunk(trans, chunk_offset);
2844 btrfs_abort_transaction(trans, ret);
2848 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2850 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2851 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2853 btrfs_abort_transaction(trans, ret);
2858 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2860 btrfs_abort_transaction(trans, ret);
2866 free_extent_map(em);
2870 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2872 struct btrfs_root *root = fs_info->chunk_root;
2873 struct btrfs_trans_handle *trans;
2874 struct btrfs_block_group *block_group;
2878 * Prevent races with automatic removal of unused block groups.
2879 * After we relocate and before we remove the chunk with offset
2880 * chunk_offset, automatic removal of the block group can kick in,
2881 * resulting in a failure when calling btrfs_remove_chunk() below.
2883 * Make sure to acquire this mutex before doing a tree search (dev
2884 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2885 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2886 * we release the path used to search the chunk/dev tree and before
2887 * the current task acquires this mutex and calls us.
2889 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2891 /* step one, relocate all the extents inside this chunk */
2892 btrfs_scrub_pause(fs_info);
2893 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2894 btrfs_scrub_continue(fs_info);
2898 block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
2901 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
2902 btrfs_put_block_group(block_group);
2904 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2906 if (IS_ERR(trans)) {
2907 ret = PTR_ERR(trans);
2908 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2913 * step two, delete the device extents and the
2914 * chunk tree entries
2916 ret = btrfs_remove_chunk(trans, chunk_offset);
2917 btrfs_end_transaction(trans);
2921 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2923 struct btrfs_root *chunk_root = fs_info->chunk_root;
2924 struct btrfs_path *path;
2925 struct extent_buffer *leaf;
2926 struct btrfs_chunk *chunk;
2927 struct btrfs_key key;
2928 struct btrfs_key found_key;
2930 bool retried = false;
2934 path = btrfs_alloc_path();
2939 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2940 key.offset = (u64)-1;
2941 key.type = BTRFS_CHUNK_ITEM_KEY;
2944 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2945 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2947 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2950 BUG_ON(ret == 0); /* Corruption */
2952 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2955 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2961 leaf = path->nodes[0];
2962 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2964 chunk = btrfs_item_ptr(leaf, path->slots[0],
2965 struct btrfs_chunk);
2966 chunk_type = btrfs_chunk_type(leaf, chunk);
2967 btrfs_release_path(path);
2969 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2970 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
2976 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2978 if (found_key.offset == 0)
2980 key.offset = found_key.offset - 1;
2983 if (failed && !retried) {
2987 } else if (WARN_ON(failed && retried)) {
2991 btrfs_free_path(path);
2996 * return 1 : allocate a data chunk successfully,
2997 * return <0: errors during allocating a data chunk,
2998 * return 0 : no need to allocate a data chunk.
3000 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3003 struct btrfs_block_group *cache;
3007 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3009 chunk_type = cache->flags;
3010 btrfs_put_block_group(cache);
3012 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3015 spin_lock(&fs_info->data_sinfo->lock);
3016 bytes_used = fs_info->data_sinfo->bytes_used;
3017 spin_unlock(&fs_info->data_sinfo->lock);
3020 struct btrfs_trans_handle *trans;
3023 trans = btrfs_join_transaction(fs_info->tree_root);
3025 return PTR_ERR(trans);
3027 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3028 btrfs_end_transaction(trans);
3037 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3038 struct btrfs_balance_control *bctl)
3040 struct btrfs_root *root = fs_info->tree_root;
3041 struct btrfs_trans_handle *trans;
3042 struct btrfs_balance_item *item;
3043 struct btrfs_disk_balance_args disk_bargs;
3044 struct btrfs_path *path;
3045 struct extent_buffer *leaf;
3046 struct btrfs_key key;
3049 path = btrfs_alloc_path();
3053 trans = btrfs_start_transaction(root, 0);
3054 if (IS_ERR(trans)) {
3055 btrfs_free_path(path);
3056 return PTR_ERR(trans);
3059 key.objectid = BTRFS_BALANCE_OBJECTID;
3060 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3063 ret = btrfs_insert_empty_item(trans, root, path, &key,
3068 leaf = path->nodes[0];
3069 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3071 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3073 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3074 btrfs_set_balance_data(leaf, item, &disk_bargs);
3075 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3076 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3077 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3078 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3080 btrfs_set_balance_flags(leaf, item, bctl->flags);
3082 btrfs_mark_buffer_dirty(leaf);
3084 btrfs_free_path(path);
3085 err = btrfs_commit_transaction(trans);
3091 static int del_balance_item(struct btrfs_fs_info *fs_info)
3093 struct btrfs_root *root = fs_info->tree_root;
3094 struct btrfs_trans_handle *trans;
3095 struct btrfs_path *path;
3096 struct btrfs_key key;
3099 path = btrfs_alloc_path();
3103 trans = btrfs_start_transaction(root, 0);
3104 if (IS_ERR(trans)) {
3105 btrfs_free_path(path);
3106 return PTR_ERR(trans);
3109 key.objectid = BTRFS_BALANCE_OBJECTID;
3110 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3113 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3121 ret = btrfs_del_item(trans, root, path);
3123 btrfs_free_path(path);
3124 err = btrfs_commit_transaction(trans);
3131 * This is a heuristic used to reduce the number of chunks balanced on
3132 * resume after balance was interrupted.
3134 static void update_balance_args(struct btrfs_balance_control *bctl)
3137 * Turn on soft mode for chunk types that were being converted.
3139 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3140 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3141 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3142 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3143 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3144 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3147 * Turn on usage filter if is not already used. The idea is
3148 * that chunks that we have already balanced should be
3149 * reasonably full. Don't do it for chunks that are being
3150 * converted - that will keep us from relocating unconverted
3151 * (albeit full) chunks.
3153 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3154 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3155 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3156 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3157 bctl->data.usage = 90;
3159 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3160 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3161 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3162 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3163 bctl->sys.usage = 90;
3165 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3166 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3167 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3168 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3169 bctl->meta.usage = 90;
3174 * Clear the balance status in fs_info and delete the balance item from disk.
3176 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3178 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3181 BUG_ON(!fs_info->balance_ctl);
3183 spin_lock(&fs_info->balance_lock);
3184 fs_info->balance_ctl = NULL;
3185 spin_unlock(&fs_info->balance_lock);
3188 ret = del_balance_item(fs_info);
3190 btrfs_handle_fs_error(fs_info, ret, NULL);
3194 * Balance filters. Return 1 if chunk should be filtered out
3195 * (should not be balanced).
3197 static int chunk_profiles_filter(u64 chunk_type,
3198 struct btrfs_balance_args *bargs)
3200 chunk_type = chunk_to_extended(chunk_type) &
3201 BTRFS_EXTENDED_PROFILE_MASK;
3203 if (bargs->profiles & chunk_type)
3209 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3210 struct btrfs_balance_args *bargs)
3212 struct btrfs_block_group *cache;
3214 u64 user_thresh_min;
3215 u64 user_thresh_max;
3218 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3219 chunk_used = cache->used;
3221 if (bargs->usage_min == 0)
3222 user_thresh_min = 0;
3224 user_thresh_min = div_factor_fine(cache->length,
3227 if (bargs->usage_max == 0)
3228 user_thresh_max = 1;
3229 else if (bargs->usage_max > 100)
3230 user_thresh_max = cache->length;
3232 user_thresh_max = div_factor_fine(cache->length,
3235 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3238 btrfs_put_block_group(cache);
3242 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3243 u64 chunk_offset, struct btrfs_balance_args *bargs)
3245 struct btrfs_block_group *cache;
3246 u64 chunk_used, user_thresh;
3249 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3250 chunk_used = cache->used;
3252 if (bargs->usage_min == 0)
3254 else if (bargs->usage > 100)
3255 user_thresh = cache->length;
3257 user_thresh = div_factor_fine(cache->length, bargs->usage);
3259 if (chunk_used < user_thresh)
3262 btrfs_put_block_group(cache);
3266 static int chunk_devid_filter(struct extent_buffer *leaf,
3267 struct btrfs_chunk *chunk,
3268 struct btrfs_balance_args *bargs)
3270 struct btrfs_stripe *stripe;
3271 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3274 for (i = 0; i < num_stripes; i++) {
3275 stripe = btrfs_stripe_nr(chunk, i);
3276 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3283 static u64 calc_data_stripes(u64 type, int num_stripes)
3285 const int index = btrfs_bg_flags_to_raid_index(type);
3286 const int ncopies = btrfs_raid_array[index].ncopies;
3287 const int nparity = btrfs_raid_array[index].nparity;
3290 return num_stripes - nparity;
3292 return num_stripes / ncopies;
3295 /* [pstart, pend) */
3296 static int chunk_drange_filter(struct extent_buffer *leaf,
3297 struct btrfs_chunk *chunk,
3298 struct btrfs_balance_args *bargs)
3300 struct btrfs_stripe *stripe;
3301 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3308 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3311 type = btrfs_chunk_type(leaf, chunk);
3312 factor = calc_data_stripes(type, num_stripes);
3314 for (i = 0; i < num_stripes; i++) {
3315 stripe = btrfs_stripe_nr(chunk, i);
3316 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3319 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3320 stripe_length = btrfs_chunk_length(leaf, chunk);
3321 stripe_length = div_u64(stripe_length, factor);
3323 if (stripe_offset < bargs->pend &&
3324 stripe_offset + stripe_length > bargs->pstart)
3331 /* [vstart, vend) */
3332 static int chunk_vrange_filter(struct extent_buffer *leaf,
3333 struct btrfs_chunk *chunk,
3335 struct btrfs_balance_args *bargs)
3337 if (chunk_offset < bargs->vend &&
3338 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3339 /* at least part of the chunk is inside this vrange */
3345 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3346 struct btrfs_chunk *chunk,
3347 struct btrfs_balance_args *bargs)
3349 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3351 if (bargs->stripes_min <= num_stripes
3352 && num_stripes <= bargs->stripes_max)
3358 static int chunk_soft_convert_filter(u64 chunk_type,
3359 struct btrfs_balance_args *bargs)
3361 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3364 chunk_type = chunk_to_extended(chunk_type) &
3365 BTRFS_EXTENDED_PROFILE_MASK;
3367 if (bargs->target == chunk_type)
3373 static int should_balance_chunk(struct extent_buffer *leaf,
3374 struct btrfs_chunk *chunk, u64 chunk_offset)
3376 struct btrfs_fs_info *fs_info = leaf->fs_info;
3377 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3378 struct btrfs_balance_args *bargs = NULL;
3379 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3382 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3383 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3387 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3388 bargs = &bctl->data;
3389 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3391 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3392 bargs = &bctl->meta;
3394 /* profiles filter */
3395 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3396 chunk_profiles_filter(chunk_type, bargs)) {
3401 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3402 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3404 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3405 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3410 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3411 chunk_devid_filter(leaf, chunk, bargs)) {
3415 /* drange filter, makes sense only with devid filter */
3416 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3417 chunk_drange_filter(leaf, chunk, bargs)) {
3422 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3423 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3427 /* stripes filter */
3428 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3429 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3433 /* soft profile changing mode */
3434 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3435 chunk_soft_convert_filter(chunk_type, bargs)) {
3440 * limited by count, must be the last filter
3442 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3443 if (bargs->limit == 0)
3447 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3449 * Same logic as the 'limit' filter; the minimum cannot be
3450 * determined here because we do not have the global information
3451 * about the count of all chunks that satisfy the filters.
3453 if (bargs->limit_max == 0)
3462 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3464 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3465 struct btrfs_root *chunk_root = fs_info->chunk_root;
3467 struct btrfs_chunk *chunk;
3468 struct btrfs_path *path = NULL;
3469 struct btrfs_key key;
3470 struct btrfs_key found_key;
3471 struct extent_buffer *leaf;
3474 int enospc_errors = 0;
3475 bool counting = true;
3476 /* The single value limit and min/max limits use the same bytes in the */
3477 u64 limit_data = bctl->data.limit;
3478 u64 limit_meta = bctl->meta.limit;
3479 u64 limit_sys = bctl->sys.limit;
3483 int chunk_reserved = 0;
3485 path = btrfs_alloc_path();
3491 /* zero out stat counters */
3492 spin_lock(&fs_info->balance_lock);
3493 memset(&bctl->stat, 0, sizeof(bctl->stat));
3494 spin_unlock(&fs_info->balance_lock);
3498 * The single value limit and min/max limits use the same bytes
3501 bctl->data.limit = limit_data;
3502 bctl->meta.limit = limit_meta;
3503 bctl->sys.limit = limit_sys;
3505 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3506 key.offset = (u64)-1;
3507 key.type = BTRFS_CHUNK_ITEM_KEY;
3510 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3511 atomic_read(&fs_info->balance_cancel_req)) {
3516 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3517 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3519 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3524 * this shouldn't happen, it means the last relocate
3528 BUG(); /* FIXME break ? */
3530 ret = btrfs_previous_item(chunk_root, path, 0,
3531 BTRFS_CHUNK_ITEM_KEY);
3533 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3538 leaf = path->nodes[0];
3539 slot = path->slots[0];
3540 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3542 if (found_key.objectid != key.objectid) {
3543 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3547 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3548 chunk_type = btrfs_chunk_type(leaf, chunk);
3551 spin_lock(&fs_info->balance_lock);
3552 bctl->stat.considered++;
3553 spin_unlock(&fs_info->balance_lock);
3556 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3558 btrfs_release_path(path);
3560 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3565 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3566 spin_lock(&fs_info->balance_lock);
3567 bctl->stat.expected++;
3568 spin_unlock(&fs_info->balance_lock);
3570 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3572 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3574 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3581 * Apply limit_min filter, no need to check if the LIMITS
3582 * filter is used, limit_min is 0 by default
3584 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3585 count_data < bctl->data.limit_min)
3586 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3587 count_meta < bctl->meta.limit_min)
3588 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3589 count_sys < bctl->sys.limit_min)) {
3590 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3594 if (!chunk_reserved) {
3596 * We may be relocating the only data chunk we have,
3597 * which could potentially end up with losing data's
3598 * raid profile, so lets allocate an empty one in
3601 ret = btrfs_may_alloc_data_chunk(fs_info,
3604 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3606 } else if (ret == 1) {
3611 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3612 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3613 if (ret == -ENOSPC) {
3615 } else if (ret == -ETXTBSY) {
3617 "skipping relocation of block group %llu due to active swapfile",
3623 spin_lock(&fs_info->balance_lock);
3624 bctl->stat.completed++;
3625 spin_unlock(&fs_info->balance_lock);
3628 if (found_key.offset == 0)
3630 key.offset = found_key.offset - 1;
3634 btrfs_release_path(path);
3639 btrfs_free_path(path);
3640 if (enospc_errors) {
3641 btrfs_info(fs_info, "%d enospc errors during balance",
3651 * alloc_profile_is_valid - see if a given profile is valid and reduced
3652 * @flags: profile to validate
3653 * @extended: if true @flags is treated as an extended profile
3655 static int alloc_profile_is_valid(u64 flags, int extended)
3657 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3658 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3660 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3662 /* 1) check that all other bits are zeroed */
3666 /* 2) see if profile is reduced */
3668 return !extended; /* "0" is valid for usual profiles */
3670 return has_single_bit_set(flags);
3673 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3675 /* cancel requested || normal exit path */
3676 return atomic_read(&fs_info->balance_cancel_req) ||
3677 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3678 atomic_read(&fs_info->balance_cancel_req) == 0);
3681 /* Non-zero return value signifies invalidity */
3682 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3685 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3686 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3687 (bctl_arg->target & ~allowed)));
3691 * Fill @buf with textual description of balance filter flags @bargs, up to
3692 * @size_buf including the terminating null. The output may be trimmed if it
3693 * does not fit into the provided buffer.
3695 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3699 u32 size_bp = size_buf;
3701 u64 flags = bargs->flags;
3702 char tmp_buf[128] = {'\0'};
3707 #define CHECK_APPEND_NOARG(a) \
3709 ret = snprintf(bp, size_bp, (a)); \
3710 if (ret < 0 || ret >= size_bp) \
3711 goto out_overflow; \
3716 #define CHECK_APPEND_1ARG(a, v1) \
3718 ret = snprintf(bp, size_bp, (a), (v1)); \
3719 if (ret < 0 || ret >= size_bp) \
3720 goto out_overflow; \
3725 #define CHECK_APPEND_2ARG(a, v1, v2) \
3727 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3728 if (ret < 0 || ret >= size_bp) \
3729 goto out_overflow; \
3734 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
3735 CHECK_APPEND_1ARG("convert=%s,",
3736 btrfs_bg_type_to_raid_name(bargs->target));
3738 if (flags & BTRFS_BALANCE_ARGS_SOFT)
3739 CHECK_APPEND_NOARG("soft,");
3741 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
3742 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
3744 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
3747 if (flags & BTRFS_BALANCE_ARGS_USAGE)
3748 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
3750 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
3751 CHECK_APPEND_2ARG("usage=%u..%u,",
3752 bargs->usage_min, bargs->usage_max);
3754 if (flags & BTRFS_BALANCE_ARGS_DEVID)
3755 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
3757 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
3758 CHECK_APPEND_2ARG("drange=%llu..%llu,",
3759 bargs->pstart, bargs->pend);
3761 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
3762 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
3763 bargs->vstart, bargs->vend);
3765 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
3766 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
3768 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
3769 CHECK_APPEND_2ARG("limit=%u..%u,",
3770 bargs->limit_min, bargs->limit_max);
3772 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
3773 CHECK_APPEND_2ARG("stripes=%u..%u,",
3774 bargs->stripes_min, bargs->stripes_max);
3776 #undef CHECK_APPEND_2ARG
3777 #undef CHECK_APPEND_1ARG
3778 #undef CHECK_APPEND_NOARG
3782 if (size_bp < size_buf)
3783 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
3788 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
3790 u32 size_buf = 1024;
3791 char tmp_buf[192] = {'\0'};
3794 u32 size_bp = size_buf;
3796 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3798 buf = kzalloc(size_buf, GFP_KERNEL);
3804 #define CHECK_APPEND_1ARG(a, v1) \
3806 ret = snprintf(bp, size_bp, (a), (v1)); \
3807 if (ret < 0 || ret >= size_bp) \
3808 goto out_overflow; \
3813 if (bctl->flags & BTRFS_BALANCE_FORCE)
3814 CHECK_APPEND_1ARG("%s", "-f ");
3816 if (bctl->flags & BTRFS_BALANCE_DATA) {
3817 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
3818 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
3821 if (bctl->flags & BTRFS_BALANCE_METADATA) {
3822 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
3823 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
3826 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
3827 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
3828 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
3831 #undef CHECK_APPEND_1ARG
3835 if (size_bp < size_buf)
3836 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
3837 btrfs_info(fs_info, "balance: %s %s",
3838 (bctl->flags & BTRFS_BALANCE_RESUME) ?
3839 "resume" : "start", buf);
3845 * Should be called with balance mutexe held
3847 int btrfs_balance(struct btrfs_fs_info *fs_info,
3848 struct btrfs_balance_control *bctl,
3849 struct btrfs_ioctl_balance_args *bargs)
3851 u64 meta_target, data_target;
3857 bool reducing_redundancy;
3860 if (btrfs_fs_closing(fs_info) ||
3861 atomic_read(&fs_info->balance_pause_req) ||
3862 atomic_read(&fs_info->balance_cancel_req)) {
3867 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3868 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3872 * In case of mixed groups both data and meta should be picked,
3873 * and identical options should be given for both of them.
3875 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3876 if (mixed && (bctl->flags & allowed)) {
3877 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3878 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3879 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3881 "balance: mixed groups data and metadata options must be the same");
3888 * rw_devices will not change at the moment, device add/delete/replace
3889 * are excluded by EXCL_OP
3891 num_devices = fs_info->fs_devices->rw_devices;
3894 * SINGLE profile on-disk has no profile bit, but in-memory we have a
3895 * special bit for it, to make it easier to distinguish. Thus we need
3896 * to set it manually, or balance would refuse the profile.
3898 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3899 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
3900 if (num_devices >= btrfs_raid_array[i].devs_min)
3901 allowed |= btrfs_raid_array[i].bg_flag;
3903 if (validate_convert_profile(&bctl->data, allowed)) {
3905 "balance: invalid convert data profile %s",
3906 btrfs_bg_type_to_raid_name(bctl->data.target));
3910 if (validate_convert_profile(&bctl->meta, allowed)) {
3912 "balance: invalid convert metadata profile %s",
3913 btrfs_bg_type_to_raid_name(bctl->meta.target));
3917 if (validate_convert_profile(&bctl->sys, allowed)) {
3919 "balance: invalid convert system profile %s",
3920 btrfs_bg_type_to_raid_name(bctl->sys.target));
3926 * Allow to reduce metadata or system integrity only if force set for
3927 * profiles with redundancy (copies, parity)
3930 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
3931 if (btrfs_raid_array[i].ncopies >= 2 ||
3932 btrfs_raid_array[i].tolerated_failures >= 1)
3933 allowed |= btrfs_raid_array[i].bg_flag;
3936 seq = read_seqbegin(&fs_info->profiles_lock);
3938 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3939 (fs_info->avail_system_alloc_bits & allowed) &&
3940 !(bctl->sys.target & allowed)) ||
3941 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3942 (fs_info->avail_metadata_alloc_bits & allowed) &&
3943 !(bctl->meta.target & allowed)))
3944 reducing_redundancy = true;
3946 reducing_redundancy = false;
3948 /* if we're not converting, the target field is uninitialized */
3949 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3950 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3951 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3952 bctl->data.target : fs_info->avail_data_alloc_bits;
3953 } while (read_seqretry(&fs_info->profiles_lock, seq));
3955 if (reducing_redundancy) {
3956 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3958 "balance: force reducing metadata redundancy");
3961 "balance: reduces metadata redundancy, use --force if you want this");
3967 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3968 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3970 "balance: metadata profile %s has lower redundancy than data profile %s",
3971 btrfs_bg_type_to_raid_name(meta_target),
3972 btrfs_bg_type_to_raid_name(data_target));
3975 if (fs_info->send_in_progress) {
3976 btrfs_warn_rl(fs_info,
3977 "cannot run balance while send operations are in progress (%d in progress)",
3978 fs_info->send_in_progress);
3983 ret = insert_balance_item(fs_info, bctl);
3984 if (ret && ret != -EEXIST)
3987 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3988 BUG_ON(ret == -EEXIST);
3989 BUG_ON(fs_info->balance_ctl);
3990 spin_lock(&fs_info->balance_lock);
3991 fs_info->balance_ctl = bctl;
3992 spin_unlock(&fs_info->balance_lock);
3994 BUG_ON(ret != -EEXIST);
3995 spin_lock(&fs_info->balance_lock);
3996 update_balance_args(bctl);
3997 spin_unlock(&fs_info->balance_lock);
4000 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4001 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4002 describe_balance_start_or_resume(fs_info);
4003 mutex_unlock(&fs_info->balance_mutex);
4005 ret = __btrfs_balance(fs_info);
4007 mutex_lock(&fs_info->balance_mutex);
4008 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4009 btrfs_info(fs_info, "balance: paused");
4010 else if (ret == -ECANCELED && atomic_read(&fs_info->balance_cancel_req))
4011 btrfs_info(fs_info, "balance: canceled");
4013 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4015 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4018 memset(bargs, 0, sizeof(*bargs));
4019 btrfs_update_ioctl_balance_args(fs_info, bargs);
4022 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4023 balance_need_close(fs_info)) {
4024 reset_balance_state(fs_info);
4025 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4028 wake_up(&fs_info->balance_wait_q);
4032 if (bctl->flags & BTRFS_BALANCE_RESUME)
4033 reset_balance_state(fs_info);
4036 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4041 static int balance_kthread(void *data)
4043 struct btrfs_fs_info *fs_info = data;
4046 mutex_lock(&fs_info->balance_mutex);
4047 if (fs_info->balance_ctl)
4048 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4049 mutex_unlock(&fs_info->balance_mutex);
4054 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4056 struct task_struct *tsk;
4058 mutex_lock(&fs_info->balance_mutex);
4059 if (!fs_info->balance_ctl) {
4060 mutex_unlock(&fs_info->balance_mutex);
4063 mutex_unlock(&fs_info->balance_mutex);
4065 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4066 btrfs_info(fs_info, "balance: resume skipped");
4071 * A ro->rw remount sequence should continue with the paused balance
4072 * regardless of who pauses it, system or the user as of now, so set
4075 spin_lock(&fs_info->balance_lock);
4076 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4077 spin_unlock(&fs_info->balance_lock);
4079 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4080 return PTR_ERR_OR_ZERO(tsk);
4083 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4085 struct btrfs_balance_control *bctl;
4086 struct btrfs_balance_item *item;
4087 struct btrfs_disk_balance_args disk_bargs;
4088 struct btrfs_path *path;
4089 struct extent_buffer *leaf;
4090 struct btrfs_key key;
4093 path = btrfs_alloc_path();
4097 key.objectid = BTRFS_BALANCE_OBJECTID;
4098 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4101 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4104 if (ret > 0) { /* ret = -ENOENT; */
4109 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4115 leaf = path->nodes[0];
4116 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4118 bctl->flags = btrfs_balance_flags(leaf, item);
4119 bctl->flags |= BTRFS_BALANCE_RESUME;
4121 btrfs_balance_data(leaf, item, &disk_bargs);
4122 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4123 btrfs_balance_meta(leaf, item, &disk_bargs);
4124 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4125 btrfs_balance_sys(leaf, item, &disk_bargs);
4126 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4129 * This should never happen, as the paused balance state is recovered
4130 * during mount without any chance of other exclusive ops to collide.
4132 * This gives the exclusive op status to balance and keeps in paused
4133 * state until user intervention (cancel or umount). If the ownership
4134 * cannot be assigned, show a message but do not fail. The balance
4135 * is in a paused state and must have fs_info::balance_ctl properly
4138 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4140 "balance: cannot set exclusive op status, resume manually");
4142 mutex_lock(&fs_info->balance_mutex);
4143 BUG_ON(fs_info->balance_ctl);
4144 spin_lock(&fs_info->balance_lock);
4145 fs_info->balance_ctl = bctl;
4146 spin_unlock(&fs_info->balance_lock);
4147 mutex_unlock(&fs_info->balance_mutex);
4149 btrfs_free_path(path);
4153 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4157 mutex_lock(&fs_info->balance_mutex);
4158 if (!fs_info->balance_ctl) {
4159 mutex_unlock(&fs_info->balance_mutex);
4163 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4164 atomic_inc(&fs_info->balance_pause_req);
4165 mutex_unlock(&fs_info->balance_mutex);
4167 wait_event(fs_info->balance_wait_q,
4168 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4170 mutex_lock(&fs_info->balance_mutex);
4171 /* we are good with balance_ctl ripped off from under us */
4172 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4173 atomic_dec(&fs_info->balance_pause_req);
4178 mutex_unlock(&fs_info->balance_mutex);
4182 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4184 mutex_lock(&fs_info->balance_mutex);
4185 if (!fs_info->balance_ctl) {
4186 mutex_unlock(&fs_info->balance_mutex);
4191 * A paused balance with the item stored on disk can be resumed at
4192 * mount time if the mount is read-write. Otherwise it's still paused
4193 * and we must not allow cancelling as it deletes the item.
4195 if (sb_rdonly(fs_info->sb)) {
4196 mutex_unlock(&fs_info->balance_mutex);
4200 atomic_inc(&fs_info->balance_cancel_req);
4202 * if we are running just wait and return, balance item is
4203 * deleted in btrfs_balance in this case
4205 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4206 mutex_unlock(&fs_info->balance_mutex);
4207 wait_event(fs_info->balance_wait_q,
4208 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4209 mutex_lock(&fs_info->balance_mutex);
4211 mutex_unlock(&fs_info->balance_mutex);
4213 * Lock released to allow other waiters to continue, we'll
4214 * reexamine the status again.
4216 mutex_lock(&fs_info->balance_mutex);
4218 if (fs_info->balance_ctl) {
4219 reset_balance_state(fs_info);
4220 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4221 btrfs_info(fs_info, "balance: canceled");
4225 BUG_ON(fs_info->balance_ctl ||
4226 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4227 atomic_dec(&fs_info->balance_cancel_req);
4228 mutex_unlock(&fs_info->balance_mutex);
4232 static int btrfs_uuid_scan_kthread(void *data)
4234 struct btrfs_fs_info *fs_info = data;
4235 struct btrfs_root *root = fs_info->tree_root;
4236 struct btrfs_key key;
4237 struct btrfs_path *path = NULL;
4239 struct extent_buffer *eb;
4241 struct btrfs_root_item root_item;
4243 struct btrfs_trans_handle *trans = NULL;
4245 path = btrfs_alloc_path();
4252 key.type = BTRFS_ROOT_ITEM_KEY;
4256 ret = btrfs_search_forward(root, &key, path,
4257 BTRFS_OLDEST_GENERATION);
4264 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4265 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4266 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4267 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4270 eb = path->nodes[0];
4271 slot = path->slots[0];
4272 item_size = btrfs_item_size_nr(eb, slot);
4273 if (item_size < sizeof(root_item))
4276 read_extent_buffer(eb, &root_item,
4277 btrfs_item_ptr_offset(eb, slot),
4278 (int)sizeof(root_item));
4279 if (btrfs_root_refs(&root_item) == 0)
4282 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4283 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4287 btrfs_release_path(path);
4289 * 1 - subvol uuid item
4290 * 1 - received_subvol uuid item
4292 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4293 if (IS_ERR(trans)) {
4294 ret = PTR_ERR(trans);
4302 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4303 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4304 BTRFS_UUID_KEY_SUBVOL,
4307 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4313 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4314 ret = btrfs_uuid_tree_add(trans,
4315 root_item.received_uuid,
4316 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4319 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4327 ret = btrfs_end_transaction(trans);
4333 btrfs_release_path(path);
4334 if (key.offset < (u64)-1) {
4336 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4338 key.type = BTRFS_ROOT_ITEM_KEY;
4339 } else if (key.objectid < (u64)-1) {
4341 key.type = BTRFS_ROOT_ITEM_KEY;
4350 btrfs_free_path(path);
4351 if (trans && !IS_ERR(trans))
4352 btrfs_end_transaction(trans);
4354 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4356 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4357 up(&fs_info->uuid_tree_rescan_sem);
4362 * Callback for btrfs_uuid_tree_iterate().
4364 * 0 check succeeded, the entry is not outdated.
4365 * < 0 if an error occurred.
4366 * > 0 if the check failed, which means the caller shall remove the entry.
4368 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4369 u8 *uuid, u8 type, u64 subid)
4371 struct btrfs_key key;
4373 struct btrfs_root *subvol_root;
4375 if (type != BTRFS_UUID_KEY_SUBVOL &&
4376 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4379 key.objectid = subid;
4380 key.type = BTRFS_ROOT_ITEM_KEY;
4381 key.offset = (u64)-1;
4382 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4383 if (IS_ERR(subvol_root)) {
4384 ret = PTR_ERR(subvol_root);
4391 case BTRFS_UUID_KEY_SUBVOL:
4392 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4395 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4396 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4406 static int btrfs_uuid_rescan_kthread(void *data)
4408 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4412 * 1st step is to iterate through the existing UUID tree and
4413 * to delete all entries that contain outdated data.
4414 * 2nd step is to add all missing entries to the UUID tree.
4416 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4418 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4419 up(&fs_info->uuid_tree_rescan_sem);
4422 return btrfs_uuid_scan_kthread(data);
4425 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4427 struct btrfs_trans_handle *trans;
4428 struct btrfs_root *tree_root = fs_info->tree_root;
4429 struct btrfs_root *uuid_root;
4430 struct task_struct *task;
4437 trans = btrfs_start_transaction(tree_root, 2);
4439 return PTR_ERR(trans);
4441 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4442 if (IS_ERR(uuid_root)) {
4443 ret = PTR_ERR(uuid_root);
4444 btrfs_abort_transaction(trans, ret);
4445 btrfs_end_transaction(trans);
4449 fs_info->uuid_root = uuid_root;
4451 ret = btrfs_commit_transaction(trans);
4455 down(&fs_info->uuid_tree_rescan_sem);
4456 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4458 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4459 btrfs_warn(fs_info, "failed to start uuid_scan task");
4460 up(&fs_info->uuid_tree_rescan_sem);
4461 return PTR_ERR(task);
4467 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4469 struct task_struct *task;
4471 down(&fs_info->uuid_tree_rescan_sem);
4472 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4474 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4475 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4476 up(&fs_info->uuid_tree_rescan_sem);
4477 return PTR_ERR(task);
4484 * shrinking a device means finding all of the device extents past
4485 * the new size, and then following the back refs to the chunks.
4486 * The chunk relocation code actually frees the device extent
4488 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4490 struct btrfs_fs_info *fs_info = device->fs_info;
4491 struct btrfs_root *root = fs_info->dev_root;
4492 struct btrfs_trans_handle *trans;
4493 struct btrfs_dev_extent *dev_extent = NULL;
4494 struct btrfs_path *path;
4500 bool retried = false;
4501 struct extent_buffer *l;
4502 struct btrfs_key key;
4503 struct btrfs_super_block *super_copy = fs_info->super_copy;
4504 u64 old_total = btrfs_super_total_bytes(super_copy);
4505 u64 old_size = btrfs_device_get_total_bytes(device);
4509 new_size = round_down(new_size, fs_info->sectorsize);
4511 diff = round_down(old_size - new_size, fs_info->sectorsize);
4513 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4516 path = btrfs_alloc_path();
4520 path->reada = READA_BACK;
4522 trans = btrfs_start_transaction(root, 0);
4523 if (IS_ERR(trans)) {
4524 btrfs_free_path(path);
4525 return PTR_ERR(trans);
4528 mutex_lock(&fs_info->chunk_mutex);
4530 btrfs_device_set_total_bytes(device, new_size);
4531 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4532 device->fs_devices->total_rw_bytes -= diff;
4533 atomic64_sub(diff, &fs_info->free_chunk_space);
4537 * Once the device's size has been set to the new size, ensure all
4538 * in-memory chunks are synced to disk so that the loop below sees them
4539 * and relocates them accordingly.
4541 if (contains_pending_extent(device, &start, diff)) {
4542 mutex_unlock(&fs_info->chunk_mutex);
4543 ret = btrfs_commit_transaction(trans);
4547 mutex_unlock(&fs_info->chunk_mutex);
4548 btrfs_end_transaction(trans);
4552 key.objectid = device->devid;
4553 key.offset = (u64)-1;
4554 key.type = BTRFS_DEV_EXTENT_KEY;
4557 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4558 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4560 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4564 ret = btrfs_previous_item(root, path, 0, key.type);
4566 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4571 btrfs_release_path(path);
4576 slot = path->slots[0];
4577 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4579 if (key.objectid != device->devid) {
4580 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4581 btrfs_release_path(path);
4585 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4586 length = btrfs_dev_extent_length(l, dev_extent);
4588 if (key.offset + length <= new_size) {
4589 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4590 btrfs_release_path(path);
4594 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4595 btrfs_release_path(path);
4598 * We may be relocating the only data chunk we have,
4599 * which could potentially end up with losing data's
4600 * raid profile, so lets allocate an empty one in
4603 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4605 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4609 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4610 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4611 if (ret == -ENOSPC) {
4614 if (ret == -ETXTBSY) {
4616 "could not shrink block group %llu due to active swapfile",
4621 } while (key.offset-- > 0);
4623 if (failed && !retried) {
4627 } else if (failed && retried) {
4632 /* Shrinking succeeded, else we would be at "done". */
4633 trans = btrfs_start_transaction(root, 0);
4634 if (IS_ERR(trans)) {
4635 ret = PTR_ERR(trans);
4639 mutex_lock(&fs_info->chunk_mutex);
4640 btrfs_device_set_disk_total_bytes(device, new_size);
4641 if (list_empty(&device->post_commit_list))
4642 list_add_tail(&device->post_commit_list,
4643 &trans->transaction->dev_update_list);
4645 WARN_ON(diff > old_total);
4646 btrfs_set_super_total_bytes(super_copy,
4647 round_down(old_total - diff, fs_info->sectorsize));
4648 mutex_unlock(&fs_info->chunk_mutex);
4650 /* Now btrfs_update_device() will change the on-disk size. */
4651 ret = btrfs_update_device(trans, device);
4653 btrfs_abort_transaction(trans, ret);
4654 btrfs_end_transaction(trans);
4656 ret = btrfs_commit_transaction(trans);
4659 btrfs_free_path(path);
4661 mutex_lock(&fs_info->chunk_mutex);
4662 btrfs_device_set_total_bytes(device, old_size);
4663 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4664 device->fs_devices->total_rw_bytes += diff;
4665 atomic64_add(diff, &fs_info->free_chunk_space);
4666 mutex_unlock(&fs_info->chunk_mutex);
4671 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4672 struct btrfs_key *key,
4673 struct btrfs_chunk *chunk, int item_size)
4675 struct btrfs_super_block *super_copy = fs_info->super_copy;
4676 struct btrfs_disk_key disk_key;
4680 mutex_lock(&fs_info->chunk_mutex);
4681 array_size = btrfs_super_sys_array_size(super_copy);
4682 if (array_size + item_size + sizeof(disk_key)
4683 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4684 mutex_unlock(&fs_info->chunk_mutex);
4688 ptr = super_copy->sys_chunk_array + array_size;
4689 btrfs_cpu_key_to_disk(&disk_key, key);
4690 memcpy(ptr, &disk_key, sizeof(disk_key));
4691 ptr += sizeof(disk_key);
4692 memcpy(ptr, chunk, item_size);
4693 item_size += sizeof(disk_key);
4694 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4695 mutex_unlock(&fs_info->chunk_mutex);
4701 * sort the devices in descending order by max_avail, total_avail
4703 static int btrfs_cmp_device_info(const void *a, const void *b)
4705 const struct btrfs_device_info *di_a = a;
4706 const struct btrfs_device_info *di_b = b;
4708 if (di_a->max_avail > di_b->max_avail)
4710 if (di_a->max_avail < di_b->max_avail)
4712 if (di_a->total_avail > di_b->total_avail)
4714 if (di_a->total_avail < di_b->total_avail)
4719 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4721 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4724 btrfs_set_fs_incompat(info, RAID56);
4727 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
4729 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
4732 btrfs_set_fs_incompat(info, RAID1C34);
4735 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4736 u64 start, u64 type)
4738 struct btrfs_fs_info *info = trans->fs_info;
4739 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4740 struct btrfs_device *device;
4741 struct map_lookup *map = NULL;
4742 struct extent_map_tree *em_tree;
4743 struct extent_map *em;
4744 struct btrfs_device_info *devices_info = NULL;
4746 int num_stripes; /* total number of stripes to allocate */
4747 int data_stripes; /* number of stripes that count for
4749 int sub_stripes; /* sub_stripes info for map */
4750 int dev_stripes; /* stripes per dev */
4751 int devs_max; /* max devs to use */
4752 int devs_min; /* min devs needed */
4753 int devs_increment; /* ndevs has to be a multiple of this */
4754 int ncopies; /* how many copies to data has */
4755 int nparity; /* number of stripes worth of bytes to
4756 store parity information */
4758 u64 max_stripe_size;
4767 BUG_ON(!alloc_profile_is_valid(type, 0));
4769 if (list_empty(&fs_devices->alloc_list)) {
4770 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4771 btrfs_debug(info, "%s: no writable device", __func__);
4775 index = btrfs_bg_flags_to_raid_index(type);
4777 sub_stripes = btrfs_raid_array[index].sub_stripes;
4778 dev_stripes = btrfs_raid_array[index].dev_stripes;
4779 devs_max = btrfs_raid_array[index].devs_max;
4781 devs_max = BTRFS_MAX_DEVS(info);
4782 devs_min = btrfs_raid_array[index].devs_min;
4783 devs_increment = btrfs_raid_array[index].devs_increment;
4784 ncopies = btrfs_raid_array[index].ncopies;
4785 nparity = btrfs_raid_array[index].nparity;
4787 if (type & BTRFS_BLOCK_GROUP_DATA) {
4788 max_stripe_size = SZ_1G;
4789 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4790 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4791 /* for larger filesystems, use larger metadata chunks */
4792 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4793 max_stripe_size = SZ_1G;
4795 max_stripe_size = SZ_256M;
4796 max_chunk_size = max_stripe_size;
4797 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4798 max_stripe_size = SZ_32M;
4799 max_chunk_size = 2 * max_stripe_size;
4800 devs_max = min_t(int, devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
4802 btrfs_err(info, "invalid chunk type 0x%llx requested",
4807 /* We don't want a chunk larger than 10% of writable space */
4808 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4811 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4817 * in the first pass through the devices list, we gather information
4818 * about the available holes on each device.
4821 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4825 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4827 "BTRFS: read-only device in alloc_list\n");
4831 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4832 &device->dev_state) ||
4833 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4836 if (device->total_bytes > device->bytes_used)
4837 total_avail = device->total_bytes - device->bytes_used;
4841 /* If there is no space on this device, skip it. */
4842 if (total_avail == 0)
4845 ret = find_free_dev_extent(device,
4846 max_stripe_size * dev_stripes,
4847 &dev_offset, &max_avail);
4848 if (ret && ret != -ENOSPC)
4852 max_avail = max_stripe_size * dev_stripes;
4854 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4855 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4857 "%s: devid %llu has no free space, have=%llu want=%u",
4858 __func__, device->devid, max_avail,
4859 BTRFS_STRIPE_LEN * dev_stripes);
4863 if (ndevs == fs_devices->rw_devices) {
4864 WARN(1, "%s: found more than %llu devices\n",
4865 __func__, fs_devices->rw_devices);
4868 devices_info[ndevs].dev_offset = dev_offset;
4869 devices_info[ndevs].max_avail = max_avail;
4870 devices_info[ndevs].total_avail = total_avail;
4871 devices_info[ndevs].dev = device;
4876 * now sort the devices by hole size / available space
4878 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4879 btrfs_cmp_device_info, NULL);
4882 * Round down to number of usable stripes, devs_increment can be any
4883 * number so we can't use round_down()
4885 ndevs -= ndevs % devs_increment;
4887 if (ndevs < devs_min) {
4889 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4891 "%s: not enough devices with free space: have=%d minimum required=%d",
4892 __func__, ndevs, devs_min);
4897 ndevs = min(ndevs, devs_max);
4900 * The primary goal is to maximize the number of stripes, so use as
4901 * many devices as possible, even if the stripes are not maximum sized.
4903 * The DUP profile stores more than one stripe per device, the
4904 * max_avail is the total size so we have to adjust.
4906 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4907 num_stripes = ndevs * dev_stripes;
4910 * this will have to be fixed for RAID1 and RAID10 over
4913 data_stripes = (num_stripes - nparity) / ncopies;
4916 * Use the number of data stripes to figure out how big this chunk
4917 * is really going to be in terms of logical address space,
4918 * and compare that answer with the max chunk size. If it's higher,
4919 * we try to reduce stripe_size.
4921 if (stripe_size * data_stripes > max_chunk_size) {
4923 * Reduce stripe_size, round it up to a 16MB boundary again and
4924 * then use it, unless it ends up being even bigger than the
4925 * previous value we had already.
4927 stripe_size = min(round_up(div_u64(max_chunk_size,
4928 data_stripes), SZ_16M),
4932 /* align to BTRFS_STRIPE_LEN */
4933 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4935 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4940 map->num_stripes = num_stripes;
4942 for (i = 0; i < ndevs; ++i) {
4943 for (j = 0; j < dev_stripes; ++j) {
4944 int s = i * dev_stripes + j;
4945 map->stripes[s].dev = devices_info[i].dev;
4946 map->stripes[s].physical = devices_info[i].dev_offset +
4950 map->stripe_len = BTRFS_STRIPE_LEN;
4951 map->io_align = BTRFS_STRIPE_LEN;
4952 map->io_width = BTRFS_STRIPE_LEN;
4954 map->sub_stripes = sub_stripes;
4956 chunk_size = stripe_size * data_stripes;
4958 trace_btrfs_chunk_alloc(info, map, start, chunk_size);
4960 em = alloc_extent_map();
4966 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4967 em->map_lookup = map;
4969 em->len = chunk_size;
4970 em->block_start = 0;
4971 em->block_len = em->len;
4972 em->orig_block_len = stripe_size;
4974 em_tree = &info->mapping_tree;
4975 write_lock(&em_tree->lock);
4976 ret = add_extent_mapping(em_tree, em, 0);
4978 write_unlock(&em_tree->lock);
4979 free_extent_map(em);
4982 write_unlock(&em_tree->lock);
4984 ret = btrfs_make_block_group(trans, 0, type, start, chunk_size);
4986 goto error_del_extent;
4988 for (i = 0; i < map->num_stripes; i++) {
4989 struct btrfs_device *dev = map->stripes[i].dev;
4991 btrfs_device_set_bytes_used(dev, dev->bytes_used + stripe_size);
4992 if (list_empty(&dev->post_commit_list))
4993 list_add_tail(&dev->post_commit_list,
4994 &trans->transaction->dev_update_list);
4997 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4999 free_extent_map(em);
5000 check_raid56_incompat_flag(info, type);
5001 check_raid1c34_incompat_flag(info, type);
5003 kfree(devices_info);
5007 write_lock(&em_tree->lock);
5008 remove_extent_mapping(em_tree, em);
5009 write_unlock(&em_tree->lock);
5011 /* One for our allocation */
5012 free_extent_map(em);
5013 /* One for the tree reference */
5014 free_extent_map(em);
5016 kfree(devices_info);
5020 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5021 u64 chunk_offset, u64 chunk_size)
5023 struct btrfs_fs_info *fs_info = trans->fs_info;
5024 struct btrfs_root *extent_root = fs_info->extent_root;
5025 struct btrfs_root *chunk_root = fs_info->chunk_root;
5026 struct btrfs_key key;
5027 struct btrfs_device *device;
5028 struct btrfs_chunk *chunk;
5029 struct btrfs_stripe *stripe;
5030 struct extent_map *em;
5031 struct map_lookup *map;
5038 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5042 map = em->map_lookup;
5043 item_size = btrfs_chunk_item_size(map->num_stripes);
5044 stripe_size = em->orig_block_len;
5046 chunk = kzalloc(item_size, GFP_NOFS);
5053 * Take the device list mutex to prevent races with the final phase of
5054 * a device replace operation that replaces the device object associated
5055 * with the map's stripes, because the device object's id can change
5056 * at any time during that final phase of the device replace operation
5057 * (dev-replace.c:btrfs_dev_replace_finishing()).
5059 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5060 for (i = 0; i < map->num_stripes; i++) {
5061 device = map->stripes[i].dev;
5062 dev_offset = map->stripes[i].physical;
5064 ret = btrfs_update_device(trans, device);
5067 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5068 dev_offset, stripe_size);
5073 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5077 stripe = &chunk->stripe;
5078 for (i = 0; i < map->num_stripes; i++) {
5079 device = map->stripes[i].dev;
5080 dev_offset = map->stripes[i].physical;
5082 btrfs_set_stack_stripe_devid(stripe, device->devid);
5083 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5084 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5087 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5089 btrfs_set_stack_chunk_length(chunk, chunk_size);
5090 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5091 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5092 btrfs_set_stack_chunk_type(chunk, map->type);
5093 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5094 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5095 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5096 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5097 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5099 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5100 key.type = BTRFS_CHUNK_ITEM_KEY;
5101 key.offset = chunk_offset;
5103 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5104 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5106 * TODO: Cleanup of inserted chunk root in case of
5109 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5114 free_extent_map(em);
5119 * Chunk allocation falls into two parts. The first part does work
5120 * that makes the new allocated chunk usable, but does not do any operation
5121 * that modifies the chunk tree. The second part does the work that
5122 * requires modifying the chunk tree. This division is important for the
5123 * bootstrap process of adding storage to a seed btrfs.
5125 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5129 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5130 chunk_offset = find_next_chunk(trans->fs_info);
5131 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5134 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5136 struct btrfs_fs_info *fs_info = trans->fs_info;
5138 u64 sys_chunk_offset;
5142 chunk_offset = find_next_chunk(fs_info);
5143 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5144 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5148 sys_chunk_offset = find_next_chunk(fs_info);
5149 alloc_profile = btrfs_system_alloc_profile(fs_info);
5150 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5154 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5156 const int index = btrfs_bg_flags_to_raid_index(map->type);
5158 return btrfs_raid_array[index].tolerated_failures;
5161 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5163 struct extent_map *em;
5164 struct map_lookup *map;
5169 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5173 map = em->map_lookup;
5174 for (i = 0; i < map->num_stripes; i++) {
5175 if (test_bit(BTRFS_DEV_STATE_MISSING,
5176 &map->stripes[i].dev->dev_state)) {
5180 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5181 &map->stripes[i].dev->dev_state)) {
5188 * If the number of missing devices is larger than max errors,
5189 * we can not write the data into that chunk successfully, so
5192 if (miss_ndevs > btrfs_chunk_max_errors(map))
5195 free_extent_map(em);
5199 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5201 struct extent_map *em;
5204 write_lock(&tree->lock);
5205 em = lookup_extent_mapping(tree, 0, (u64)-1);
5207 remove_extent_mapping(tree, em);
5208 write_unlock(&tree->lock);
5212 free_extent_map(em);
5213 /* once for the tree */
5214 free_extent_map(em);
5218 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5220 struct extent_map *em;
5221 struct map_lookup *map;
5224 em = btrfs_get_chunk_map(fs_info, logical, len);
5227 * We could return errors for these cases, but that could get
5228 * ugly and we'd probably do the same thing which is just not do
5229 * anything else and exit, so return 1 so the callers don't try
5230 * to use other copies.
5234 map = em->map_lookup;
5235 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5236 ret = map->num_stripes;
5237 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5238 ret = map->sub_stripes;
5239 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5241 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5243 * There could be two corrupted data stripes, we need
5244 * to loop retry in order to rebuild the correct data.
5246 * Fail a stripe at a time on every retry except the
5247 * stripe under reconstruction.
5249 ret = map->num_stripes;
5252 free_extent_map(em);
5254 down_read(&fs_info->dev_replace.rwsem);
5255 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5256 fs_info->dev_replace.tgtdev)
5258 up_read(&fs_info->dev_replace.rwsem);
5263 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5266 struct extent_map *em;
5267 struct map_lookup *map;
5268 unsigned long len = fs_info->sectorsize;
5270 em = btrfs_get_chunk_map(fs_info, logical, len);
5272 if (!WARN_ON(IS_ERR(em))) {
5273 map = em->map_lookup;
5274 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5275 len = map->stripe_len * nr_data_stripes(map);
5276 free_extent_map(em);
5281 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5283 struct extent_map *em;
5284 struct map_lookup *map;
5287 em = btrfs_get_chunk_map(fs_info, logical, len);
5289 if(!WARN_ON(IS_ERR(em))) {
5290 map = em->map_lookup;
5291 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5293 free_extent_map(em);
5298 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5299 struct map_lookup *map, int first,
5300 int dev_replace_is_ongoing)
5304 int preferred_mirror;
5306 struct btrfs_device *srcdev;
5309 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5311 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5312 num_stripes = map->sub_stripes;
5314 num_stripes = map->num_stripes;
5316 preferred_mirror = first + current->pid % num_stripes;
5318 if (dev_replace_is_ongoing &&
5319 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5320 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5321 srcdev = fs_info->dev_replace.srcdev;
5326 * try to avoid the drive that is the source drive for a
5327 * dev-replace procedure, only choose it if no other non-missing
5328 * mirror is available
5330 for (tolerance = 0; tolerance < 2; tolerance++) {
5331 if (map->stripes[preferred_mirror].dev->bdev &&
5332 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5333 return preferred_mirror;
5334 for (i = first; i < first + num_stripes; i++) {
5335 if (map->stripes[i].dev->bdev &&
5336 (tolerance || map->stripes[i].dev != srcdev))
5341 /* we couldn't find one that doesn't fail. Just return something
5342 * and the io error handling code will clean up eventually
5344 return preferred_mirror;
5347 static inline int parity_smaller(u64 a, u64 b)
5352 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5353 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5355 struct btrfs_bio_stripe s;
5362 for (i = 0; i < num_stripes - 1; i++) {
5363 if (parity_smaller(bbio->raid_map[i],
5364 bbio->raid_map[i+1])) {
5365 s = bbio->stripes[i];
5366 l = bbio->raid_map[i];
5367 bbio->stripes[i] = bbio->stripes[i+1];
5368 bbio->raid_map[i] = bbio->raid_map[i+1];
5369 bbio->stripes[i+1] = s;
5370 bbio->raid_map[i+1] = l;
5378 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5380 struct btrfs_bio *bbio = kzalloc(
5381 /* the size of the btrfs_bio */
5382 sizeof(struct btrfs_bio) +
5383 /* plus the variable array for the stripes */
5384 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5385 /* plus the variable array for the tgt dev */
5386 sizeof(int) * (real_stripes) +
5388 * plus the raid_map, which includes both the tgt dev
5391 sizeof(u64) * (total_stripes),
5392 GFP_NOFS|__GFP_NOFAIL);
5394 atomic_set(&bbio->error, 0);
5395 refcount_set(&bbio->refs, 1);
5400 void btrfs_get_bbio(struct btrfs_bio *bbio)
5402 WARN_ON(!refcount_read(&bbio->refs));
5403 refcount_inc(&bbio->refs);
5406 void btrfs_put_bbio(struct btrfs_bio *bbio)
5410 if (refcount_dec_and_test(&bbio->refs))
5414 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5416 * Please note that, discard won't be sent to target device of device
5419 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5420 u64 logical, u64 *length_ret,
5421 struct btrfs_bio **bbio_ret)
5423 struct extent_map *em;
5424 struct map_lookup *map;
5425 struct btrfs_bio *bbio;
5426 u64 length = *length_ret;
5430 u64 stripe_end_offset;
5437 u32 sub_stripes = 0;
5438 u64 stripes_per_dev = 0;
5439 u32 remaining_stripes = 0;
5440 u32 last_stripe = 0;
5444 /* discard always return a bbio */
5447 em = btrfs_get_chunk_map(fs_info, logical, length);
5451 map = em->map_lookup;
5452 /* we don't discard raid56 yet */
5453 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5458 offset = logical - em->start;
5459 length = min_t(u64, em->start + em->len - logical, length);
5460 *length_ret = length;
5462 stripe_len = map->stripe_len;
5464 * stripe_nr counts the total number of stripes we have to stride
5465 * to get to this block
5467 stripe_nr = div64_u64(offset, stripe_len);
5469 /* stripe_offset is the offset of this block in its stripe */
5470 stripe_offset = offset - stripe_nr * stripe_len;
5472 stripe_nr_end = round_up(offset + length, map->stripe_len);
5473 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5474 stripe_cnt = stripe_nr_end - stripe_nr;
5475 stripe_end_offset = stripe_nr_end * map->stripe_len -
5478 * after this, stripe_nr is the number of stripes on this
5479 * device we have to walk to find the data, and stripe_index is
5480 * the number of our device in the stripe array
5484 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5485 BTRFS_BLOCK_GROUP_RAID10)) {
5486 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5489 sub_stripes = map->sub_stripes;
5491 factor = map->num_stripes / sub_stripes;
5492 num_stripes = min_t(u64, map->num_stripes,
5493 sub_stripes * stripe_cnt);
5494 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5495 stripe_index *= sub_stripes;
5496 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5497 &remaining_stripes);
5498 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5499 last_stripe *= sub_stripes;
5500 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5501 BTRFS_BLOCK_GROUP_DUP)) {
5502 num_stripes = map->num_stripes;
5504 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5508 bbio = alloc_btrfs_bio(num_stripes, 0);
5514 for (i = 0; i < num_stripes; i++) {
5515 bbio->stripes[i].physical =
5516 map->stripes[stripe_index].physical +
5517 stripe_offset + stripe_nr * map->stripe_len;
5518 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5520 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5521 BTRFS_BLOCK_GROUP_RAID10)) {
5522 bbio->stripes[i].length = stripes_per_dev *
5525 if (i / sub_stripes < remaining_stripes)
5526 bbio->stripes[i].length +=
5530 * Special for the first stripe and
5533 * |-------|...|-------|
5537 if (i < sub_stripes)
5538 bbio->stripes[i].length -=
5541 if (stripe_index >= last_stripe &&
5542 stripe_index <= (last_stripe +
5544 bbio->stripes[i].length -=
5547 if (i == sub_stripes - 1)
5550 bbio->stripes[i].length = length;
5554 if (stripe_index == map->num_stripes) {
5561 bbio->map_type = map->type;
5562 bbio->num_stripes = num_stripes;
5564 free_extent_map(em);
5569 * In dev-replace case, for repair case (that's the only case where the mirror
5570 * is selected explicitly when calling btrfs_map_block), blocks left of the
5571 * left cursor can also be read from the target drive.
5573 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5575 * For READ, it also needs to be supported using the same mirror number.
5577 * If the requested block is not left of the left cursor, EIO is returned. This
5578 * can happen because btrfs_num_copies() returns one more in the dev-replace
5581 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5582 u64 logical, u64 length,
5583 u64 srcdev_devid, int *mirror_num,
5586 struct btrfs_bio *bbio = NULL;
5588 int index_srcdev = 0;
5590 u64 physical_of_found = 0;
5594 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5595 logical, &length, &bbio, 0, 0);
5597 ASSERT(bbio == NULL);
5601 num_stripes = bbio->num_stripes;
5602 if (*mirror_num > num_stripes) {
5604 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5605 * that means that the requested area is not left of the left
5608 btrfs_put_bbio(bbio);
5613 * process the rest of the function using the mirror_num of the source
5614 * drive. Therefore look it up first. At the end, patch the device
5615 * pointer to the one of the target drive.
5617 for (i = 0; i < num_stripes; i++) {
5618 if (bbio->stripes[i].dev->devid != srcdev_devid)
5622 * In case of DUP, in order to keep it simple, only add the
5623 * mirror with the lowest physical address
5626 physical_of_found <= bbio->stripes[i].physical)
5631 physical_of_found = bbio->stripes[i].physical;
5634 btrfs_put_bbio(bbio);
5640 *mirror_num = index_srcdev + 1;
5641 *physical = physical_of_found;
5645 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5646 struct btrfs_bio **bbio_ret,
5647 struct btrfs_dev_replace *dev_replace,
5648 int *num_stripes_ret, int *max_errors_ret)
5650 struct btrfs_bio *bbio = *bbio_ret;
5651 u64 srcdev_devid = dev_replace->srcdev->devid;
5652 int tgtdev_indexes = 0;
5653 int num_stripes = *num_stripes_ret;
5654 int max_errors = *max_errors_ret;
5657 if (op == BTRFS_MAP_WRITE) {
5658 int index_where_to_add;
5661 * duplicate the write operations while the dev replace
5662 * procedure is running. Since the copying of the old disk to
5663 * the new disk takes place at run time while the filesystem is
5664 * mounted writable, the regular write operations to the old
5665 * disk have to be duplicated to go to the new disk as well.
5667 * Note that device->missing is handled by the caller, and that
5668 * the write to the old disk is already set up in the stripes
5671 index_where_to_add = num_stripes;
5672 for (i = 0; i < num_stripes; i++) {
5673 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5674 /* write to new disk, too */
5675 struct btrfs_bio_stripe *new =
5676 bbio->stripes + index_where_to_add;
5677 struct btrfs_bio_stripe *old =
5680 new->physical = old->physical;
5681 new->length = old->length;
5682 new->dev = dev_replace->tgtdev;
5683 bbio->tgtdev_map[i] = index_where_to_add;
5684 index_where_to_add++;
5689 num_stripes = index_where_to_add;
5690 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5691 int index_srcdev = 0;
5693 u64 physical_of_found = 0;
5696 * During the dev-replace procedure, the target drive can also
5697 * be used to read data in case it is needed to repair a corrupt
5698 * block elsewhere. This is possible if the requested area is
5699 * left of the left cursor. In this area, the target drive is a
5700 * full copy of the source drive.
5702 for (i = 0; i < num_stripes; i++) {
5703 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5705 * In case of DUP, in order to keep it simple,
5706 * only add the mirror with the lowest physical
5710 physical_of_found <=
5711 bbio->stripes[i].physical)
5715 physical_of_found = bbio->stripes[i].physical;
5719 struct btrfs_bio_stripe *tgtdev_stripe =
5720 bbio->stripes + num_stripes;
5722 tgtdev_stripe->physical = physical_of_found;
5723 tgtdev_stripe->length =
5724 bbio->stripes[index_srcdev].length;
5725 tgtdev_stripe->dev = dev_replace->tgtdev;
5726 bbio->tgtdev_map[index_srcdev] = num_stripes;
5733 *num_stripes_ret = num_stripes;
5734 *max_errors_ret = max_errors;
5735 bbio->num_tgtdevs = tgtdev_indexes;
5739 static bool need_full_stripe(enum btrfs_map_op op)
5741 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5745 * btrfs_get_io_geometry - calculates the geomery of a particular (address, len)
5746 * tuple. This information is used to calculate how big a
5747 * particular bio can get before it straddles a stripe.
5749 * @fs_info - the filesystem
5750 * @logical - address that we want to figure out the geometry of
5751 * @len - the length of IO we are going to perform, starting at @logical
5752 * @op - type of operation - write or read
5753 * @io_geom - pointer used to return values
5755 * Returns < 0 in case a chunk for the given logical address cannot be found,
5756 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
5758 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5759 u64 logical, u64 len, struct btrfs_io_geometry *io_geom)
5761 struct extent_map *em;
5762 struct map_lookup *map;
5767 u64 raid56_full_stripe_start = (u64)-1;
5771 ASSERT(op != BTRFS_MAP_DISCARD);
5773 em = btrfs_get_chunk_map(fs_info, logical, len);
5777 map = em->map_lookup;
5778 /* Offset of this logical address in the chunk */
5779 offset = logical - em->start;
5780 /* Len of a stripe in a chunk */
5781 stripe_len = map->stripe_len;
5782 /* Stripe wher this block falls in */
5783 stripe_nr = div64_u64(offset, stripe_len);
5784 /* Offset of stripe in the chunk */
5785 stripe_offset = stripe_nr * stripe_len;
5786 if (offset < stripe_offset) {
5788 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
5789 stripe_offset, offset, em->start, logical, stripe_len);
5794 /* stripe_offset is the offset of this block in its stripe */
5795 stripe_offset = offset - stripe_offset;
5796 data_stripes = nr_data_stripes(map);
5798 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5799 u64 max_len = stripe_len - stripe_offset;
5802 * In case of raid56, we need to know the stripe aligned start
5804 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5805 unsigned long full_stripe_len = stripe_len * data_stripes;
5806 raid56_full_stripe_start = offset;
5809 * Allow a write of a full stripe, but make sure we
5810 * don't allow straddling of stripes
5812 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5814 raid56_full_stripe_start *= full_stripe_len;
5817 * For writes to RAID[56], allow a full stripeset across
5818 * all disks. For other RAID types and for RAID[56]
5819 * reads, just allow a single stripe (on a single disk).
5821 if (op == BTRFS_MAP_WRITE) {
5822 max_len = stripe_len * data_stripes -
5823 (offset - raid56_full_stripe_start);
5826 len = min_t(u64, em->len - offset, max_len);
5828 len = em->len - offset;
5832 io_geom->offset = offset;
5833 io_geom->stripe_len = stripe_len;
5834 io_geom->stripe_nr = stripe_nr;
5835 io_geom->stripe_offset = stripe_offset;
5836 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
5840 free_extent_map(em);
5844 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5845 enum btrfs_map_op op,
5846 u64 logical, u64 *length,
5847 struct btrfs_bio **bbio_ret,
5848 int mirror_num, int need_raid_map)
5850 struct extent_map *em;
5851 struct map_lookup *map;
5861 int tgtdev_indexes = 0;
5862 struct btrfs_bio *bbio = NULL;
5863 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5864 int dev_replace_is_ongoing = 0;
5865 int num_alloc_stripes;
5866 int patch_the_first_stripe_for_dev_replace = 0;
5867 u64 physical_to_patch_in_first_stripe = 0;
5868 u64 raid56_full_stripe_start = (u64)-1;
5869 struct btrfs_io_geometry geom;
5873 if (op == BTRFS_MAP_DISCARD)
5874 return __btrfs_map_block_for_discard(fs_info, logical,
5877 ret = btrfs_get_io_geometry(fs_info, op, logical, *length, &geom);
5881 em = btrfs_get_chunk_map(fs_info, logical, *length);
5882 ASSERT(!IS_ERR(em));
5883 map = em->map_lookup;
5886 stripe_len = geom.stripe_len;
5887 stripe_nr = geom.stripe_nr;
5888 stripe_offset = geom.stripe_offset;
5889 raid56_full_stripe_start = geom.raid56_stripe_offset;
5890 data_stripes = nr_data_stripes(map);
5892 down_read(&dev_replace->rwsem);
5893 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5895 * Hold the semaphore for read during the whole operation, write is
5896 * requested at commit time but must wait.
5898 if (!dev_replace_is_ongoing)
5899 up_read(&dev_replace->rwsem);
5901 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5902 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5903 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5904 dev_replace->srcdev->devid,
5906 &physical_to_patch_in_first_stripe);
5910 patch_the_first_stripe_for_dev_replace = 1;
5911 } else if (mirror_num > map->num_stripes) {
5917 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5918 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5920 if (!need_full_stripe(op))
5922 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
5923 if (need_full_stripe(op))
5924 num_stripes = map->num_stripes;
5925 else if (mirror_num)
5926 stripe_index = mirror_num - 1;
5928 stripe_index = find_live_mirror(fs_info, map, 0,
5929 dev_replace_is_ongoing);
5930 mirror_num = stripe_index + 1;
5933 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5934 if (need_full_stripe(op)) {
5935 num_stripes = map->num_stripes;
5936 } else if (mirror_num) {
5937 stripe_index = mirror_num - 1;
5942 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5943 u32 factor = map->num_stripes / map->sub_stripes;
5945 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5946 stripe_index *= map->sub_stripes;
5948 if (need_full_stripe(op))
5949 num_stripes = map->sub_stripes;
5950 else if (mirror_num)
5951 stripe_index += mirror_num - 1;
5953 int old_stripe_index = stripe_index;
5954 stripe_index = find_live_mirror(fs_info, map,
5956 dev_replace_is_ongoing);
5957 mirror_num = stripe_index - old_stripe_index + 1;
5960 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5961 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5962 /* push stripe_nr back to the start of the full stripe */
5963 stripe_nr = div64_u64(raid56_full_stripe_start,
5964 stripe_len * data_stripes);
5966 /* RAID[56] write or recovery. Return all stripes */
5967 num_stripes = map->num_stripes;
5968 max_errors = nr_parity_stripes(map);
5970 *length = map->stripe_len;
5975 * Mirror #0 or #1 means the original data block.
5976 * Mirror #2 is RAID5 parity block.
5977 * Mirror #3 is RAID6 Q block.
5979 stripe_nr = div_u64_rem(stripe_nr,
5980 data_stripes, &stripe_index);
5982 stripe_index = data_stripes + mirror_num - 2;
5984 /* We distribute the parity blocks across stripes */
5985 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5987 if (!need_full_stripe(op) && mirror_num <= 1)
5992 * after this, stripe_nr is the number of stripes on this
5993 * device we have to walk to find the data, and stripe_index is
5994 * the number of our device in the stripe array
5996 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5998 mirror_num = stripe_index + 1;
6000 if (stripe_index >= map->num_stripes) {
6002 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6003 stripe_index, map->num_stripes);
6008 num_alloc_stripes = num_stripes;
6009 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6010 if (op == BTRFS_MAP_WRITE)
6011 num_alloc_stripes <<= 1;
6012 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6013 num_alloc_stripes++;
6014 tgtdev_indexes = num_stripes;
6017 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6022 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
6023 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
6025 /* build raid_map */
6026 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6027 (need_full_stripe(op) || mirror_num > 1)) {
6031 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6032 sizeof(struct btrfs_bio_stripe) *
6034 sizeof(int) * tgtdev_indexes);
6036 /* Work out the disk rotation on this stripe-set */
6037 div_u64_rem(stripe_nr, num_stripes, &rot);
6039 /* Fill in the logical address of each stripe */
6040 tmp = stripe_nr * data_stripes;
6041 for (i = 0; i < data_stripes; i++)
6042 bbio->raid_map[(i+rot) % num_stripes] =
6043 em->start + (tmp + i) * map->stripe_len;
6045 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6046 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6047 bbio->raid_map[(i+rot+1) % num_stripes] =
6052 for (i = 0; i < num_stripes; i++) {
6053 bbio->stripes[i].physical =
6054 map->stripes[stripe_index].physical +
6056 stripe_nr * map->stripe_len;
6057 bbio->stripes[i].dev =
6058 map->stripes[stripe_index].dev;
6062 if (need_full_stripe(op))
6063 max_errors = btrfs_chunk_max_errors(map);
6066 sort_parity_stripes(bbio, num_stripes);
6068 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6069 need_full_stripe(op)) {
6070 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6075 bbio->map_type = map->type;
6076 bbio->num_stripes = num_stripes;
6077 bbio->max_errors = max_errors;
6078 bbio->mirror_num = mirror_num;
6081 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6082 * mirror_num == num_stripes + 1 && dev_replace target drive is
6083 * available as a mirror
6085 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6086 WARN_ON(num_stripes > 1);
6087 bbio->stripes[0].dev = dev_replace->tgtdev;
6088 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6089 bbio->mirror_num = map->num_stripes + 1;
6092 if (dev_replace_is_ongoing) {
6093 lockdep_assert_held(&dev_replace->rwsem);
6094 /* Unlock and let waiting writers proceed */
6095 up_read(&dev_replace->rwsem);
6097 free_extent_map(em);
6101 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6102 u64 logical, u64 *length,
6103 struct btrfs_bio **bbio_ret, int mirror_num)
6105 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6109 /* For Scrub/replace */
6110 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6111 u64 logical, u64 *length,
6112 struct btrfs_bio **bbio_ret)
6114 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6117 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6119 bio->bi_private = bbio->private;
6120 bio->bi_end_io = bbio->end_io;
6123 btrfs_put_bbio(bbio);
6126 static void btrfs_end_bio(struct bio *bio)
6128 struct btrfs_bio *bbio = bio->bi_private;
6129 int is_orig_bio = 0;
6131 if (bio->bi_status) {
6132 atomic_inc(&bbio->error);
6133 if (bio->bi_status == BLK_STS_IOERR ||
6134 bio->bi_status == BLK_STS_TARGET) {
6135 unsigned int stripe_index =
6136 btrfs_io_bio(bio)->stripe_index;
6137 struct btrfs_device *dev;
6139 BUG_ON(stripe_index >= bbio->num_stripes);
6140 dev = bbio->stripes[stripe_index].dev;
6142 if (bio_op(bio) == REQ_OP_WRITE)
6143 btrfs_dev_stat_inc_and_print(dev,
6144 BTRFS_DEV_STAT_WRITE_ERRS);
6145 else if (!(bio->bi_opf & REQ_RAHEAD))
6146 btrfs_dev_stat_inc_and_print(dev,
6147 BTRFS_DEV_STAT_READ_ERRS);
6148 if (bio->bi_opf & REQ_PREFLUSH)
6149 btrfs_dev_stat_inc_and_print(dev,
6150 BTRFS_DEV_STAT_FLUSH_ERRS);
6155 if (bio == bbio->orig_bio)
6158 btrfs_bio_counter_dec(bbio->fs_info);
6160 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6163 bio = bbio->orig_bio;
6166 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6167 /* only send an error to the higher layers if it is
6168 * beyond the tolerance of the btrfs bio
6170 if (atomic_read(&bbio->error) > bbio->max_errors) {
6171 bio->bi_status = BLK_STS_IOERR;
6174 * this bio is actually up to date, we didn't
6175 * go over the max number of errors
6177 bio->bi_status = BLK_STS_OK;
6180 btrfs_end_bbio(bbio, bio);
6181 } else if (!is_orig_bio) {
6186 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6187 u64 physical, int dev_nr)
6189 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6190 struct btrfs_fs_info *fs_info = bbio->fs_info;
6192 bio->bi_private = bbio;
6193 btrfs_io_bio(bio)->stripe_index = dev_nr;
6194 bio->bi_end_io = btrfs_end_bio;
6195 bio->bi_iter.bi_sector = physical >> 9;
6196 btrfs_debug_in_rcu(fs_info,
6197 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6198 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6199 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6200 bio->bi_iter.bi_size);
6201 bio_set_dev(bio, dev->bdev);
6203 btrfs_bio_counter_inc_noblocked(fs_info);
6205 btrfsic_submit_bio(bio);
6208 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6210 atomic_inc(&bbio->error);
6211 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6212 /* Should be the original bio. */
6213 WARN_ON(bio != bbio->orig_bio);
6215 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6216 bio->bi_iter.bi_sector = logical >> 9;
6217 if (atomic_read(&bbio->error) > bbio->max_errors)
6218 bio->bi_status = BLK_STS_IOERR;
6220 bio->bi_status = BLK_STS_OK;
6221 btrfs_end_bbio(bbio, bio);
6225 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6228 struct btrfs_device *dev;
6229 struct bio *first_bio = bio;
6230 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6236 struct btrfs_bio *bbio = NULL;
6238 length = bio->bi_iter.bi_size;
6239 map_length = length;
6241 btrfs_bio_counter_inc_blocked(fs_info);
6242 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6243 &map_length, &bbio, mirror_num, 1);
6245 btrfs_bio_counter_dec(fs_info);
6246 return errno_to_blk_status(ret);
6249 total_devs = bbio->num_stripes;
6250 bbio->orig_bio = first_bio;
6251 bbio->private = first_bio->bi_private;
6252 bbio->end_io = first_bio->bi_end_io;
6253 bbio->fs_info = fs_info;
6254 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6256 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6257 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6258 /* In this case, map_length has been set to the length of
6259 a single stripe; not the whole write */
6260 if (bio_op(bio) == REQ_OP_WRITE) {
6261 ret = raid56_parity_write(fs_info, bio, bbio,
6264 ret = raid56_parity_recover(fs_info, bio, bbio,
6265 map_length, mirror_num, 1);
6268 btrfs_bio_counter_dec(fs_info);
6269 return errno_to_blk_status(ret);
6272 if (map_length < length) {
6274 "mapping failed logical %llu bio len %llu len %llu",
6275 logical, length, map_length);
6279 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6280 dev = bbio->stripes[dev_nr].dev;
6281 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6283 (bio_op(first_bio) == REQ_OP_WRITE &&
6284 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6285 bbio_error(bbio, first_bio, logical);
6289 if (dev_nr < total_devs - 1)
6290 bio = btrfs_bio_clone(first_bio);
6294 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6297 btrfs_bio_counter_dec(fs_info);
6302 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6305 * If devid and uuid are both specified, the match must be exact, otherwise
6306 * only devid is used.
6308 * If @seed is true, traverse through the seed devices.
6310 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6311 u64 devid, u8 *uuid, u8 *fsid,
6314 struct btrfs_device *device;
6316 while (fs_devices) {
6318 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6319 list_for_each_entry(device, &fs_devices->devices,
6321 if (device->devid == devid &&
6322 (!uuid || memcmp(device->uuid, uuid,
6323 BTRFS_UUID_SIZE) == 0))
6328 fs_devices = fs_devices->seed;
6335 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6336 u64 devid, u8 *dev_uuid)
6338 struct btrfs_device *device;
6340 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6344 list_add(&device->dev_list, &fs_devices->devices);
6345 device->fs_devices = fs_devices;
6346 fs_devices->num_devices++;
6348 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6349 fs_devices->missing_devices++;
6355 * btrfs_alloc_device - allocate struct btrfs_device
6356 * @fs_info: used only for generating a new devid, can be NULL if
6357 * devid is provided (i.e. @devid != NULL).
6358 * @devid: a pointer to devid for this device. If NULL a new devid
6360 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6363 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6364 * on error. Returned struct is not linked onto any lists and must be
6365 * destroyed with btrfs_free_device.
6367 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6371 struct btrfs_device *dev;
6374 if (WARN_ON(!devid && !fs_info))
6375 return ERR_PTR(-EINVAL);
6377 dev = __alloc_device();
6386 ret = find_next_devid(fs_info, &tmp);
6388 btrfs_free_device(dev);
6389 return ERR_PTR(ret);
6395 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6397 generate_random_uuid(dev->uuid);
6402 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6403 u64 devid, u8 *uuid, bool error)
6406 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6409 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6413 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6415 int index = btrfs_bg_flags_to_raid_index(type);
6416 int ncopies = btrfs_raid_array[index].ncopies;
6417 const int nparity = btrfs_raid_array[index].nparity;
6421 data_stripes = num_stripes - nparity;
6423 data_stripes = num_stripes / ncopies;
6425 return div_u64(chunk_len, data_stripes);
6428 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6429 struct btrfs_chunk *chunk)
6431 struct btrfs_fs_info *fs_info = leaf->fs_info;
6432 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6433 struct map_lookup *map;
6434 struct extent_map *em;
6438 u8 uuid[BTRFS_UUID_SIZE];
6443 logical = key->offset;
6444 length = btrfs_chunk_length(leaf, chunk);
6445 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6448 * Only need to verify chunk item if we're reading from sys chunk array,
6449 * as chunk item in tree block is already verified by tree-checker.
6451 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6452 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6457 read_lock(&map_tree->lock);
6458 em = lookup_extent_mapping(map_tree, logical, 1);
6459 read_unlock(&map_tree->lock);
6461 /* already mapped? */
6462 if (em && em->start <= logical && em->start + em->len > logical) {
6463 free_extent_map(em);
6466 free_extent_map(em);
6469 em = alloc_extent_map();
6472 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6474 free_extent_map(em);
6478 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6479 em->map_lookup = map;
6480 em->start = logical;
6483 em->block_start = 0;
6484 em->block_len = em->len;
6486 map->num_stripes = num_stripes;
6487 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6488 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6489 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6490 map->type = btrfs_chunk_type(leaf, chunk);
6491 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6492 map->verified_stripes = 0;
6493 em->orig_block_len = calc_stripe_length(map->type, em->len,
6495 for (i = 0; i < num_stripes; i++) {
6496 map->stripes[i].physical =
6497 btrfs_stripe_offset_nr(leaf, chunk, i);
6498 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6499 read_extent_buffer(leaf, uuid, (unsigned long)
6500 btrfs_stripe_dev_uuid_nr(chunk, i),
6502 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6503 devid, uuid, NULL, true);
6504 if (!map->stripes[i].dev &&
6505 !btrfs_test_opt(fs_info, DEGRADED)) {
6506 free_extent_map(em);
6507 btrfs_report_missing_device(fs_info, devid, uuid, true);
6510 if (!map->stripes[i].dev) {
6511 map->stripes[i].dev =
6512 add_missing_dev(fs_info->fs_devices, devid,
6514 if (IS_ERR(map->stripes[i].dev)) {
6515 free_extent_map(em);
6517 "failed to init missing dev %llu: %ld",
6518 devid, PTR_ERR(map->stripes[i].dev));
6519 return PTR_ERR(map->stripes[i].dev);
6521 btrfs_report_missing_device(fs_info, devid, uuid, false);
6523 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6524 &(map->stripes[i].dev->dev_state));
6528 write_lock(&map_tree->lock);
6529 ret = add_extent_mapping(map_tree, em, 0);
6530 write_unlock(&map_tree->lock);
6533 "failed to add chunk map, start=%llu len=%llu: %d",
6534 em->start, em->len, ret);
6536 free_extent_map(em);
6541 static void fill_device_from_item(struct extent_buffer *leaf,
6542 struct btrfs_dev_item *dev_item,
6543 struct btrfs_device *device)
6547 device->devid = btrfs_device_id(leaf, dev_item);
6548 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6549 device->total_bytes = device->disk_total_bytes;
6550 device->commit_total_bytes = device->disk_total_bytes;
6551 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6552 device->commit_bytes_used = device->bytes_used;
6553 device->type = btrfs_device_type(leaf, dev_item);
6554 device->io_align = btrfs_device_io_align(leaf, dev_item);
6555 device->io_width = btrfs_device_io_width(leaf, dev_item);
6556 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6557 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6558 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6560 ptr = btrfs_device_uuid(dev_item);
6561 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6564 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6567 struct btrfs_fs_devices *fs_devices;
6570 lockdep_assert_held(&uuid_mutex);
6573 fs_devices = fs_info->fs_devices->seed;
6574 while (fs_devices) {
6575 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6578 fs_devices = fs_devices->seed;
6581 fs_devices = find_fsid(fsid, NULL);
6583 if (!btrfs_test_opt(fs_info, DEGRADED))
6584 return ERR_PTR(-ENOENT);
6586 fs_devices = alloc_fs_devices(fsid, NULL);
6587 if (IS_ERR(fs_devices))
6590 fs_devices->seeding = true;
6591 fs_devices->opened = 1;
6595 fs_devices = clone_fs_devices(fs_devices);
6596 if (IS_ERR(fs_devices))
6599 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6601 free_fs_devices(fs_devices);
6602 fs_devices = ERR_PTR(ret);
6606 if (!fs_devices->seeding) {
6607 close_fs_devices(fs_devices);
6608 free_fs_devices(fs_devices);
6609 fs_devices = ERR_PTR(-EINVAL);
6613 fs_devices->seed = fs_info->fs_devices->seed;
6614 fs_info->fs_devices->seed = fs_devices;
6619 static int read_one_dev(struct extent_buffer *leaf,
6620 struct btrfs_dev_item *dev_item)
6622 struct btrfs_fs_info *fs_info = leaf->fs_info;
6623 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6624 struct btrfs_device *device;
6627 u8 fs_uuid[BTRFS_FSID_SIZE];
6628 u8 dev_uuid[BTRFS_UUID_SIZE];
6630 devid = btrfs_device_id(leaf, dev_item);
6631 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6633 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6636 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6637 fs_devices = open_seed_devices(fs_info, fs_uuid);
6638 if (IS_ERR(fs_devices))
6639 return PTR_ERR(fs_devices);
6642 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6645 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6646 btrfs_report_missing_device(fs_info, devid,
6651 device = add_missing_dev(fs_devices, devid, dev_uuid);
6652 if (IS_ERR(device)) {
6654 "failed to add missing dev %llu: %ld",
6655 devid, PTR_ERR(device));
6656 return PTR_ERR(device);
6658 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6660 if (!device->bdev) {
6661 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6662 btrfs_report_missing_device(fs_info,
6663 devid, dev_uuid, true);
6666 btrfs_report_missing_device(fs_info, devid,
6670 if (!device->bdev &&
6671 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6673 * this happens when a device that was properly setup
6674 * in the device info lists suddenly goes bad.
6675 * device->bdev is NULL, and so we have to set
6676 * device->missing to one here
6678 device->fs_devices->missing_devices++;
6679 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6682 /* Move the device to its own fs_devices */
6683 if (device->fs_devices != fs_devices) {
6684 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6685 &device->dev_state));
6687 list_move(&device->dev_list, &fs_devices->devices);
6688 device->fs_devices->num_devices--;
6689 fs_devices->num_devices++;
6691 device->fs_devices->missing_devices--;
6692 fs_devices->missing_devices++;
6694 device->fs_devices = fs_devices;
6698 if (device->fs_devices != fs_info->fs_devices) {
6699 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6700 if (device->generation !=
6701 btrfs_device_generation(leaf, dev_item))
6705 fill_device_from_item(leaf, dev_item, device);
6706 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6707 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6708 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6709 device->fs_devices->total_rw_bytes += device->total_bytes;
6710 atomic64_add(device->total_bytes - device->bytes_used,
6711 &fs_info->free_chunk_space);
6717 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6719 struct btrfs_root *root = fs_info->tree_root;
6720 struct btrfs_super_block *super_copy = fs_info->super_copy;
6721 struct extent_buffer *sb;
6722 struct btrfs_disk_key *disk_key;
6723 struct btrfs_chunk *chunk;
6725 unsigned long sb_array_offset;
6732 struct btrfs_key key;
6734 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6736 * This will create extent buffer of nodesize, superblock size is
6737 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6738 * overallocate but we can keep it as-is, only the first page is used.
6740 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6743 set_extent_buffer_uptodate(sb);
6744 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6746 * The sb extent buffer is artificial and just used to read the system array.
6747 * set_extent_buffer_uptodate() call does not properly mark all it's
6748 * pages up-to-date when the page is larger: extent does not cover the
6749 * whole page and consequently check_page_uptodate does not find all
6750 * the page's extents up-to-date (the hole beyond sb),
6751 * write_extent_buffer then triggers a WARN_ON.
6753 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6754 * but sb spans only this function. Add an explicit SetPageUptodate call
6755 * to silence the warning eg. on PowerPC 64.
6757 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6758 SetPageUptodate(sb->pages[0]);
6760 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6761 array_size = btrfs_super_sys_array_size(super_copy);
6763 array_ptr = super_copy->sys_chunk_array;
6764 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6767 while (cur_offset < array_size) {
6768 disk_key = (struct btrfs_disk_key *)array_ptr;
6769 len = sizeof(*disk_key);
6770 if (cur_offset + len > array_size)
6771 goto out_short_read;
6773 btrfs_disk_key_to_cpu(&key, disk_key);
6776 sb_array_offset += len;
6779 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
6781 "unexpected item type %u in sys_array at offset %u",
6782 (u32)key.type, cur_offset);
6787 chunk = (struct btrfs_chunk *)sb_array_offset;
6789 * At least one btrfs_chunk with one stripe must be present,
6790 * exact stripe count check comes afterwards
6792 len = btrfs_chunk_item_size(1);
6793 if (cur_offset + len > array_size)
6794 goto out_short_read;
6796 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6799 "invalid number of stripes %u in sys_array at offset %u",
6800 num_stripes, cur_offset);
6805 type = btrfs_chunk_type(sb, chunk);
6806 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6808 "invalid chunk type %llu in sys_array at offset %u",
6814 len = btrfs_chunk_item_size(num_stripes);
6815 if (cur_offset + len > array_size)
6816 goto out_short_read;
6818 ret = read_one_chunk(&key, sb, chunk);
6823 sb_array_offset += len;
6826 clear_extent_buffer_uptodate(sb);
6827 free_extent_buffer_stale(sb);
6831 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6833 clear_extent_buffer_uptodate(sb);
6834 free_extent_buffer_stale(sb);
6839 * Check if all chunks in the fs are OK for read-write degraded mount
6841 * If the @failing_dev is specified, it's accounted as missing.
6843 * Return true if all chunks meet the minimal RW mount requirements.
6844 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6846 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6847 struct btrfs_device *failing_dev)
6849 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6850 struct extent_map *em;
6854 read_lock(&map_tree->lock);
6855 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
6856 read_unlock(&map_tree->lock);
6857 /* No chunk at all? Return false anyway */
6863 struct map_lookup *map;
6868 map = em->map_lookup;
6870 btrfs_get_num_tolerated_disk_barrier_failures(
6872 for (i = 0; i < map->num_stripes; i++) {
6873 struct btrfs_device *dev = map->stripes[i].dev;
6875 if (!dev || !dev->bdev ||
6876 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6877 dev->last_flush_error)
6879 else if (failing_dev && failing_dev == dev)
6882 if (missing > max_tolerated) {
6885 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
6886 em->start, missing, max_tolerated);
6887 free_extent_map(em);
6891 next_start = extent_map_end(em);
6892 free_extent_map(em);
6894 read_lock(&map_tree->lock);
6895 em = lookup_extent_mapping(map_tree, next_start,
6896 (u64)(-1) - next_start);
6897 read_unlock(&map_tree->lock);
6903 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6905 struct btrfs_root *root = fs_info->chunk_root;
6906 struct btrfs_path *path;
6907 struct extent_buffer *leaf;
6908 struct btrfs_key key;
6909 struct btrfs_key found_key;
6914 path = btrfs_alloc_path();
6919 * uuid_mutex is needed only if we are mounting a sprout FS
6920 * otherwise we don't need it.
6922 mutex_lock(&uuid_mutex);
6923 mutex_lock(&fs_info->chunk_mutex);
6926 * Read all device items, and then all the chunk items. All
6927 * device items are found before any chunk item (their object id
6928 * is smaller than the lowest possible object id for a chunk
6929 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6931 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6934 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6938 leaf = path->nodes[0];
6939 slot = path->slots[0];
6940 if (slot >= btrfs_header_nritems(leaf)) {
6941 ret = btrfs_next_leaf(root, path);
6948 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6949 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6950 struct btrfs_dev_item *dev_item;
6951 dev_item = btrfs_item_ptr(leaf, slot,
6952 struct btrfs_dev_item);
6953 ret = read_one_dev(leaf, dev_item);
6957 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6958 struct btrfs_chunk *chunk;
6959 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6960 ret = read_one_chunk(&found_key, leaf, chunk);
6968 * After loading chunk tree, we've got all device information,
6969 * do another round of validation checks.
6971 if (total_dev != fs_info->fs_devices->total_devices) {
6973 "super_num_devices %llu mismatch with num_devices %llu found here",
6974 btrfs_super_num_devices(fs_info->super_copy),
6979 if (btrfs_super_total_bytes(fs_info->super_copy) <
6980 fs_info->fs_devices->total_rw_bytes) {
6982 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
6983 btrfs_super_total_bytes(fs_info->super_copy),
6984 fs_info->fs_devices->total_rw_bytes);
6990 mutex_unlock(&fs_info->chunk_mutex);
6991 mutex_unlock(&uuid_mutex);
6993 btrfs_free_path(path);
6997 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6999 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7000 struct btrfs_device *device;
7002 while (fs_devices) {
7003 mutex_lock(&fs_devices->device_list_mutex);
7004 list_for_each_entry(device, &fs_devices->devices, dev_list)
7005 device->fs_info = fs_info;
7006 mutex_unlock(&fs_devices->device_list_mutex);
7008 fs_devices = fs_devices->seed;
7012 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7013 const struct btrfs_dev_stats_item *ptr,
7018 read_extent_buffer(eb, &val,
7019 offsetof(struct btrfs_dev_stats_item, values) +
7020 ((unsigned long)ptr) + (index * sizeof(u64)),
7025 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7026 struct btrfs_dev_stats_item *ptr,
7029 write_extent_buffer(eb, &val,
7030 offsetof(struct btrfs_dev_stats_item, values) +
7031 ((unsigned long)ptr) + (index * sizeof(u64)),
7035 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7037 struct btrfs_key key;
7038 struct btrfs_root *dev_root = fs_info->dev_root;
7039 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7040 struct extent_buffer *eb;
7043 struct btrfs_device *device;
7044 struct btrfs_path *path = NULL;
7047 path = btrfs_alloc_path();
7051 mutex_lock(&fs_devices->device_list_mutex);
7052 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7054 struct btrfs_dev_stats_item *ptr;
7056 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7057 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7058 key.offset = device->devid;
7059 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7061 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7062 btrfs_dev_stat_set(device, i, 0);
7063 device->dev_stats_valid = 1;
7064 btrfs_release_path(path);
7067 slot = path->slots[0];
7068 eb = path->nodes[0];
7069 item_size = btrfs_item_size_nr(eb, slot);
7071 ptr = btrfs_item_ptr(eb, slot,
7072 struct btrfs_dev_stats_item);
7074 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7075 if (item_size >= (1 + i) * sizeof(__le64))
7076 btrfs_dev_stat_set(device, i,
7077 btrfs_dev_stats_value(eb, ptr, i));
7079 btrfs_dev_stat_set(device, i, 0);
7082 device->dev_stats_valid = 1;
7083 btrfs_dev_stat_print_on_load(device);
7084 btrfs_release_path(path);
7086 mutex_unlock(&fs_devices->device_list_mutex);
7088 btrfs_free_path(path);
7089 return ret < 0 ? ret : 0;
7092 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7093 struct btrfs_device *device)
7095 struct btrfs_fs_info *fs_info = trans->fs_info;
7096 struct btrfs_root *dev_root = fs_info->dev_root;
7097 struct btrfs_path *path;
7098 struct btrfs_key key;
7099 struct extent_buffer *eb;
7100 struct btrfs_dev_stats_item *ptr;
7104 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7105 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7106 key.offset = device->devid;
7108 path = btrfs_alloc_path();
7111 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7113 btrfs_warn_in_rcu(fs_info,
7114 "error %d while searching for dev_stats item for device %s",
7115 ret, rcu_str_deref(device->name));
7120 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7121 /* need to delete old one and insert a new one */
7122 ret = btrfs_del_item(trans, dev_root, path);
7124 btrfs_warn_in_rcu(fs_info,
7125 "delete too small dev_stats item for device %s failed %d",
7126 rcu_str_deref(device->name), ret);
7133 /* need to insert a new item */
7134 btrfs_release_path(path);
7135 ret = btrfs_insert_empty_item(trans, dev_root, path,
7136 &key, sizeof(*ptr));
7138 btrfs_warn_in_rcu(fs_info,
7139 "insert dev_stats item for device %s failed %d",
7140 rcu_str_deref(device->name), ret);
7145 eb = path->nodes[0];
7146 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7147 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7148 btrfs_set_dev_stats_value(eb, ptr, i,
7149 btrfs_dev_stat_read(device, i));
7150 btrfs_mark_buffer_dirty(eb);
7153 btrfs_free_path(path);
7158 * called from commit_transaction. Writes all changed device stats to disk.
7160 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7162 struct btrfs_fs_info *fs_info = trans->fs_info;
7163 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7164 struct btrfs_device *device;
7168 mutex_lock(&fs_devices->device_list_mutex);
7169 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7170 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7171 if (!device->dev_stats_valid || stats_cnt == 0)
7176 * There is a LOAD-LOAD control dependency between the value of
7177 * dev_stats_ccnt and updating the on-disk values which requires
7178 * reading the in-memory counters. Such control dependencies
7179 * require explicit read memory barriers.
7181 * This memory barriers pairs with smp_mb__before_atomic in
7182 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7183 * barrier implied by atomic_xchg in
7184 * btrfs_dev_stats_read_and_reset
7188 ret = update_dev_stat_item(trans, device);
7190 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7192 mutex_unlock(&fs_devices->device_list_mutex);
7197 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7199 btrfs_dev_stat_inc(dev, index);
7200 btrfs_dev_stat_print_on_error(dev);
7203 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7205 if (!dev->dev_stats_valid)
7207 btrfs_err_rl_in_rcu(dev->fs_info,
7208 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7209 rcu_str_deref(dev->name),
7210 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7211 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7212 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7213 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7214 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7217 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7221 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7222 if (btrfs_dev_stat_read(dev, i) != 0)
7224 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7225 return; /* all values == 0, suppress message */
7227 btrfs_info_in_rcu(dev->fs_info,
7228 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7229 rcu_str_deref(dev->name),
7230 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7231 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7232 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7233 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7234 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7237 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7238 struct btrfs_ioctl_get_dev_stats *stats)
7240 struct btrfs_device *dev;
7241 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7244 mutex_lock(&fs_devices->device_list_mutex);
7245 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7247 mutex_unlock(&fs_devices->device_list_mutex);
7250 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7252 } else if (!dev->dev_stats_valid) {
7253 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7255 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7256 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7257 if (stats->nr_items > i)
7259 btrfs_dev_stat_read_and_reset(dev, i);
7261 btrfs_dev_stat_set(dev, i, 0);
7263 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7264 current->comm, task_pid_nr(current));
7266 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7267 if (stats->nr_items > i)
7268 stats->values[i] = btrfs_dev_stat_read(dev, i);
7270 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7271 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7275 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7277 struct buffer_head *bh;
7278 struct btrfs_super_block *disk_super;
7284 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7287 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7290 disk_super = (struct btrfs_super_block *)bh->b_data;
7292 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7293 set_buffer_dirty(bh);
7294 sync_dirty_buffer(bh);
7298 /* Notify udev that device has changed */
7299 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7301 /* Update ctime/mtime for device path for libblkid */
7302 update_dev_time(device_path);
7306 * Update the size and bytes used for each device where it changed. This is
7307 * delayed since we would otherwise get errors while writing out the
7310 * Must be invoked during transaction commit.
7312 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7314 struct btrfs_device *curr, *next;
7316 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7318 if (list_empty(&trans->dev_update_list))
7322 * We don't need the device_list_mutex here. This list is owned by the
7323 * transaction and the transaction must complete before the device is
7326 mutex_lock(&trans->fs_info->chunk_mutex);
7327 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7329 list_del_init(&curr->post_commit_list);
7330 curr->commit_total_bytes = curr->disk_total_bytes;
7331 curr->commit_bytes_used = curr->bytes_used;
7333 mutex_unlock(&trans->fs_info->chunk_mutex);
7336 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7338 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7339 while (fs_devices) {
7340 fs_devices->fs_info = fs_info;
7341 fs_devices = fs_devices->seed;
7345 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7347 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7348 while (fs_devices) {
7349 fs_devices->fs_info = NULL;
7350 fs_devices = fs_devices->seed;
7355 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7357 int btrfs_bg_type_to_factor(u64 flags)
7359 const int index = btrfs_bg_flags_to_raid_index(flags);
7361 return btrfs_raid_array[index].ncopies;
7366 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7367 u64 chunk_offset, u64 devid,
7368 u64 physical_offset, u64 physical_len)
7370 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7371 struct extent_map *em;
7372 struct map_lookup *map;
7373 struct btrfs_device *dev;
7379 read_lock(&em_tree->lock);
7380 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7381 read_unlock(&em_tree->lock);
7385 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7386 physical_offset, devid);
7391 map = em->map_lookup;
7392 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7393 if (physical_len != stripe_len) {
7395 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7396 physical_offset, devid, em->start, physical_len,
7402 for (i = 0; i < map->num_stripes; i++) {
7403 if (map->stripes[i].dev->devid == devid &&
7404 map->stripes[i].physical == physical_offset) {
7406 if (map->verified_stripes >= map->num_stripes) {
7408 "too many dev extents for chunk %llu found",
7413 map->verified_stripes++;
7419 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7420 physical_offset, devid);
7424 /* Make sure no dev extent is beyond device bondary */
7425 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7427 btrfs_err(fs_info, "failed to find devid %llu", devid);
7432 /* It's possible this device is a dummy for seed device */
7433 if (dev->disk_total_bytes == 0) {
7434 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7437 btrfs_err(fs_info, "failed to find seed devid %llu",
7444 if (physical_offset + physical_len > dev->disk_total_bytes) {
7446 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7447 devid, physical_offset, physical_len,
7448 dev->disk_total_bytes);
7453 free_extent_map(em);
7457 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7459 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7460 struct extent_map *em;
7461 struct rb_node *node;
7464 read_lock(&em_tree->lock);
7465 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7466 em = rb_entry(node, struct extent_map, rb_node);
7467 if (em->map_lookup->num_stripes !=
7468 em->map_lookup->verified_stripes) {
7470 "chunk %llu has missing dev extent, have %d expect %d",
7471 em->start, em->map_lookup->verified_stripes,
7472 em->map_lookup->num_stripes);
7478 read_unlock(&em_tree->lock);
7483 * Ensure that all dev extents are mapped to correct chunk, otherwise
7484 * later chunk allocation/free would cause unexpected behavior.
7486 * NOTE: This will iterate through the whole device tree, which should be of
7487 * the same size level as the chunk tree. This slightly increases mount time.
7489 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7491 struct btrfs_path *path;
7492 struct btrfs_root *root = fs_info->dev_root;
7493 struct btrfs_key key;
7495 u64 prev_dev_ext_end = 0;
7499 key.type = BTRFS_DEV_EXTENT_KEY;
7502 path = btrfs_alloc_path();
7506 path->reada = READA_FORWARD;
7507 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7511 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7512 ret = btrfs_next_item(root, path);
7515 /* No dev extents at all? Not good */
7522 struct extent_buffer *leaf = path->nodes[0];
7523 struct btrfs_dev_extent *dext;
7524 int slot = path->slots[0];
7526 u64 physical_offset;
7530 btrfs_item_key_to_cpu(leaf, &key, slot);
7531 if (key.type != BTRFS_DEV_EXTENT_KEY)
7533 devid = key.objectid;
7534 physical_offset = key.offset;
7536 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7537 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7538 physical_len = btrfs_dev_extent_length(leaf, dext);
7540 /* Check if this dev extent overlaps with the previous one */
7541 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7543 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7544 devid, physical_offset, prev_dev_ext_end);
7549 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7550 physical_offset, physical_len);
7554 prev_dev_ext_end = physical_offset + physical_len;
7556 ret = btrfs_next_item(root, path);
7565 /* Ensure all chunks have corresponding dev extents */
7566 ret = verify_chunk_dev_extent_mapping(fs_info);
7568 btrfs_free_path(path);
7573 * Check whether the given block group or device is pinned by any inode being
7574 * used as a swapfile.
7576 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7578 struct btrfs_swapfile_pin *sp;
7579 struct rb_node *node;
7581 spin_lock(&fs_info->swapfile_pins_lock);
7582 node = fs_info->swapfile_pins.rb_node;
7584 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7586 node = node->rb_left;
7587 else if (ptr > sp->ptr)
7588 node = node->rb_right;
7592 spin_unlock(&fs_info->swapfile_pins_lock);
7593 return node != NULL;