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>
18 #include "extent_map.h"
20 #include "transaction.h"
21 #include "print-tree.h"
24 #include "async-thread.h"
25 #include "check-integrity.h"
26 #include "rcu-string.h"
28 #include "dev-replace.h"
31 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
32 [BTRFS_RAID_RAID10] = {
35 .devs_max = 0, /* 0 == as many as possible */
37 .tolerated_failures = 1,
41 .raid_name = "raid10",
42 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
43 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
45 [BTRFS_RAID_RAID1] = {
50 .tolerated_failures = 1,
55 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
56 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
63 .tolerated_failures = 0,
68 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
71 [BTRFS_RAID_RAID0] = {
76 .tolerated_failures = 0,
81 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
84 [BTRFS_RAID_SINGLE] = {
89 .tolerated_failures = 0,
93 .raid_name = "single",
97 [BTRFS_RAID_RAID5] = {
102 .tolerated_failures = 1,
106 .raid_name = "raid5",
107 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
108 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
110 [BTRFS_RAID_RAID6] = {
115 .tolerated_failures = 2,
119 .raid_name = "raid6",
120 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
121 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
125 const char *get_raid_name(enum btrfs_raid_types type)
127 if (type >= BTRFS_NR_RAID_TYPES)
130 return btrfs_raid_array[type].raid_name;
134 * Fill @buf with textual description of @bg_flags, no more than @size_buf
135 * bytes including terminating null byte.
137 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
142 u64 flags = bg_flags;
143 u32 size_bp = size_buf;
150 #define DESCRIBE_FLAG(flag, desc) \
152 if (flags & (flag)) { \
153 ret = snprintf(bp, size_bp, "%s|", (desc)); \
154 if (ret < 0 || ret >= size_bp) \
162 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
163 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
164 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
166 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
167 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
168 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
169 btrfs_raid_array[i].raid_name);
173 ret = snprintf(bp, size_bp, "0x%llx|", flags);
177 if (size_bp < size_buf)
178 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
181 * The text is trimmed, it's up to the caller to provide sufficiently
187 static int init_first_rw_device(struct btrfs_trans_handle *trans,
188 struct btrfs_fs_info *fs_info);
189 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
190 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
191 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
192 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
193 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
194 enum btrfs_map_op op,
195 u64 logical, u64 *length,
196 struct btrfs_bio **bbio_ret,
197 int mirror_num, int need_raid_map);
203 * There are several mutexes that protect manipulation of devices and low-level
204 * structures like chunks but not block groups, extents or files
206 * uuid_mutex (global lock)
207 * ------------------------
208 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
209 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
210 * device) or requested by the device= mount option
212 * the mutex can be very coarse and can cover long-running operations
214 * protects: updates to fs_devices counters like missing devices, rw devices,
215 * seeding, structure cloning, opening/closing devices at mount/umount time
217 * global::fs_devs - add, remove, updates to the global list
219 * does not protect: manipulation of the fs_devices::devices list!
221 * btrfs_device::name - renames (write side), read is RCU
223 * fs_devices::device_list_mutex (per-fs, with RCU)
224 * ------------------------------------------------
225 * protects updates to fs_devices::devices, ie. adding and deleting
227 * simple list traversal with read-only actions can be done with RCU protection
229 * may be used to exclude some operations from running concurrently without any
230 * modifications to the list (see write_all_supers)
234 * protects balance structures (status, state) and context accessed from
235 * several places (internally, ioctl)
239 * protects chunks, adding or removing during allocation, trim or when a new
240 * device is added/removed
244 * a big lock that is held by the cleaner thread and prevents running subvolume
245 * cleaning together with relocation or delayed iputs
258 * Exclusive operations, BTRFS_FS_EXCL_OP
259 * ======================================
261 * Maintains the exclusivity of the following operations that apply to the
262 * whole filesystem and cannot run in parallel.
267 * - Device replace (*)
270 * The device operations (as above) can be in one of the following states:
276 * Only device operations marked with (*) can go into the Paused state for the
279 * - ioctl (only Balance can be Paused through ioctl)
280 * - filesystem remounted as read-only
281 * - filesystem unmounted and mounted as read-only
282 * - system power-cycle and filesystem mounted as read-only
283 * - filesystem or device errors leading to forced read-only
285 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
286 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
287 * A device operation in Paused or Running state can be canceled or resumed
288 * either by ioctl (Balance only) or when remounted as read-write.
289 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
293 DEFINE_MUTEX(uuid_mutex);
294 static LIST_HEAD(fs_uuids);
295 struct list_head *btrfs_get_fs_uuids(void)
301 * alloc_fs_devices - allocate struct btrfs_fs_devices
302 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
303 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
305 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
306 * The returned struct is not linked onto any lists and can be destroyed with
307 * kfree() right away.
309 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
310 const u8 *metadata_fsid)
312 struct btrfs_fs_devices *fs_devs;
314 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
316 return ERR_PTR(-ENOMEM);
318 mutex_init(&fs_devs->device_list_mutex);
320 INIT_LIST_HEAD(&fs_devs->devices);
321 INIT_LIST_HEAD(&fs_devs->resized_devices);
322 INIT_LIST_HEAD(&fs_devs->alloc_list);
323 INIT_LIST_HEAD(&fs_devs->fs_list);
325 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
328 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
330 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
335 void btrfs_free_device(struct btrfs_device *device)
337 rcu_string_free(device->name);
338 bio_put(device->flush_bio);
342 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
344 struct btrfs_device *device;
345 WARN_ON(fs_devices->opened);
346 while (!list_empty(&fs_devices->devices)) {
347 device = list_entry(fs_devices->devices.next,
348 struct btrfs_device, dev_list);
349 list_del(&device->dev_list);
350 btrfs_free_device(device);
355 static void btrfs_kobject_uevent(struct block_device *bdev,
356 enum kobject_action action)
360 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
362 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
364 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
365 &disk_to_dev(bdev->bd_disk)->kobj);
368 void __exit btrfs_cleanup_fs_uuids(void)
370 struct btrfs_fs_devices *fs_devices;
372 while (!list_empty(&fs_uuids)) {
373 fs_devices = list_entry(fs_uuids.next,
374 struct btrfs_fs_devices, fs_list);
375 list_del(&fs_devices->fs_list);
376 free_fs_devices(fs_devices);
381 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
382 * Returned struct is not linked onto any lists and must be destroyed using
385 static struct btrfs_device *__alloc_device(void)
387 struct btrfs_device *dev;
389 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
391 return ERR_PTR(-ENOMEM);
394 * Preallocate a bio that's always going to be used for flushing device
395 * barriers and matches the device lifespan
397 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
398 if (!dev->flush_bio) {
400 return ERR_PTR(-ENOMEM);
403 INIT_LIST_HEAD(&dev->dev_list);
404 INIT_LIST_HEAD(&dev->dev_alloc_list);
405 INIT_LIST_HEAD(&dev->resized_list);
407 spin_lock_init(&dev->io_lock);
409 atomic_set(&dev->reada_in_flight, 0);
410 atomic_set(&dev->dev_stats_ccnt, 0);
411 btrfs_device_data_ordered_init(dev);
412 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
413 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
418 static noinline struct btrfs_fs_devices *find_fsid(
419 const u8 *fsid, const u8 *metadata_fsid)
421 struct btrfs_fs_devices *fs_devices;
427 * Handle scanned device having completed its fsid change but
428 * belonging to a fs_devices that was created by first scanning
429 * a device which didn't have its fsid/metadata_uuid changed
430 * at all and the CHANGING_FSID_V2 flag set.
432 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
433 if (fs_devices->fsid_change &&
434 memcmp(metadata_fsid, fs_devices->fsid,
435 BTRFS_FSID_SIZE) == 0 &&
436 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
437 BTRFS_FSID_SIZE) == 0) {
442 * Handle scanned device having completed its fsid change but
443 * belonging to a fs_devices that was created by a device that
444 * has an outdated pair of fsid/metadata_uuid and
445 * CHANGING_FSID_V2 flag set.
447 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
448 if (fs_devices->fsid_change &&
449 memcmp(fs_devices->metadata_uuid,
450 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
451 memcmp(metadata_fsid, fs_devices->metadata_uuid,
452 BTRFS_FSID_SIZE) == 0) {
458 /* Handle non-split brain cases */
459 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
461 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
462 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
463 BTRFS_FSID_SIZE) == 0)
466 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
474 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
475 int flush, struct block_device **bdev,
476 struct buffer_head **bh)
480 *bdev = blkdev_get_by_path(device_path, flags, holder);
483 ret = PTR_ERR(*bdev);
488 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
489 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
491 blkdev_put(*bdev, flags);
494 invalidate_bdev(*bdev);
495 *bh = btrfs_read_dev_super(*bdev);
498 blkdev_put(*bdev, flags);
510 static void requeue_list(struct btrfs_pending_bios *pending_bios,
511 struct bio *head, struct bio *tail)
514 struct bio *old_head;
516 old_head = pending_bios->head;
517 pending_bios->head = head;
518 if (pending_bios->tail)
519 tail->bi_next = old_head;
521 pending_bios->tail = tail;
525 * we try to collect pending bios for a device so we don't get a large
526 * number of procs sending bios down to the same device. This greatly
527 * improves the schedulers ability to collect and merge the bios.
529 * But, it also turns into a long list of bios to process and that is sure
530 * to eventually make the worker thread block. The solution here is to
531 * make some progress and then put this work struct back at the end of
532 * the list if the block device is congested. This way, multiple devices
533 * can make progress from a single worker thread.
535 static noinline void run_scheduled_bios(struct btrfs_device *device)
537 struct btrfs_fs_info *fs_info = device->fs_info;
539 struct backing_dev_info *bdi;
540 struct btrfs_pending_bios *pending_bios;
544 unsigned long num_run;
545 unsigned long batch_run = 0;
546 unsigned long last_waited = 0;
548 int sync_pending = 0;
549 struct blk_plug plug;
552 * this function runs all the bios we've collected for
553 * a particular device. We don't want to wander off to
554 * another device without first sending all of these down.
555 * So, setup a plug here and finish it off before we return
557 blk_start_plug(&plug);
559 bdi = device->bdev->bd_bdi;
562 spin_lock(&device->io_lock);
567 /* take all the bios off the list at once and process them
568 * later on (without the lock held). But, remember the
569 * tail and other pointers so the bios can be properly reinserted
570 * into the list if we hit congestion
572 if (!force_reg && device->pending_sync_bios.head) {
573 pending_bios = &device->pending_sync_bios;
576 pending_bios = &device->pending_bios;
580 pending = pending_bios->head;
581 tail = pending_bios->tail;
582 WARN_ON(pending && !tail);
585 * if pending was null this time around, no bios need processing
586 * at all and we can stop. Otherwise it'll loop back up again
587 * and do an additional check so no bios are missed.
589 * device->running_pending is used to synchronize with the
592 if (device->pending_sync_bios.head == NULL &&
593 device->pending_bios.head == NULL) {
595 device->running_pending = 0;
598 device->running_pending = 1;
601 pending_bios->head = NULL;
602 pending_bios->tail = NULL;
604 spin_unlock(&device->io_lock);
609 /* we want to work on both lists, but do more bios on the
610 * sync list than the regular list
613 pending_bios != &device->pending_sync_bios &&
614 device->pending_sync_bios.head) ||
615 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
616 device->pending_bios.head)) {
617 spin_lock(&device->io_lock);
618 requeue_list(pending_bios, pending, tail);
623 pending = pending->bi_next;
626 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
629 * if we're doing the sync list, record that our
630 * plug has some sync requests on it
632 * If we're doing the regular list and there are
633 * sync requests sitting around, unplug before
636 if (pending_bios == &device->pending_sync_bios) {
638 } else if (sync_pending) {
639 blk_finish_plug(&plug);
640 blk_start_plug(&plug);
644 btrfsic_submit_bio(cur);
651 * we made progress, there is more work to do and the bdi
652 * is now congested. Back off and let other work structs
655 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
656 fs_info->fs_devices->open_devices > 1) {
657 struct io_context *ioc;
659 ioc = current->io_context;
662 * the main goal here is that we don't want to
663 * block if we're going to be able to submit
664 * more requests without blocking.
666 * This code does two great things, it pokes into
667 * the elevator code from a filesystem _and_
668 * it makes assumptions about how batching works.
670 if (ioc && ioc->nr_batch_requests > 0 &&
671 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
673 ioc->last_waited == last_waited)) {
675 * we want to go through our batch of
676 * requests and stop. So, we copy out
677 * the ioc->last_waited time and test
678 * against it before looping
680 last_waited = ioc->last_waited;
684 spin_lock(&device->io_lock);
685 requeue_list(pending_bios, pending, tail);
686 device->running_pending = 1;
688 spin_unlock(&device->io_lock);
689 btrfs_queue_work(fs_info->submit_workers,
699 spin_lock(&device->io_lock);
700 if (device->pending_bios.head || device->pending_sync_bios.head)
702 spin_unlock(&device->io_lock);
705 blk_finish_plug(&plug);
708 static void pending_bios_fn(struct btrfs_work *work)
710 struct btrfs_device *device;
712 device = container_of(work, struct btrfs_device, work);
713 run_scheduled_bios(device);
716 static bool device_path_matched(const char *path, struct btrfs_device *device)
721 found = strcmp(rcu_str_deref(device->name), path);
728 * Search and remove all stale (devices which are not mounted) devices.
729 * When both inputs are NULL, it will search and release all stale devices.
730 * path: Optional. When provided will it release all unmounted devices
731 * matching this path only.
732 * skip_dev: Optional. Will skip this device when searching for the stale
734 * Return: 0 for success or if @path is NULL.
735 * -EBUSY if @path is a mounted device.
736 * -ENOENT if @path does not match any device in the list.
738 static int btrfs_free_stale_devices(const char *path,
739 struct btrfs_device *skip_device)
741 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
742 struct btrfs_device *device, *tmp_device;
748 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
750 mutex_lock(&fs_devices->device_list_mutex);
751 list_for_each_entry_safe(device, tmp_device,
752 &fs_devices->devices, dev_list) {
753 if (skip_device && skip_device == device)
755 if (path && !device->name)
757 if (path && !device_path_matched(path, device))
759 if (fs_devices->opened) {
760 /* for an already deleted device return 0 */
761 if (path && ret != 0)
766 /* delete the stale device */
767 fs_devices->num_devices--;
768 list_del(&device->dev_list);
769 btrfs_free_device(device);
772 if (fs_devices->num_devices == 0)
775 mutex_unlock(&fs_devices->device_list_mutex);
777 if (fs_devices->num_devices == 0) {
778 btrfs_sysfs_remove_fsid(fs_devices);
779 list_del(&fs_devices->fs_list);
780 free_fs_devices(fs_devices);
787 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
788 struct btrfs_device *device, fmode_t flags,
791 struct request_queue *q;
792 struct block_device *bdev;
793 struct buffer_head *bh;
794 struct btrfs_super_block *disk_super;
803 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
808 disk_super = (struct btrfs_super_block *)bh->b_data;
809 devid = btrfs_stack_device_id(&disk_super->dev_item);
810 if (devid != device->devid)
813 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
816 device->generation = btrfs_super_generation(disk_super);
818 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
819 if (btrfs_super_incompat_flags(disk_super) &
820 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
822 "BTRFS: Invalid seeding and uuid-changed device detected\n");
826 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
827 fs_devices->seeding = 1;
829 if (bdev_read_only(bdev))
830 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
832 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
835 q = bdev_get_queue(bdev);
836 if (!blk_queue_nonrot(q))
837 fs_devices->rotating = 1;
840 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
841 device->mode = flags;
843 fs_devices->open_devices++;
844 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
845 device->devid != BTRFS_DEV_REPLACE_DEVID) {
846 fs_devices->rw_devices++;
847 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
855 blkdev_put(bdev, flags);
861 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
862 * being created with a disk that has already completed its fsid change.
864 static struct btrfs_fs_devices *find_fsid_inprogress(
865 struct btrfs_super_block *disk_super)
867 struct btrfs_fs_devices *fs_devices;
869 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
870 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
871 BTRFS_FSID_SIZE) != 0 &&
872 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
873 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
882 static struct btrfs_fs_devices *find_fsid_changed(
883 struct btrfs_super_block *disk_super)
885 struct btrfs_fs_devices *fs_devices;
888 * Handles the case where scanned device is part of an fs that had
889 * multiple successful changes of FSID but curently device didn't
890 * observe it. Meaning our fsid will be different than theirs.
892 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
893 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
894 BTRFS_FSID_SIZE) != 0 &&
895 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
896 BTRFS_FSID_SIZE) == 0 &&
897 memcmp(fs_devices->fsid, disk_super->fsid,
898 BTRFS_FSID_SIZE) != 0) {
906 * Add new device to list of registered devices
909 * device pointer which was just added or updated when successful
910 * error pointer when failed
912 static noinline struct btrfs_device *device_list_add(const char *path,
913 struct btrfs_super_block *disk_super,
914 bool *new_device_added)
916 struct btrfs_device *device;
917 struct btrfs_fs_devices *fs_devices = NULL;
918 struct rcu_string *name;
919 u64 found_transid = btrfs_super_generation(disk_super);
920 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
921 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
922 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
923 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
924 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
926 if (fsid_change_in_progress) {
927 if (!has_metadata_uuid) {
929 * When we have an image which has CHANGING_FSID_V2 set
930 * it might belong to either a filesystem which has
931 * disks with completed fsid change or it might belong
932 * to fs with no UUID changes in effect, handle both.
934 fs_devices = find_fsid_inprogress(disk_super);
936 fs_devices = find_fsid(disk_super->fsid, NULL);
938 fs_devices = find_fsid_changed(disk_super);
940 } else if (has_metadata_uuid) {
941 fs_devices = find_fsid(disk_super->fsid,
942 disk_super->metadata_uuid);
944 fs_devices = find_fsid(disk_super->fsid, NULL);
949 if (has_metadata_uuid)
950 fs_devices = alloc_fs_devices(disk_super->fsid,
951 disk_super->metadata_uuid);
953 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
955 if (IS_ERR(fs_devices))
956 return ERR_CAST(fs_devices);
958 fs_devices->fsid_change = fsid_change_in_progress;
960 mutex_lock(&fs_devices->device_list_mutex);
961 list_add(&fs_devices->fs_list, &fs_uuids);
965 mutex_lock(&fs_devices->device_list_mutex);
966 device = btrfs_find_device(fs_devices, devid,
967 disk_super->dev_item.uuid, NULL, false);
970 * If this disk has been pulled into an fs devices created by
971 * a device which had the CHANGING_FSID_V2 flag then replace the
972 * metadata_uuid/fsid values of the fs_devices.
974 if (has_metadata_uuid && fs_devices->fsid_change &&
975 found_transid > fs_devices->latest_generation) {
976 memcpy(fs_devices->fsid, disk_super->fsid,
978 memcpy(fs_devices->metadata_uuid,
979 disk_super->metadata_uuid, BTRFS_FSID_SIZE);
981 fs_devices->fsid_change = false;
986 if (fs_devices->opened) {
987 mutex_unlock(&fs_devices->device_list_mutex);
988 return ERR_PTR(-EBUSY);
991 device = btrfs_alloc_device(NULL, &devid,
992 disk_super->dev_item.uuid);
993 if (IS_ERR(device)) {
994 mutex_unlock(&fs_devices->device_list_mutex);
995 /* we can safely leave the fs_devices entry around */
999 name = rcu_string_strdup(path, GFP_NOFS);
1001 btrfs_free_device(device);
1002 mutex_unlock(&fs_devices->device_list_mutex);
1003 return ERR_PTR(-ENOMEM);
1005 rcu_assign_pointer(device->name, name);
1007 list_add_rcu(&device->dev_list, &fs_devices->devices);
1008 fs_devices->num_devices++;
1010 device->fs_devices = fs_devices;
1011 *new_device_added = true;
1013 if (disk_super->label[0])
1014 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
1015 disk_super->label, devid, found_transid, path);
1017 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
1018 disk_super->fsid, devid, found_transid, path);
1020 } else if (!device->name || strcmp(device->name->str, path)) {
1022 * When FS is already mounted.
1023 * 1. If you are here and if the device->name is NULL that
1024 * means this device was missing at time of FS mount.
1025 * 2. If you are here and if the device->name is different
1026 * from 'path' that means either
1027 * a. The same device disappeared and reappeared with
1028 * different name. or
1029 * b. The missing-disk-which-was-replaced, has
1032 * We must allow 1 and 2a above. But 2b would be a spurious
1033 * and unintentional.
1035 * Further in case of 1 and 2a above, the disk at 'path'
1036 * would have missed some transaction when it was away and
1037 * in case of 2a the stale bdev has to be updated as well.
1038 * 2b must not be allowed at all time.
1042 * For now, we do allow update to btrfs_fs_device through the
1043 * btrfs dev scan cli after FS has been mounted. We're still
1044 * tracking a problem where systems fail mount by subvolume id
1045 * when we reject replacement on a mounted FS.
1047 if (!fs_devices->opened && found_transid < device->generation) {
1049 * That is if the FS is _not_ mounted and if you
1050 * are here, that means there is more than one
1051 * disk with same uuid and devid.We keep the one
1052 * with larger generation number or the last-in if
1053 * generation are equal.
1055 mutex_unlock(&fs_devices->device_list_mutex);
1056 return ERR_PTR(-EEXIST);
1060 * We are going to replace the device path for a given devid,
1061 * make sure it's the same device if the device is mounted
1064 struct block_device *path_bdev;
1066 path_bdev = lookup_bdev(path);
1067 if (IS_ERR(path_bdev)) {
1068 mutex_unlock(&fs_devices->device_list_mutex);
1069 return ERR_CAST(path_bdev);
1072 if (device->bdev != path_bdev) {
1074 mutex_unlock(&fs_devices->device_list_mutex);
1075 btrfs_warn_in_rcu(device->fs_info,
1076 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
1077 disk_super->fsid, devid,
1078 rcu_str_deref(device->name), path);
1079 return ERR_PTR(-EEXIST);
1082 btrfs_info_in_rcu(device->fs_info,
1083 "device fsid %pU devid %llu moved old:%s new:%s",
1084 disk_super->fsid, devid,
1085 rcu_str_deref(device->name), path);
1088 name = rcu_string_strdup(path, GFP_NOFS);
1090 mutex_unlock(&fs_devices->device_list_mutex);
1091 return ERR_PTR(-ENOMEM);
1093 rcu_string_free(device->name);
1094 rcu_assign_pointer(device->name, name);
1095 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1096 fs_devices->missing_devices--;
1097 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1102 * Unmount does not free the btrfs_device struct but would zero
1103 * generation along with most of the other members. So just update
1104 * it back. We need it to pick the disk with largest generation
1107 if (!fs_devices->opened) {
1108 device->generation = found_transid;
1109 fs_devices->latest_generation = max_t(u64, found_transid,
1110 fs_devices->latest_generation);
1113 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
1115 mutex_unlock(&fs_devices->device_list_mutex);
1119 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1121 struct btrfs_fs_devices *fs_devices;
1122 struct btrfs_device *device;
1123 struct btrfs_device *orig_dev;
1125 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1126 if (IS_ERR(fs_devices))
1129 mutex_lock(&orig->device_list_mutex);
1130 fs_devices->total_devices = orig->total_devices;
1132 /* We have held the volume lock, it is safe to get the devices. */
1133 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1134 struct rcu_string *name;
1136 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1142 * This is ok to do without rcu read locked because we hold the
1143 * uuid mutex so nothing we touch in here is going to disappear.
1145 if (orig_dev->name) {
1146 name = rcu_string_strdup(orig_dev->name->str,
1149 btrfs_free_device(device);
1152 rcu_assign_pointer(device->name, name);
1155 list_add(&device->dev_list, &fs_devices->devices);
1156 device->fs_devices = fs_devices;
1157 fs_devices->num_devices++;
1159 mutex_unlock(&orig->device_list_mutex);
1162 mutex_unlock(&orig->device_list_mutex);
1163 free_fs_devices(fs_devices);
1164 return ERR_PTR(-ENOMEM);
1168 * After we have read the system tree and know devids belonging to
1169 * this filesystem, remove the device which does not belong there.
1171 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1173 struct btrfs_device *device, *next;
1174 struct btrfs_device *latest_dev = NULL;
1176 mutex_lock(&uuid_mutex);
1178 /* This is the initialized path, it is safe to release the devices. */
1179 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1180 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1181 &device->dev_state)) {
1182 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1183 &device->dev_state) &&
1185 device->generation > latest_dev->generation)) {
1186 latest_dev = device;
1191 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1193 * In the first step, keep the device which has
1194 * the correct fsid and the devid that is used
1195 * for the dev_replace procedure.
1196 * In the second step, the dev_replace state is
1197 * read from the device tree and it is known
1198 * whether the procedure is really active or
1199 * not, which means whether this device is
1200 * used or whether it should be removed.
1202 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1203 &device->dev_state)) {
1208 blkdev_put(device->bdev, device->mode);
1209 device->bdev = NULL;
1210 fs_devices->open_devices--;
1212 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1213 list_del_init(&device->dev_alloc_list);
1214 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1215 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1216 &device->dev_state))
1217 fs_devices->rw_devices--;
1219 list_del_init(&device->dev_list);
1220 fs_devices->num_devices--;
1221 btrfs_free_device(device);
1224 if (fs_devices->seed) {
1225 fs_devices = fs_devices->seed;
1229 fs_devices->latest_bdev = latest_dev->bdev;
1231 mutex_unlock(&uuid_mutex);
1234 static void free_device_rcu(struct rcu_head *head)
1236 struct btrfs_device *device;
1238 device = container_of(head, struct btrfs_device, rcu);
1239 btrfs_free_device(device);
1242 static void btrfs_close_bdev(struct btrfs_device *device)
1247 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1248 sync_blockdev(device->bdev);
1249 invalidate_bdev(device->bdev);
1252 blkdev_put(device->bdev, device->mode);
1255 static void btrfs_close_one_device(struct btrfs_device *device)
1257 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1258 struct btrfs_device *new_device;
1259 struct rcu_string *name;
1262 fs_devices->open_devices--;
1264 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1265 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1266 list_del_init(&device->dev_alloc_list);
1267 fs_devices->rw_devices--;
1270 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1271 fs_devices->missing_devices--;
1273 btrfs_close_bdev(device);
1275 new_device = btrfs_alloc_device(NULL, &device->devid,
1277 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1279 /* Safe because we are under uuid_mutex */
1281 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1282 BUG_ON(!name); /* -ENOMEM */
1283 rcu_assign_pointer(new_device->name, name);
1286 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1287 new_device->fs_devices = device->fs_devices;
1289 call_rcu(&device->rcu, free_device_rcu);
1292 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1294 struct btrfs_device *device, *tmp;
1296 if (--fs_devices->opened > 0)
1299 mutex_lock(&fs_devices->device_list_mutex);
1300 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1301 btrfs_close_one_device(device);
1303 mutex_unlock(&fs_devices->device_list_mutex);
1305 WARN_ON(fs_devices->open_devices);
1306 WARN_ON(fs_devices->rw_devices);
1307 fs_devices->opened = 0;
1308 fs_devices->seeding = 0;
1313 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1315 struct btrfs_fs_devices *seed_devices = NULL;
1318 mutex_lock(&uuid_mutex);
1319 ret = close_fs_devices(fs_devices);
1320 if (!fs_devices->opened) {
1321 seed_devices = fs_devices->seed;
1322 fs_devices->seed = NULL;
1324 mutex_unlock(&uuid_mutex);
1326 while (seed_devices) {
1327 fs_devices = seed_devices;
1328 seed_devices = fs_devices->seed;
1329 close_fs_devices(fs_devices);
1330 free_fs_devices(fs_devices);
1335 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1336 fmode_t flags, void *holder)
1338 struct btrfs_device *device;
1339 struct btrfs_device *latest_dev = NULL;
1342 flags |= FMODE_EXCL;
1344 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1345 /* Just open everything we can; ignore failures here */
1346 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1350 device->generation > latest_dev->generation)
1351 latest_dev = device;
1353 if (fs_devices->open_devices == 0) {
1357 fs_devices->opened = 1;
1358 fs_devices->latest_bdev = latest_dev->bdev;
1359 fs_devices->total_rw_bytes = 0;
1364 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1366 struct btrfs_device *dev1, *dev2;
1368 dev1 = list_entry(a, struct btrfs_device, dev_list);
1369 dev2 = list_entry(b, struct btrfs_device, dev_list);
1371 if (dev1->devid < dev2->devid)
1373 else if (dev1->devid > dev2->devid)
1378 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1379 fmode_t flags, void *holder)
1383 lockdep_assert_held(&uuid_mutex);
1385 mutex_lock(&fs_devices->device_list_mutex);
1386 if (fs_devices->opened) {
1387 fs_devices->opened++;
1390 list_sort(NULL, &fs_devices->devices, devid_cmp);
1391 ret = open_fs_devices(fs_devices, flags, holder);
1393 mutex_unlock(&fs_devices->device_list_mutex);
1398 static void btrfs_release_disk_super(struct page *page)
1404 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1406 struct btrfs_super_block **disk_super)
1411 /* make sure our super fits in the device */
1412 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1415 /* make sure our super fits in the page */
1416 if (sizeof(**disk_super) > PAGE_SIZE)
1419 /* make sure our super doesn't straddle pages on disk */
1420 index = bytenr >> PAGE_SHIFT;
1421 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1424 /* pull in the page with our super */
1425 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1428 if (IS_ERR_OR_NULL(*page))
1433 /* align our pointer to the offset of the super block */
1434 *disk_super = p + offset_in_page(bytenr);
1436 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1437 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1438 btrfs_release_disk_super(*page);
1442 if ((*disk_super)->label[0] &&
1443 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1444 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1449 int btrfs_forget_devices(const char *path)
1453 mutex_lock(&uuid_mutex);
1454 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1455 mutex_unlock(&uuid_mutex);
1461 * Look for a btrfs signature on a device. This may be called out of the mount path
1462 * and we are not allowed to call set_blocksize during the scan. The superblock
1463 * is read via pagecache
1465 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1468 struct btrfs_super_block *disk_super;
1469 bool new_device_added = false;
1470 struct btrfs_device *device = NULL;
1471 struct block_device *bdev;
1475 lockdep_assert_held(&uuid_mutex);
1478 * we would like to check all the supers, but that would make
1479 * a btrfs mount succeed after a mkfs from a different FS.
1480 * So, we need to add a special mount option to scan for
1481 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1483 bytenr = btrfs_sb_offset(0);
1484 flags |= FMODE_EXCL;
1486 bdev = blkdev_get_by_path(path, flags, holder);
1488 return ERR_CAST(bdev);
1490 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1491 device = ERR_PTR(-EINVAL);
1492 goto error_bdev_put;
1495 device = device_list_add(path, disk_super, &new_device_added);
1496 if (!IS_ERR(device)) {
1497 if (new_device_added)
1498 btrfs_free_stale_devices(path, device);
1501 btrfs_release_disk_super(page);
1504 blkdev_put(bdev, flags);
1509 static int contains_pending_extent(struct btrfs_transaction *transaction,
1510 struct btrfs_device *device,
1511 u64 *start, u64 len)
1513 struct btrfs_fs_info *fs_info = device->fs_info;
1514 struct extent_map *em;
1515 struct list_head *search_list = &fs_info->pinned_chunks;
1517 u64 physical_start = *start;
1520 search_list = &transaction->pending_chunks;
1522 list_for_each_entry(em, search_list, list) {
1523 struct map_lookup *map;
1526 map = em->map_lookup;
1527 for (i = 0; i < map->num_stripes; i++) {
1530 if (map->stripes[i].dev != device)
1532 if (map->stripes[i].physical >= physical_start + len ||
1533 map->stripes[i].physical + em->orig_block_len <=
1537 * Make sure that while processing the pinned list we do
1538 * not override our *start with a lower value, because
1539 * we can have pinned chunks that fall within this
1540 * device hole and that have lower physical addresses
1541 * than the pending chunks we processed before. If we
1542 * do not take this special care we can end up getting
1543 * 2 pending chunks that start at the same physical
1544 * device offsets because the end offset of a pinned
1545 * chunk can be equal to the start offset of some
1548 end = map->stripes[i].physical + em->orig_block_len;
1555 if (search_list != &fs_info->pinned_chunks) {
1556 search_list = &fs_info->pinned_chunks;
1565 * find_free_dev_extent_start - find free space in the specified device
1566 * @device: the device which we search the free space in
1567 * @num_bytes: the size of the free space that we need
1568 * @search_start: the position from which to begin the search
1569 * @start: store the start of the free space.
1570 * @len: the size of the free space. that we find, or the size
1571 * of the max free space if we don't find suitable free space
1573 * this uses a pretty simple search, the expectation is that it is
1574 * called very infrequently and that a given device has a small number
1577 * @start is used to store the start of the free space if we find. But if we
1578 * don't find suitable free space, it will be used to store the start position
1579 * of the max free space.
1581 * @len is used to store the size of the free space that we find.
1582 * But if we don't find suitable free space, it is used to store the size of
1583 * the max free space.
1585 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1586 struct btrfs_device *device, u64 num_bytes,
1587 u64 search_start, u64 *start, u64 *len)
1589 struct btrfs_fs_info *fs_info = device->fs_info;
1590 struct btrfs_root *root = fs_info->dev_root;
1591 struct btrfs_key key;
1592 struct btrfs_dev_extent *dev_extent;
1593 struct btrfs_path *path;
1598 u64 search_end = device->total_bytes;
1601 struct extent_buffer *l;
1604 * We don't want to overwrite the superblock on the drive nor any area
1605 * used by the boot loader (grub for example), so we make sure to start
1606 * at an offset of at least 1MB.
1608 search_start = max_t(u64, search_start, SZ_1M);
1610 path = btrfs_alloc_path();
1614 max_hole_start = search_start;
1618 if (search_start >= search_end ||
1619 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1624 path->reada = READA_FORWARD;
1625 path->search_commit_root = 1;
1626 path->skip_locking = 1;
1628 key.objectid = device->devid;
1629 key.offset = search_start;
1630 key.type = BTRFS_DEV_EXTENT_KEY;
1632 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1636 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1643 slot = path->slots[0];
1644 if (slot >= btrfs_header_nritems(l)) {
1645 ret = btrfs_next_leaf(root, path);
1653 btrfs_item_key_to_cpu(l, &key, slot);
1655 if (key.objectid < device->devid)
1658 if (key.objectid > device->devid)
1661 if (key.type != BTRFS_DEV_EXTENT_KEY)
1664 if (key.offset > search_start) {
1665 hole_size = key.offset - search_start;
1668 * Have to check before we set max_hole_start, otherwise
1669 * we could end up sending back this offset anyway.
1671 if (contains_pending_extent(transaction, device,
1674 if (key.offset >= search_start) {
1675 hole_size = key.offset - search_start;
1682 if (hole_size > max_hole_size) {
1683 max_hole_start = search_start;
1684 max_hole_size = hole_size;
1688 * If this free space is greater than which we need,
1689 * it must be the max free space that we have found
1690 * until now, so max_hole_start must point to the start
1691 * of this free space and the length of this free space
1692 * is stored in max_hole_size. Thus, we return
1693 * max_hole_start and max_hole_size and go back to the
1696 if (hole_size >= num_bytes) {
1702 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1703 extent_end = key.offset + btrfs_dev_extent_length(l,
1705 if (extent_end > search_start)
1706 search_start = extent_end;
1713 * At this point, search_start should be the end of
1714 * allocated dev extents, and when shrinking the device,
1715 * search_end may be smaller than search_start.
1717 if (search_end > search_start) {
1718 hole_size = search_end - search_start;
1720 if (contains_pending_extent(transaction, device, &search_start,
1722 btrfs_release_path(path);
1726 if (hole_size > max_hole_size) {
1727 max_hole_start = search_start;
1728 max_hole_size = hole_size;
1733 if (max_hole_size < num_bytes)
1739 btrfs_free_path(path);
1740 *start = max_hole_start;
1742 *len = max_hole_size;
1746 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1747 struct btrfs_device *device, u64 num_bytes,
1748 u64 *start, u64 *len)
1750 /* FIXME use last free of some kind */
1751 return find_free_dev_extent_start(trans->transaction, device,
1752 num_bytes, 0, start, len);
1755 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1756 struct btrfs_device *device,
1757 u64 start, u64 *dev_extent_len)
1759 struct btrfs_fs_info *fs_info = device->fs_info;
1760 struct btrfs_root *root = fs_info->dev_root;
1762 struct btrfs_path *path;
1763 struct btrfs_key key;
1764 struct btrfs_key found_key;
1765 struct extent_buffer *leaf = NULL;
1766 struct btrfs_dev_extent *extent = NULL;
1768 path = btrfs_alloc_path();
1772 key.objectid = device->devid;
1774 key.type = BTRFS_DEV_EXTENT_KEY;
1776 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1778 ret = btrfs_previous_item(root, path, key.objectid,
1779 BTRFS_DEV_EXTENT_KEY);
1782 leaf = path->nodes[0];
1783 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1784 extent = btrfs_item_ptr(leaf, path->slots[0],
1785 struct btrfs_dev_extent);
1786 BUG_ON(found_key.offset > start || found_key.offset +
1787 btrfs_dev_extent_length(leaf, extent) < start);
1789 btrfs_release_path(path);
1791 } else if (ret == 0) {
1792 leaf = path->nodes[0];
1793 extent = btrfs_item_ptr(leaf, path->slots[0],
1794 struct btrfs_dev_extent);
1796 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1800 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1802 ret = btrfs_del_item(trans, root, path);
1804 btrfs_handle_fs_error(fs_info, ret,
1805 "Failed to remove dev extent item");
1807 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1810 btrfs_free_path(path);
1814 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1815 struct btrfs_device *device,
1816 u64 chunk_offset, u64 start, u64 num_bytes)
1819 struct btrfs_path *path;
1820 struct btrfs_fs_info *fs_info = device->fs_info;
1821 struct btrfs_root *root = fs_info->dev_root;
1822 struct btrfs_dev_extent *extent;
1823 struct extent_buffer *leaf;
1824 struct btrfs_key key;
1826 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1827 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1828 path = btrfs_alloc_path();
1832 key.objectid = device->devid;
1834 key.type = BTRFS_DEV_EXTENT_KEY;
1835 ret = btrfs_insert_empty_item(trans, root, path, &key,
1840 leaf = path->nodes[0];
1841 extent = btrfs_item_ptr(leaf, path->slots[0],
1842 struct btrfs_dev_extent);
1843 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1844 BTRFS_CHUNK_TREE_OBJECTID);
1845 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1846 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1847 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1849 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1850 btrfs_mark_buffer_dirty(leaf);
1852 btrfs_free_path(path);
1856 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1858 struct extent_map_tree *em_tree;
1859 struct extent_map *em;
1863 em_tree = &fs_info->mapping_tree.map_tree;
1864 read_lock(&em_tree->lock);
1865 n = rb_last(&em_tree->map.rb_root);
1867 em = rb_entry(n, struct extent_map, rb_node);
1868 ret = em->start + em->len;
1870 read_unlock(&em_tree->lock);
1875 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1879 struct btrfs_key key;
1880 struct btrfs_key found_key;
1881 struct btrfs_path *path;
1883 path = btrfs_alloc_path();
1887 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1888 key.type = BTRFS_DEV_ITEM_KEY;
1889 key.offset = (u64)-1;
1891 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1895 BUG_ON(ret == 0); /* Corruption */
1897 ret = btrfs_previous_item(fs_info->chunk_root, path,
1898 BTRFS_DEV_ITEMS_OBJECTID,
1899 BTRFS_DEV_ITEM_KEY);
1903 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1905 *devid_ret = found_key.offset + 1;
1909 btrfs_free_path(path);
1914 * the device information is stored in the chunk root
1915 * the btrfs_device struct should be fully filled in
1917 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1918 struct btrfs_device *device)
1921 struct btrfs_path *path;
1922 struct btrfs_dev_item *dev_item;
1923 struct extent_buffer *leaf;
1924 struct btrfs_key key;
1927 path = btrfs_alloc_path();
1931 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1932 key.type = BTRFS_DEV_ITEM_KEY;
1933 key.offset = device->devid;
1935 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1936 &key, sizeof(*dev_item));
1940 leaf = path->nodes[0];
1941 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1943 btrfs_set_device_id(leaf, dev_item, device->devid);
1944 btrfs_set_device_generation(leaf, dev_item, 0);
1945 btrfs_set_device_type(leaf, dev_item, device->type);
1946 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1947 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1948 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1949 btrfs_set_device_total_bytes(leaf, dev_item,
1950 btrfs_device_get_disk_total_bytes(device));
1951 btrfs_set_device_bytes_used(leaf, dev_item,
1952 btrfs_device_get_bytes_used(device));
1953 btrfs_set_device_group(leaf, dev_item, 0);
1954 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1955 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1956 btrfs_set_device_start_offset(leaf, dev_item, 0);
1958 ptr = btrfs_device_uuid(dev_item);
1959 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1960 ptr = btrfs_device_fsid(dev_item);
1961 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1962 ptr, BTRFS_FSID_SIZE);
1963 btrfs_mark_buffer_dirty(leaf);
1967 btrfs_free_path(path);
1972 * Function to update ctime/mtime for a given device path.
1973 * Mainly used for ctime/mtime based probe like libblkid.
1975 static void update_dev_time(const char *path_name)
1979 filp = filp_open(path_name, O_RDWR, 0);
1982 file_update_time(filp);
1983 filp_close(filp, NULL);
1986 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1987 struct btrfs_device *device)
1989 struct btrfs_root *root = fs_info->chunk_root;
1991 struct btrfs_path *path;
1992 struct btrfs_key key;
1993 struct btrfs_trans_handle *trans;
1995 path = btrfs_alloc_path();
1999 trans = btrfs_start_transaction(root, 0);
2000 if (IS_ERR(trans)) {
2001 btrfs_free_path(path);
2002 return PTR_ERR(trans);
2004 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2005 key.type = BTRFS_DEV_ITEM_KEY;
2006 key.offset = device->devid;
2008 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2012 btrfs_abort_transaction(trans, ret);
2013 btrfs_end_transaction(trans);
2017 ret = btrfs_del_item(trans, root, path);
2019 btrfs_abort_transaction(trans, ret);
2020 btrfs_end_transaction(trans);
2024 btrfs_free_path(path);
2026 ret = btrfs_commit_transaction(trans);
2031 * Verify that @num_devices satisfies the RAID profile constraints in the whole
2032 * filesystem. It's up to the caller to adjust that number regarding eg. device
2035 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
2043 seq = read_seqbegin(&fs_info->profiles_lock);
2045 all_avail = fs_info->avail_data_alloc_bits |
2046 fs_info->avail_system_alloc_bits |
2047 fs_info->avail_metadata_alloc_bits;
2048 } while (read_seqretry(&fs_info->profiles_lock, seq));
2050 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2051 if (!(all_avail & btrfs_raid_array[i].bg_flag))
2054 if (num_devices < btrfs_raid_array[i].devs_min) {
2055 int ret = btrfs_raid_array[i].mindev_error;
2065 static struct btrfs_device * btrfs_find_next_active_device(
2066 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2068 struct btrfs_device *next_device;
2070 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2071 if (next_device != device &&
2072 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2073 && next_device->bdev)
2081 * Helper function to check if the given device is part of s_bdev / latest_bdev
2082 * and replace it with the provided or the next active device, in the context
2083 * where this function called, there should be always be another device (or
2084 * this_dev) which is active.
2086 void btrfs_assign_next_active_device(struct btrfs_device *device,
2087 struct btrfs_device *this_dev)
2089 struct btrfs_fs_info *fs_info = device->fs_info;
2090 struct btrfs_device *next_device;
2093 next_device = this_dev;
2095 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2097 ASSERT(next_device);
2099 if (fs_info->sb->s_bdev &&
2100 (fs_info->sb->s_bdev == device->bdev))
2101 fs_info->sb->s_bdev = next_device->bdev;
2103 if (fs_info->fs_devices->latest_bdev == device->bdev)
2104 fs_info->fs_devices->latest_bdev = next_device->bdev;
2108 * Return btrfs_fs_devices::num_devices excluding the device that's being
2109 * currently replaced.
2111 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2113 u64 num_devices = fs_info->fs_devices->num_devices;
2115 down_read(&fs_info->dev_replace.rwsem);
2116 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2117 ASSERT(num_devices > 1);
2120 up_read(&fs_info->dev_replace.rwsem);
2125 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2128 struct btrfs_device *device;
2129 struct btrfs_fs_devices *cur_devices;
2130 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2134 mutex_lock(&uuid_mutex);
2136 num_devices = btrfs_num_devices(fs_info);
2138 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2142 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2144 if (IS_ERR(device)) {
2145 if (PTR_ERR(device) == -ENOENT &&
2146 strcmp(device_path, "missing") == 0)
2147 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2149 ret = PTR_ERR(device);
2153 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2154 btrfs_warn_in_rcu(fs_info,
2155 "cannot remove device %s (devid %llu) due to active swapfile",
2156 rcu_str_deref(device->name), device->devid);
2161 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2162 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2166 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2167 fs_info->fs_devices->rw_devices == 1) {
2168 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2172 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2173 mutex_lock(&fs_info->chunk_mutex);
2174 list_del_init(&device->dev_alloc_list);
2175 device->fs_devices->rw_devices--;
2176 mutex_unlock(&fs_info->chunk_mutex);
2179 mutex_unlock(&uuid_mutex);
2180 ret = btrfs_shrink_device(device, 0);
2181 mutex_lock(&uuid_mutex);
2186 * TODO: the superblock still includes this device in its num_devices
2187 * counter although write_all_supers() is not locked out. This
2188 * could give a filesystem state which requires a degraded mount.
2190 ret = btrfs_rm_dev_item(fs_info, device);
2194 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2195 btrfs_scrub_cancel_dev(fs_info, device);
2198 * the device list mutex makes sure that we don't change
2199 * the device list while someone else is writing out all
2200 * the device supers. Whoever is writing all supers, should
2201 * lock the device list mutex before getting the number of
2202 * devices in the super block (super_copy). Conversely,
2203 * whoever updates the number of devices in the super block
2204 * (super_copy) should hold the device list mutex.
2208 * In normal cases the cur_devices == fs_devices. But in case
2209 * of deleting a seed device, the cur_devices should point to
2210 * its own fs_devices listed under the fs_devices->seed.
2212 cur_devices = device->fs_devices;
2213 mutex_lock(&fs_devices->device_list_mutex);
2214 list_del_rcu(&device->dev_list);
2216 cur_devices->num_devices--;
2217 cur_devices->total_devices--;
2218 /* Update total_devices of the parent fs_devices if it's seed */
2219 if (cur_devices != fs_devices)
2220 fs_devices->total_devices--;
2222 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2223 cur_devices->missing_devices--;
2225 btrfs_assign_next_active_device(device, NULL);
2228 cur_devices->open_devices--;
2229 /* remove sysfs entry */
2230 btrfs_sysfs_rm_device_link(fs_devices, device);
2233 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2234 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2235 mutex_unlock(&fs_devices->device_list_mutex);
2238 * at this point, the device is zero sized and detached from
2239 * the devices list. All that's left is to zero out the old
2240 * supers and free the device.
2242 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2243 btrfs_scratch_superblocks(device->bdev, device->name->str);
2245 btrfs_close_bdev(device);
2246 call_rcu(&device->rcu, free_device_rcu);
2248 if (cur_devices->open_devices == 0) {
2249 while (fs_devices) {
2250 if (fs_devices->seed == cur_devices) {
2251 fs_devices->seed = cur_devices->seed;
2254 fs_devices = fs_devices->seed;
2256 cur_devices->seed = NULL;
2257 close_fs_devices(cur_devices);
2258 free_fs_devices(cur_devices);
2262 mutex_unlock(&uuid_mutex);
2266 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2267 mutex_lock(&fs_info->chunk_mutex);
2268 list_add(&device->dev_alloc_list,
2269 &fs_devices->alloc_list);
2270 device->fs_devices->rw_devices++;
2271 mutex_unlock(&fs_info->chunk_mutex);
2276 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2278 struct btrfs_fs_devices *fs_devices;
2280 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2283 * in case of fs with no seed, srcdev->fs_devices will point
2284 * to fs_devices of fs_info. However when the dev being replaced is
2285 * a seed dev it will point to the seed's local fs_devices. In short
2286 * srcdev will have its correct fs_devices in both the cases.
2288 fs_devices = srcdev->fs_devices;
2290 list_del_rcu(&srcdev->dev_list);
2291 list_del(&srcdev->dev_alloc_list);
2292 fs_devices->num_devices--;
2293 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2294 fs_devices->missing_devices--;
2296 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2297 fs_devices->rw_devices--;
2300 fs_devices->open_devices--;
2303 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2304 struct btrfs_device *srcdev)
2306 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2308 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2309 /* zero out the old super if it is writable */
2310 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2313 btrfs_close_bdev(srcdev);
2314 call_rcu(&srcdev->rcu, free_device_rcu);
2316 /* if this is no devs we rather delete the fs_devices */
2317 if (!fs_devices->num_devices) {
2318 struct btrfs_fs_devices *tmp_fs_devices;
2321 * On a mounted FS, num_devices can't be zero unless it's a
2322 * seed. In case of a seed device being replaced, the replace
2323 * target added to the sprout FS, so there will be no more
2324 * device left under the seed FS.
2326 ASSERT(fs_devices->seeding);
2328 tmp_fs_devices = fs_info->fs_devices;
2329 while (tmp_fs_devices) {
2330 if (tmp_fs_devices->seed == fs_devices) {
2331 tmp_fs_devices->seed = fs_devices->seed;
2334 tmp_fs_devices = tmp_fs_devices->seed;
2336 fs_devices->seed = NULL;
2337 close_fs_devices(fs_devices);
2338 free_fs_devices(fs_devices);
2342 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2344 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2347 mutex_lock(&fs_devices->device_list_mutex);
2349 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2352 fs_devices->open_devices--;
2354 fs_devices->num_devices--;
2356 btrfs_assign_next_active_device(tgtdev, NULL);
2358 list_del_rcu(&tgtdev->dev_list);
2360 mutex_unlock(&fs_devices->device_list_mutex);
2363 * The update_dev_time() with in btrfs_scratch_superblocks()
2364 * may lead to a call to btrfs_show_devname() which will try
2365 * to hold device_list_mutex. And here this device
2366 * is already out of device list, so we don't have to hold
2367 * the device_list_mutex lock.
2369 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2371 btrfs_close_bdev(tgtdev);
2372 call_rcu(&tgtdev->rcu, free_device_rcu);
2375 static struct btrfs_device *btrfs_find_device_by_path(
2376 struct btrfs_fs_info *fs_info, const char *device_path)
2379 struct btrfs_super_block *disk_super;
2382 struct block_device *bdev;
2383 struct buffer_head *bh;
2384 struct btrfs_device *device;
2386 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2387 fs_info->bdev_holder, 0, &bdev, &bh);
2389 return ERR_PTR(ret);
2390 disk_super = (struct btrfs_super_block *)bh->b_data;
2391 devid = btrfs_stack_device_id(&disk_super->dev_item);
2392 dev_uuid = disk_super->dev_item.uuid;
2393 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2394 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2395 disk_super->metadata_uuid, true);
2397 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2398 disk_super->fsid, true);
2402 device = ERR_PTR(-ENOENT);
2403 blkdev_put(bdev, FMODE_READ);
2408 * Lookup a device given by device id, or the path if the id is 0.
2410 struct btrfs_device *btrfs_find_device_by_devspec(
2411 struct btrfs_fs_info *fs_info, u64 devid,
2412 const char *device_path)
2414 struct btrfs_device *device;
2417 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2420 return ERR_PTR(-ENOENT);
2424 if (!device_path || !device_path[0])
2425 return ERR_PTR(-EINVAL);
2427 if (strcmp(device_path, "missing") == 0) {
2428 /* Find first missing device */
2429 list_for_each_entry(device, &fs_info->fs_devices->devices,
2431 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2432 &device->dev_state) && !device->bdev)
2435 return ERR_PTR(-ENOENT);
2438 return btrfs_find_device_by_path(fs_info, device_path);
2442 * does all the dirty work required for changing file system's UUID.
2444 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2446 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2447 struct btrfs_fs_devices *old_devices;
2448 struct btrfs_fs_devices *seed_devices;
2449 struct btrfs_super_block *disk_super = fs_info->super_copy;
2450 struct btrfs_device *device;
2453 lockdep_assert_held(&uuid_mutex);
2454 if (!fs_devices->seeding)
2457 seed_devices = alloc_fs_devices(NULL, NULL);
2458 if (IS_ERR(seed_devices))
2459 return PTR_ERR(seed_devices);
2461 old_devices = clone_fs_devices(fs_devices);
2462 if (IS_ERR(old_devices)) {
2463 kfree(seed_devices);
2464 return PTR_ERR(old_devices);
2467 list_add(&old_devices->fs_list, &fs_uuids);
2469 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2470 seed_devices->opened = 1;
2471 INIT_LIST_HEAD(&seed_devices->devices);
2472 INIT_LIST_HEAD(&seed_devices->alloc_list);
2473 mutex_init(&seed_devices->device_list_mutex);
2475 mutex_lock(&fs_devices->device_list_mutex);
2476 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2478 list_for_each_entry(device, &seed_devices->devices, dev_list)
2479 device->fs_devices = seed_devices;
2481 mutex_lock(&fs_info->chunk_mutex);
2482 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2483 mutex_unlock(&fs_info->chunk_mutex);
2485 fs_devices->seeding = 0;
2486 fs_devices->num_devices = 0;
2487 fs_devices->open_devices = 0;
2488 fs_devices->missing_devices = 0;
2489 fs_devices->rotating = 0;
2490 fs_devices->seed = seed_devices;
2492 generate_random_uuid(fs_devices->fsid);
2493 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2494 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2495 mutex_unlock(&fs_devices->device_list_mutex);
2497 super_flags = btrfs_super_flags(disk_super) &
2498 ~BTRFS_SUPER_FLAG_SEEDING;
2499 btrfs_set_super_flags(disk_super, super_flags);
2505 * Store the expected generation for seed devices in device items.
2507 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2508 struct btrfs_fs_info *fs_info)
2510 struct btrfs_root *root = fs_info->chunk_root;
2511 struct btrfs_path *path;
2512 struct extent_buffer *leaf;
2513 struct btrfs_dev_item *dev_item;
2514 struct btrfs_device *device;
2515 struct btrfs_key key;
2516 u8 fs_uuid[BTRFS_FSID_SIZE];
2517 u8 dev_uuid[BTRFS_UUID_SIZE];
2521 path = btrfs_alloc_path();
2525 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2527 key.type = BTRFS_DEV_ITEM_KEY;
2530 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2534 leaf = path->nodes[0];
2536 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2537 ret = btrfs_next_leaf(root, path);
2542 leaf = path->nodes[0];
2543 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2544 btrfs_release_path(path);
2548 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2549 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2550 key.type != BTRFS_DEV_ITEM_KEY)
2553 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2554 struct btrfs_dev_item);
2555 devid = btrfs_device_id(leaf, dev_item);
2556 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2558 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2560 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2562 BUG_ON(!device); /* Logic error */
2564 if (device->fs_devices->seeding) {
2565 btrfs_set_device_generation(leaf, dev_item,
2566 device->generation);
2567 btrfs_mark_buffer_dirty(leaf);
2575 btrfs_free_path(path);
2579 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2581 struct btrfs_root *root = fs_info->dev_root;
2582 struct request_queue *q;
2583 struct btrfs_trans_handle *trans;
2584 struct btrfs_device *device;
2585 struct block_device *bdev;
2586 struct super_block *sb = fs_info->sb;
2587 struct rcu_string *name;
2588 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2589 u64 orig_super_total_bytes;
2590 u64 orig_super_num_devices;
2591 int seeding_dev = 0;
2593 bool unlocked = false;
2595 if (sb_rdonly(sb) && !fs_devices->seeding)
2598 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2599 fs_info->bdev_holder);
2601 return PTR_ERR(bdev);
2603 if (fs_devices->seeding) {
2605 down_write(&sb->s_umount);
2606 mutex_lock(&uuid_mutex);
2609 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2611 mutex_lock(&fs_devices->device_list_mutex);
2612 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2613 if (device->bdev == bdev) {
2616 &fs_devices->device_list_mutex);
2620 mutex_unlock(&fs_devices->device_list_mutex);
2622 device = btrfs_alloc_device(fs_info, NULL, NULL);
2623 if (IS_ERR(device)) {
2624 /* we can safely leave the fs_devices entry around */
2625 ret = PTR_ERR(device);
2629 name = rcu_string_strdup(device_path, GFP_KERNEL);
2632 goto error_free_device;
2634 rcu_assign_pointer(device->name, name);
2636 trans = btrfs_start_transaction(root, 0);
2637 if (IS_ERR(trans)) {
2638 ret = PTR_ERR(trans);
2639 goto error_free_device;
2642 q = bdev_get_queue(bdev);
2643 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2644 device->generation = trans->transid;
2645 device->io_width = fs_info->sectorsize;
2646 device->io_align = fs_info->sectorsize;
2647 device->sector_size = fs_info->sectorsize;
2648 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2649 fs_info->sectorsize);
2650 device->disk_total_bytes = device->total_bytes;
2651 device->commit_total_bytes = device->total_bytes;
2652 device->fs_info = fs_info;
2653 device->bdev = bdev;
2654 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2655 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2656 device->mode = FMODE_EXCL;
2657 device->dev_stats_valid = 1;
2658 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2661 sb->s_flags &= ~SB_RDONLY;
2662 ret = btrfs_prepare_sprout(fs_info);
2664 btrfs_abort_transaction(trans, ret);
2669 device->fs_devices = fs_devices;
2671 mutex_lock(&fs_devices->device_list_mutex);
2672 mutex_lock(&fs_info->chunk_mutex);
2673 list_add_rcu(&device->dev_list, &fs_devices->devices);
2674 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2675 fs_devices->num_devices++;
2676 fs_devices->open_devices++;
2677 fs_devices->rw_devices++;
2678 fs_devices->total_devices++;
2679 fs_devices->total_rw_bytes += device->total_bytes;
2681 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2683 if (!blk_queue_nonrot(q))
2684 fs_devices->rotating = 1;
2686 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2687 btrfs_set_super_total_bytes(fs_info->super_copy,
2688 round_down(orig_super_total_bytes + device->total_bytes,
2689 fs_info->sectorsize));
2691 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2692 btrfs_set_super_num_devices(fs_info->super_copy,
2693 orig_super_num_devices + 1);
2695 /* add sysfs device entry */
2696 btrfs_sysfs_add_device_link(fs_devices, device);
2699 * we've got more storage, clear any full flags on the space
2702 btrfs_clear_space_info_full(fs_info);
2704 mutex_unlock(&fs_info->chunk_mutex);
2705 mutex_unlock(&fs_devices->device_list_mutex);
2708 mutex_lock(&fs_info->chunk_mutex);
2709 ret = init_first_rw_device(trans, fs_info);
2710 mutex_unlock(&fs_info->chunk_mutex);
2712 btrfs_abort_transaction(trans, ret);
2717 ret = btrfs_add_dev_item(trans, device);
2719 btrfs_abort_transaction(trans, ret);
2724 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2726 ret = btrfs_finish_sprout(trans, fs_info);
2728 btrfs_abort_transaction(trans, ret);
2732 /* Sprouting would change fsid of the mounted root,
2733 * so rename the fsid on the sysfs
2735 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2736 fs_info->fs_devices->fsid);
2737 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2739 "sysfs: failed to create fsid for sprout");
2742 ret = btrfs_commit_transaction(trans);
2745 mutex_unlock(&uuid_mutex);
2746 up_write(&sb->s_umount);
2749 if (ret) /* transaction commit */
2752 ret = btrfs_relocate_sys_chunks(fs_info);
2754 btrfs_handle_fs_error(fs_info, ret,
2755 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2756 trans = btrfs_attach_transaction(root);
2757 if (IS_ERR(trans)) {
2758 if (PTR_ERR(trans) == -ENOENT)
2760 ret = PTR_ERR(trans);
2764 ret = btrfs_commit_transaction(trans);
2767 /* Update ctime/mtime for libblkid */
2768 update_dev_time(device_path);
2772 btrfs_sysfs_rm_device_link(fs_devices, device);
2773 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2774 mutex_lock(&fs_info->chunk_mutex);
2775 list_del_rcu(&device->dev_list);
2776 list_del(&device->dev_alloc_list);
2777 fs_info->fs_devices->num_devices--;
2778 fs_info->fs_devices->open_devices--;
2779 fs_info->fs_devices->rw_devices--;
2780 fs_info->fs_devices->total_devices--;
2781 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2782 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2783 btrfs_set_super_total_bytes(fs_info->super_copy,
2784 orig_super_total_bytes);
2785 btrfs_set_super_num_devices(fs_info->super_copy,
2786 orig_super_num_devices);
2787 mutex_unlock(&fs_info->chunk_mutex);
2788 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2791 sb->s_flags |= SB_RDONLY;
2793 btrfs_end_transaction(trans);
2795 btrfs_free_device(device);
2797 blkdev_put(bdev, FMODE_EXCL);
2798 if (seeding_dev && !unlocked) {
2799 mutex_unlock(&uuid_mutex);
2800 up_write(&sb->s_umount);
2805 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2806 struct btrfs_device *device)
2809 struct btrfs_path *path;
2810 struct btrfs_root *root = device->fs_info->chunk_root;
2811 struct btrfs_dev_item *dev_item;
2812 struct extent_buffer *leaf;
2813 struct btrfs_key key;
2815 path = btrfs_alloc_path();
2819 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2820 key.type = BTRFS_DEV_ITEM_KEY;
2821 key.offset = device->devid;
2823 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2832 leaf = path->nodes[0];
2833 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2835 btrfs_set_device_id(leaf, dev_item, device->devid);
2836 btrfs_set_device_type(leaf, dev_item, device->type);
2837 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2838 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2839 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2840 btrfs_set_device_total_bytes(leaf, dev_item,
2841 btrfs_device_get_disk_total_bytes(device));
2842 btrfs_set_device_bytes_used(leaf, dev_item,
2843 btrfs_device_get_bytes_used(device));
2844 btrfs_mark_buffer_dirty(leaf);
2847 btrfs_free_path(path);
2851 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2852 struct btrfs_device *device, u64 new_size)
2854 struct btrfs_fs_info *fs_info = device->fs_info;
2855 struct btrfs_super_block *super_copy = fs_info->super_copy;
2856 struct btrfs_fs_devices *fs_devices;
2860 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2863 new_size = round_down(new_size, fs_info->sectorsize);
2865 mutex_lock(&fs_info->chunk_mutex);
2866 old_total = btrfs_super_total_bytes(super_copy);
2867 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2869 if (new_size <= device->total_bytes ||
2870 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2871 mutex_unlock(&fs_info->chunk_mutex);
2875 fs_devices = fs_info->fs_devices;
2877 btrfs_set_super_total_bytes(super_copy,
2878 round_down(old_total + diff, fs_info->sectorsize));
2879 device->fs_devices->total_rw_bytes += diff;
2881 btrfs_device_set_total_bytes(device, new_size);
2882 btrfs_device_set_disk_total_bytes(device, new_size);
2883 btrfs_clear_space_info_full(device->fs_info);
2884 if (list_empty(&device->resized_list))
2885 list_add_tail(&device->resized_list,
2886 &fs_devices->resized_devices);
2887 mutex_unlock(&fs_info->chunk_mutex);
2889 return btrfs_update_device(trans, device);
2892 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2894 struct btrfs_fs_info *fs_info = trans->fs_info;
2895 struct btrfs_root *root = fs_info->chunk_root;
2897 struct btrfs_path *path;
2898 struct btrfs_key key;
2900 path = btrfs_alloc_path();
2904 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2905 key.offset = chunk_offset;
2906 key.type = BTRFS_CHUNK_ITEM_KEY;
2908 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2911 else if (ret > 0) { /* Logic error or corruption */
2912 btrfs_handle_fs_error(fs_info, -ENOENT,
2913 "Failed lookup while freeing chunk.");
2918 ret = btrfs_del_item(trans, root, path);
2920 btrfs_handle_fs_error(fs_info, ret,
2921 "Failed to delete chunk item.");
2923 btrfs_free_path(path);
2927 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2929 struct btrfs_super_block *super_copy = fs_info->super_copy;
2930 struct btrfs_disk_key *disk_key;
2931 struct btrfs_chunk *chunk;
2938 struct btrfs_key key;
2940 mutex_lock(&fs_info->chunk_mutex);
2941 array_size = btrfs_super_sys_array_size(super_copy);
2943 ptr = super_copy->sys_chunk_array;
2946 while (cur < array_size) {
2947 disk_key = (struct btrfs_disk_key *)ptr;
2948 btrfs_disk_key_to_cpu(&key, disk_key);
2950 len = sizeof(*disk_key);
2952 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2953 chunk = (struct btrfs_chunk *)(ptr + len);
2954 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2955 len += btrfs_chunk_item_size(num_stripes);
2960 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2961 key.offset == chunk_offset) {
2962 memmove(ptr, ptr + len, array_size - (cur + len));
2964 btrfs_set_super_sys_array_size(super_copy, array_size);
2970 mutex_unlock(&fs_info->chunk_mutex);
2975 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2976 * @logical: Logical block offset in bytes.
2977 * @length: Length of extent in bytes.
2979 * Return: Chunk mapping or ERR_PTR.
2981 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2982 u64 logical, u64 length)
2984 struct extent_map_tree *em_tree;
2985 struct extent_map *em;
2987 em_tree = &fs_info->mapping_tree.map_tree;
2988 read_lock(&em_tree->lock);
2989 em = lookup_extent_mapping(em_tree, logical, length);
2990 read_unlock(&em_tree->lock);
2993 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2995 return ERR_PTR(-EINVAL);
2998 if (em->start > logical || em->start + em->len < logical) {
3000 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
3001 logical, length, em->start, em->start + em->len);
3002 free_extent_map(em);
3003 return ERR_PTR(-EINVAL);
3006 /* callers are responsible for dropping em's ref. */
3010 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3012 struct btrfs_fs_info *fs_info = trans->fs_info;
3013 struct extent_map *em;
3014 struct map_lookup *map;
3015 u64 dev_extent_len = 0;
3017 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3019 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3022 * This is a logic error, but we don't want to just rely on the
3023 * user having built with ASSERT enabled, so if ASSERT doesn't
3024 * do anything we still error out.
3029 map = em->map_lookup;
3030 mutex_lock(&fs_info->chunk_mutex);
3031 check_system_chunk(trans, map->type);
3032 mutex_unlock(&fs_info->chunk_mutex);
3035 * Take the device list mutex to prevent races with the final phase of
3036 * a device replace operation that replaces the device object associated
3037 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
3039 mutex_lock(&fs_devices->device_list_mutex);
3040 for (i = 0; i < map->num_stripes; i++) {
3041 struct btrfs_device *device = map->stripes[i].dev;
3042 ret = btrfs_free_dev_extent(trans, device,
3043 map->stripes[i].physical,
3046 mutex_unlock(&fs_devices->device_list_mutex);
3047 btrfs_abort_transaction(trans, ret);
3051 if (device->bytes_used > 0) {
3052 mutex_lock(&fs_info->chunk_mutex);
3053 btrfs_device_set_bytes_used(device,
3054 device->bytes_used - dev_extent_len);
3055 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3056 btrfs_clear_space_info_full(fs_info);
3057 mutex_unlock(&fs_info->chunk_mutex);
3060 ret = btrfs_update_device(trans, device);
3062 mutex_unlock(&fs_devices->device_list_mutex);
3063 btrfs_abort_transaction(trans, ret);
3067 mutex_unlock(&fs_devices->device_list_mutex);
3069 ret = btrfs_free_chunk(trans, chunk_offset);
3071 btrfs_abort_transaction(trans, ret);
3075 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3077 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3078 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3080 btrfs_abort_transaction(trans, ret);
3085 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3087 btrfs_abort_transaction(trans, ret);
3093 free_extent_map(em);
3097 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3099 struct btrfs_root *root = fs_info->chunk_root;
3100 struct btrfs_trans_handle *trans;
3104 * Prevent races with automatic removal of unused block groups.
3105 * After we relocate and before we remove the chunk with offset
3106 * chunk_offset, automatic removal of the block group can kick in,
3107 * resulting in a failure when calling btrfs_remove_chunk() below.
3109 * Make sure to acquire this mutex before doing a tree search (dev
3110 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3111 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3112 * we release the path used to search the chunk/dev tree and before
3113 * the current task acquires this mutex and calls us.
3115 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3117 ret = btrfs_can_relocate(fs_info, chunk_offset);
3121 /* step one, relocate all the extents inside this chunk */
3122 btrfs_scrub_pause(fs_info);
3123 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3124 btrfs_scrub_continue(fs_info);
3129 * We add the kobjects here (and after forcing data chunk creation)
3130 * since relocation is the only place we'll create chunks of a new
3131 * type at runtime. The only place where we'll remove the last
3132 * chunk of a type is the call immediately below this one. Even
3133 * so, we're protected against races with the cleaner thread since
3134 * we're covered by the delete_unused_bgs_mutex.
3136 btrfs_add_raid_kobjects(fs_info);
3138 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3140 if (IS_ERR(trans)) {
3141 ret = PTR_ERR(trans);
3142 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3147 * step two, delete the device extents and the
3148 * chunk tree entries
3150 ret = btrfs_remove_chunk(trans, chunk_offset);
3151 btrfs_end_transaction(trans);
3155 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3157 struct btrfs_root *chunk_root = fs_info->chunk_root;
3158 struct btrfs_path *path;
3159 struct extent_buffer *leaf;
3160 struct btrfs_chunk *chunk;
3161 struct btrfs_key key;
3162 struct btrfs_key found_key;
3164 bool retried = false;
3168 path = btrfs_alloc_path();
3173 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3174 key.offset = (u64)-1;
3175 key.type = BTRFS_CHUNK_ITEM_KEY;
3178 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3179 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3181 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3184 BUG_ON(ret == 0); /* Corruption */
3186 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3189 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3195 leaf = path->nodes[0];
3196 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3198 chunk = btrfs_item_ptr(leaf, path->slots[0],
3199 struct btrfs_chunk);
3200 chunk_type = btrfs_chunk_type(leaf, chunk);
3201 btrfs_release_path(path);
3203 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3204 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3210 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3212 if (found_key.offset == 0)
3214 key.offset = found_key.offset - 1;
3217 if (failed && !retried) {
3221 } else if (WARN_ON(failed && retried)) {
3225 btrfs_free_path(path);
3230 * return 1 : allocate a data chunk successfully,
3231 * return <0: errors during allocating a data chunk,
3232 * return 0 : no need to allocate a data chunk.
3234 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3237 struct btrfs_block_group_cache *cache;
3241 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3243 chunk_type = cache->flags;
3244 btrfs_put_block_group(cache);
3246 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3247 spin_lock(&fs_info->data_sinfo->lock);
3248 bytes_used = fs_info->data_sinfo->bytes_used;
3249 spin_unlock(&fs_info->data_sinfo->lock);
3252 struct btrfs_trans_handle *trans;
3255 trans = btrfs_join_transaction(fs_info->tree_root);
3257 return PTR_ERR(trans);
3259 ret = btrfs_force_chunk_alloc(trans,
3260 BTRFS_BLOCK_GROUP_DATA);
3261 btrfs_end_transaction(trans);
3265 btrfs_add_raid_kobjects(fs_info);
3273 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3274 struct btrfs_balance_control *bctl)
3276 struct btrfs_root *root = fs_info->tree_root;
3277 struct btrfs_trans_handle *trans;
3278 struct btrfs_balance_item *item;
3279 struct btrfs_disk_balance_args disk_bargs;
3280 struct btrfs_path *path;
3281 struct extent_buffer *leaf;
3282 struct btrfs_key key;
3285 path = btrfs_alloc_path();
3289 trans = btrfs_start_transaction(root, 0);
3290 if (IS_ERR(trans)) {
3291 btrfs_free_path(path);
3292 return PTR_ERR(trans);
3295 key.objectid = BTRFS_BALANCE_OBJECTID;
3296 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3299 ret = btrfs_insert_empty_item(trans, root, path, &key,
3304 leaf = path->nodes[0];
3305 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3307 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3309 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3310 btrfs_set_balance_data(leaf, item, &disk_bargs);
3311 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3312 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3313 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3314 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3316 btrfs_set_balance_flags(leaf, item, bctl->flags);
3318 btrfs_mark_buffer_dirty(leaf);
3320 btrfs_free_path(path);
3321 err = btrfs_commit_transaction(trans);
3327 static int del_balance_item(struct btrfs_fs_info *fs_info)
3329 struct btrfs_root *root = fs_info->tree_root;
3330 struct btrfs_trans_handle *trans;
3331 struct btrfs_path *path;
3332 struct btrfs_key key;
3335 path = btrfs_alloc_path();
3339 trans = btrfs_start_transaction(root, 0);
3340 if (IS_ERR(trans)) {
3341 btrfs_free_path(path);
3342 return PTR_ERR(trans);
3345 key.objectid = BTRFS_BALANCE_OBJECTID;
3346 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3349 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3357 ret = btrfs_del_item(trans, root, path);
3359 btrfs_free_path(path);
3360 err = btrfs_commit_transaction(trans);
3367 * This is a heuristic used to reduce the number of chunks balanced on
3368 * resume after balance was interrupted.
3370 static void update_balance_args(struct btrfs_balance_control *bctl)
3373 * Turn on soft mode for chunk types that were being converted.
3375 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3376 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3377 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3378 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3379 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3380 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3383 * Turn on usage filter if is not already used. The idea is
3384 * that chunks that we have already balanced should be
3385 * reasonably full. Don't do it for chunks that are being
3386 * converted - that will keep us from relocating unconverted
3387 * (albeit full) chunks.
3389 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3390 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3391 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3392 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3393 bctl->data.usage = 90;
3395 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3396 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3397 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3398 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3399 bctl->sys.usage = 90;
3401 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3402 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3403 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3404 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3405 bctl->meta.usage = 90;
3410 * Clear the balance status in fs_info and delete the balance item from disk.
3412 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3414 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3417 BUG_ON(!fs_info->balance_ctl);
3419 spin_lock(&fs_info->balance_lock);
3420 fs_info->balance_ctl = NULL;
3421 spin_unlock(&fs_info->balance_lock);
3424 ret = del_balance_item(fs_info);
3426 btrfs_handle_fs_error(fs_info, ret, NULL);
3430 * Balance filters. Return 1 if chunk should be filtered out
3431 * (should not be balanced).
3433 static int chunk_profiles_filter(u64 chunk_type,
3434 struct btrfs_balance_args *bargs)
3436 chunk_type = chunk_to_extended(chunk_type) &
3437 BTRFS_EXTENDED_PROFILE_MASK;
3439 if (bargs->profiles & chunk_type)
3445 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3446 struct btrfs_balance_args *bargs)
3448 struct btrfs_block_group_cache *cache;
3450 u64 user_thresh_min;
3451 u64 user_thresh_max;
3454 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3455 chunk_used = btrfs_block_group_used(&cache->item);
3457 if (bargs->usage_min == 0)
3458 user_thresh_min = 0;
3460 user_thresh_min = div_factor_fine(cache->key.offset,
3463 if (bargs->usage_max == 0)
3464 user_thresh_max = 1;
3465 else if (bargs->usage_max > 100)
3466 user_thresh_max = cache->key.offset;
3468 user_thresh_max = div_factor_fine(cache->key.offset,
3471 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3474 btrfs_put_block_group(cache);
3478 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3479 u64 chunk_offset, struct btrfs_balance_args *bargs)
3481 struct btrfs_block_group_cache *cache;
3482 u64 chunk_used, user_thresh;
3485 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3486 chunk_used = btrfs_block_group_used(&cache->item);
3488 if (bargs->usage_min == 0)
3490 else if (bargs->usage > 100)
3491 user_thresh = cache->key.offset;
3493 user_thresh = div_factor_fine(cache->key.offset,
3496 if (chunk_used < user_thresh)
3499 btrfs_put_block_group(cache);
3503 static int chunk_devid_filter(struct extent_buffer *leaf,
3504 struct btrfs_chunk *chunk,
3505 struct btrfs_balance_args *bargs)
3507 struct btrfs_stripe *stripe;
3508 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3511 for (i = 0; i < num_stripes; i++) {
3512 stripe = btrfs_stripe_nr(chunk, i);
3513 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3520 /* [pstart, pend) */
3521 static int chunk_drange_filter(struct extent_buffer *leaf,
3522 struct btrfs_chunk *chunk,
3523 struct btrfs_balance_args *bargs)
3525 struct btrfs_stripe *stripe;
3526 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3532 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3535 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3536 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3537 factor = num_stripes / 2;
3538 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3539 factor = num_stripes - 1;
3540 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3541 factor = num_stripes - 2;
3543 factor = num_stripes;
3546 for (i = 0; i < num_stripes; i++) {
3547 stripe = btrfs_stripe_nr(chunk, i);
3548 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3551 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3552 stripe_length = btrfs_chunk_length(leaf, chunk);
3553 stripe_length = div_u64(stripe_length, factor);
3555 if (stripe_offset < bargs->pend &&
3556 stripe_offset + stripe_length > bargs->pstart)
3563 /* [vstart, vend) */
3564 static int chunk_vrange_filter(struct extent_buffer *leaf,
3565 struct btrfs_chunk *chunk,
3567 struct btrfs_balance_args *bargs)
3569 if (chunk_offset < bargs->vend &&
3570 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3571 /* at least part of the chunk is inside this vrange */
3577 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3578 struct btrfs_chunk *chunk,
3579 struct btrfs_balance_args *bargs)
3581 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3583 if (bargs->stripes_min <= num_stripes
3584 && num_stripes <= bargs->stripes_max)
3590 static int chunk_soft_convert_filter(u64 chunk_type,
3591 struct btrfs_balance_args *bargs)
3593 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3596 chunk_type = chunk_to_extended(chunk_type) &
3597 BTRFS_EXTENDED_PROFILE_MASK;
3599 if (bargs->target == chunk_type)
3605 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3606 struct extent_buffer *leaf,
3607 struct btrfs_chunk *chunk, u64 chunk_offset)
3609 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3610 struct btrfs_balance_args *bargs = NULL;
3611 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3614 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3615 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3619 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3620 bargs = &bctl->data;
3621 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3623 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3624 bargs = &bctl->meta;
3626 /* profiles filter */
3627 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3628 chunk_profiles_filter(chunk_type, bargs)) {
3633 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3634 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3636 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3637 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3642 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3643 chunk_devid_filter(leaf, chunk, bargs)) {
3647 /* drange filter, makes sense only with devid filter */
3648 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3649 chunk_drange_filter(leaf, chunk, bargs)) {
3654 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3655 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3659 /* stripes filter */
3660 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3661 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3665 /* soft profile changing mode */
3666 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3667 chunk_soft_convert_filter(chunk_type, bargs)) {
3672 * limited by count, must be the last filter
3674 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3675 if (bargs->limit == 0)
3679 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3681 * Same logic as the 'limit' filter; the minimum cannot be
3682 * determined here because we do not have the global information
3683 * about the count of all chunks that satisfy the filters.
3685 if (bargs->limit_max == 0)
3694 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3696 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3697 struct btrfs_root *chunk_root = fs_info->chunk_root;
3699 struct btrfs_chunk *chunk;
3700 struct btrfs_path *path = NULL;
3701 struct btrfs_key key;
3702 struct btrfs_key found_key;
3703 struct extent_buffer *leaf;
3706 int enospc_errors = 0;
3707 bool counting = true;
3708 /* The single value limit and min/max limits use the same bytes in the */
3709 u64 limit_data = bctl->data.limit;
3710 u64 limit_meta = bctl->meta.limit;
3711 u64 limit_sys = bctl->sys.limit;
3715 int chunk_reserved = 0;
3717 path = btrfs_alloc_path();
3723 /* zero out stat counters */
3724 spin_lock(&fs_info->balance_lock);
3725 memset(&bctl->stat, 0, sizeof(bctl->stat));
3726 spin_unlock(&fs_info->balance_lock);
3730 * The single value limit and min/max limits use the same bytes
3733 bctl->data.limit = limit_data;
3734 bctl->meta.limit = limit_meta;
3735 bctl->sys.limit = limit_sys;
3737 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3738 key.offset = (u64)-1;
3739 key.type = BTRFS_CHUNK_ITEM_KEY;
3742 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3743 atomic_read(&fs_info->balance_cancel_req)) {
3748 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3749 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3751 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3756 * this shouldn't happen, it means the last relocate
3760 BUG(); /* FIXME break ? */
3762 ret = btrfs_previous_item(chunk_root, path, 0,
3763 BTRFS_CHUNK_ITEM_KEY);
3765 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3770 leaf = path->nodes[0];
3771 slot = path->slots[0];
3772 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3774 if (found_key.objectid != key.objectid) {
3775 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3779 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3780 chunk_type = btrfs_chunk_type(leaf, chunk);
3783 spin_lock(&fs_info->balance_lock);
3784 bctl->stat.considered++;
3785 spin_unlock(&fs_info->balance_lock);
3788 ret = should_balance_chunk(fs_info, leaf, chunk,
3791 btrfs_release_path(path);
3793 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3798 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3799 spin_lock(&fs_info->balance_lock);
3800 bctl->stat.expected++;
3801 spin_unlock(&fs_info->balance_lock);
3803 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3805 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3807 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3814 * Apply limit_min filter, no need to check if the LIMITS
3815 * filter is used, limit_min is 0 by default
3817 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3818 count_data < bctl->data.limit_min)
3819 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3820 count_meta < bctl->meta.limit_min)
3821 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3822 count_sys < bctl->sys.limit_min)) {
3823 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3827 if (!chunk_reserved) {
3829 * We may be relocating the only data chunk we have,
3830 * which could potentially end up with losing data's
3831 * raid profile, so lets allocate an empty one in
3834 ret = btrfs_may_alloc_data_chunk(fs_info,
3837 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3839 } else if (ret == 1) {
3844 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3845 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3846 if (ret == -ENOSPC) {
3848 } else if (ret == -ETXTBSY) {
3850 "skipping relocation of block group %llu due to active swapfile",
3856 spin_lock(&fs_info->balance_lock);
3857 bctl->stat.completed++;
3858 spin_unlock(&fs_info->balance_lock);
3861 if (found_key.offset == 0)
3863 key.offset = found_key.offset - 1;
3867 btrfs_release_path(path);
3872 btrfs_free_path(path);
3873 if (enospc_errors) {
3874 btrfs_info(fs_info, "%d enospc errors during balance",
3884 * alloc_profile_is_valid - see if a given profile is valid and reduced
3885 * @flags: profile to validate
3886 * @extended: if true @flags is treated as an extended profile
3888 static int alloc_profile_is_valid(u64 flags, int extended)
3890 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3891 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3893 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3895 /* 1) check that all other bits are zeroed */
3899 /* 2) see if profile is reduced */
3901 return !extended; /* "0" is valid for usual profiles */
3903 /* true if exactly one bit set */
3904 return is_power_of_2(flags);
3907 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3909 /* cancel requested || normal exit path */
3910 return atomic_read(&fs_info->balance_cancel_req) ||
3911 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3912 atomic_read(&fs_info->balance_cancel_req) == 0);
3915 /* Non-zero return value signifies invalidity */
3916 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3919 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3920 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3921 (bctl_arg->target & ~allowed)));
3925 * Fill @buf with textual description of balance filter flags @bargs, up to
3926 * @size_buf including the terminating null. The output may be trimmed if it
3927 * does not fit into the provided buffer.
3929 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3933 u32 size_bp = size_buf;
3935 u64 flags = bargs->flags;
3936 char tmp_buf[128] = {'\0'};
3941 #define CHECK_APPEND_NOARG(a) \
3943 ret = snprintf(bp, size_bp, (a)); \
3944 if (ret < 0 || ret >= size_bp) \
3945 goto out_overflow; \
3950 #define CHECK_APPEND_1ARG(a, v1) \
3952 ret = snprintf(bp, size_bp, (a), (v1)); \
3953 if (ret < 0 || ret >= size_bp) \
3954 goto out_overflow; \
3959 #define CHECK_APPEND_2ARG(a, v1, v2) \
3961 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3962 if (ret < 0 || ret >= size_bp) \
3963 goto out_overflow; \
3968 if (flags & BTRFS_BALANCE_ARGS_CONVERT) {
3969 int index = btrfs_bg_flags_to_raid_index(bargs->target);
3971 CHECK_APPEND_1ARG("convert=%s,", get_raid_name(index));
3974 if (flags & BTRFS_BALANCE_ARGS_SOFT)
3975 CHECK_APPEND_NOARG("soft,");
3977 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
3978 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
3980 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
3983 if (flags & BTRFS_BALANCE_ARGS_USAGE)
3984 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
3986 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
3987 CHECK_APPEND_2ARG("usage=%u..%u,",
3988 bargs->usage_min, bargs->usage_max);
3990 if (flags & BTRFS_BALANCE_ARGS_DEVID)
3991 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
3993 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
3994 CHECK_APPEND_2ARG("drange=%llu..%llu,",
3995 bargs->pstart, bargs->pend);
3997 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
3998 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
3999 bargs->vstart, bargs->vend);
4001 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4002 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4004 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4005 CHECK_APPEND_2ARG("limit=%u..%u,",
4006 bargs->limit_min, bargs->limit_max);
4008 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4009 CHECK_APPEND_2ARG("stripes=%u..%u,",
4010 bargs->stripes_min, bargs->stripes_max);
4012 #undef CHECK_APPEND_2ARG
4013 #undef CHECK_APPEND_1ARG
4014 #undef CHECK_APPEND_NOARG
4018 if (size_bp < size_buf)
4019 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4024 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4026 u32 size_buf = 1024;
4027 char tmp_buf[192] = {'\0'};
4030 u32 size_bp = size_buf;
4032 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4034 buf = kzalloc(size_buf, GFP_KERNEL);
4040 #define CHECK_APPEND_1ARG(a, v1) \
4042 ret = snprintf(bp, size_bp, (a), (v1)); \
4043 if (ret < 0 || ret >= size_bp) \
4044 goto out_overflow; \
4049 if (bctl->flags & BTRFS_BALANCE_FORCE)
4050 CHECK_APPEND_1ARG("%s", "-f ");
4052 if (bctl->flags & BTRFS_BALANCE_DATA) {
4053 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4054 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4057 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4058 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4059 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4062 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4063 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4064 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4067 #undef CHECK_APPEND_1ARG
4071 if (size_bp < size_buf)
4072 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4073 btrfs_info(fs_info, "balance: %s %s",
4074 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4075 "resume" : "start", buf);
4081 * Should be called with balance mutexe held
4083 int btrfs_balance(struct btrfs_fs_info *fs_info,
4084 struct btrfs_balance_control *bctl,
4085 struct btrfs_ioctl_balance_args *bargs)
4087 u64 meta_target, data_target;
4093 bool reducing_integrity;
4095 if (btrfs_fs_closing(fs_info) ||
4096 atomic_read(&fs_info->balance_pause_req) ||
4097 atomic_read(&fs_info->balance_cancel_req)) {
4102 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4103 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4107 * In case of mixed groups both data and meta should be picked,
4108 * and identical options should be given for both of them.
4110 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4111 if (mixed && (bctl->flags & allowed)) {
4112 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4113 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4114 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4116 "balance: mixed groups data and metadata options must be the same");
4122 num_devices = btrfs_num_devices(fs_info);
4124 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
4125 if (num_devices > 1)
4126 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
4127 if (num_devices > 2)
4128 allowed |= BTRFS_BLOCK_GROUP_RAID5;
4129 if (num_devices > 3)
4130 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
4131 BTRFS_BLOCK_GROUP_RAID6);
4132 if (validate_convert_profile(&bctl->data, allowed)) {
4133 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
4136 "balance: invalid convert data profile %s",
4137 get_raid_name(index));
4141 if (validate_convert_profile(&bctl->meta, allowed)) {
4142 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
4145 "balance: invalid convert metadata profile %s",
4146 get_raid_name(index));
4150 if (validate_convert_profile(&bctl->sys, allowed)) {
4151 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
4154 "balance: invalid convert system profile %s",
4155 get_raid_name(index));
4160 /* allow to reduce meta or sys integrity only if force set */
4161 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
4162 BTRFS_BLOCK_GROUP_RAID10 |
4163 BTRFS_BLOCK_GROUP_RAID5 |
4164 BTRFS_BLOCK_GROUP_RAID6;
4166 seq = read_seqbegin(&fs_info->profiles_lock);
4168 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4169 (fs_info->avail_system_alloc_bits & allowed) &&
4170 !(bctl->sys.target & allowed)) ||
4171 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4172 (fs_info->avail_metadata_alloc_bits & allowed) &&
4173 !(bctl->meta.target & allowed)))
4174 reducing_integrity = true;
4176 reducing_integrity = false;
4178 /* if we're not converting, the target field is uninitialized */
4179 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4180 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4181 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4182 bctl->data.target : fs_info->avail_data_alloc_bits;
4183 } while (read_seqretry(&fs_info->profiles_lock, seq));
4185 if (reducing_integrity) {
4186 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4188 "balance: force reducing metadata integrity");
4191 "balance: reduces metadata integrity, use --force if you want this");
4197 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4198 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4199 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
4200 int data_index = btrfs_bg_flags_to_raid_index(data_target);
4203 "balance: metadata profile %s has lower redundancy than data profile %s",
4204 get_raid_name(meta_index), get_raid_name(data_index));
4207 ret = insert_balance_item(fs_info, bctl);
4208 if (ret && ret != -EEXIST)
4211 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4212 BUG_ON(ret == -EEXIST);
4213 BUG_ON(fs_info->balance_ctl);
4214 spin_lock(&fs_info->balance_lock);
4215 fs_info->balance_ctl = bctl;
4216 spin_unlock(&fs_info->balance_lock);
4218 BUG_ON(ret != -EEXIST);
4219 spin_lock(&fs_info->balance_lock);
4220 update_balance_args(bctl);
4221 spin_unlock(&fs_info->balance_lock);
4224 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4225 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4226 describe_balance_start_or_resume(fs_info);
4227 mutex_unlock(&fs_info->balance_mutex);
4229 ret = __btrfs_balance(fs_info);
4231 mutex_lock(&fs_info->balance_mutex);
4232 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4233 btrfs_info(fs_info, "balance: paused");
4234 else if (ret == -ECANCELED && atomic_read(&fs_info->balance_cancel_req))
4235 btrfs_info(fs_info, "balance: canceled");
4237 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4239 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4242 memset(bargs, 0, sizeof(*bargs));
4243 btrfs_update_ioctl_balance_args(fs_info, bargs);
4246 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4247 balance_need_close(fs_info)) {
4248 reset_balance_state(fs_info);
4249 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4252 wake_up(&fs_info->balance_wait_q);
4256 if (bctl->flags & BTRFS_BALANCE_RESUME)
4257 reset_balance_state(fs_info);
4260 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4265 static int balance_kthread(void *data)
4267 struct btrfs_fs_info *fs_info = data;
4270 mutex_lock(&fs_info->balance_mutex);
4271 if (fs_info->balance_ctl)
4272 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4273 mutex_unlock(&fs_info->balance_mutex);
4278 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4280 struct task_struct *tsk;
4282 mutex_lock(&fs_info->balance_mutex);
4283 if (!fs_info->balance_ctl) {
4284 mutex_unlock(&fs_info->balance_mutex);
4287 mutex_unlock(&fs_info->balance_mutex);
4289 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4290 btrfs_info(fs_info, "balance: resume skipped");
4295 * A ro->rw remount sequence should continue with the paused balance
4296 * regardless of who pauses it, system or the user as of now, so set
4299 spin_lock(&fs_info->balance_lock);
4300 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4301 spin_unlock(&fs_info->balance_lock);
4303 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4304 return PTR_ERR_OR_ZERO(tsk);
4307 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4309 struct btrfs_balance_control *bctl;
4310 struct btrfs_balance_item *item;
4311 struct btrfs_disk_balance_args disk_bargs;
4312 struct btrfs_path *path;
4313 struct extent_buffer *leaf;
4314 struct btrfs_key key;
4317 path = btrfs_alloc_path();
4321 key.objectid = BTRFS_BALANCE_OBJECTID;
4322 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4325 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4328 if (ret > 0) { /* ret = -ENOENT; */
4333 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4339 leaf = path->nodes[0];
4340 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4342 bctl->flags = btrfs_balance_flags(leaf, item);
4343 bctl->flags |= BTRFS_BALANCE_RESUME;
4345 btrfs_balance_data(leaf, item, &disk_bargs);
4346 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4347 btrfs_balance_meta(leaf, item, &disk_bargs);
4348 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4349 btrfs_balance_sys(leaf, item, &disk_bargs);
4350 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4353 * This should never happen, as the paused balance state is recovered
4354 * during mount without any chance of other exclusive ops to collide.
4356 * This gives the exclusive op status to balance and keeps in paused
4357 * state until user intervention (cancel or umount). If the ownership
4358 * cannot be assigned, show a message but do not fail. The balance
4359 * is in a paused state and must have fs_info::balance_ctl properly
4362 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4364 "balance: cannot set exclusive op status, resume manually");
4366 mutex_lock(&fs_info->balance_mutex);
4367 BUG_ON(fs_info->balance_ctl);
4368 spin_lock(&fs_info->balance_lock);
4369 fs_info->balance_ctl = bctl;
4370 spin_unlock(&fs_info->balance_lock);
4371 mutex_unlock(&fs_info->balance_mutex);
4373 btrfs_free_path(path);
4377 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4381 mutex_lock(&fs_info->balance_mutex);
4382 if (!fs_info->balance_ctl) {
4383 mutex_unlock(&fs_info->balance_mutex);
4387 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4388 atomic_inc(&fs_info->balance_pause_req);
4389 mutex_unlock(&fs_info->balance_mutex);
4391 wait_event(fs_info->balance_wait_q,
4392 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4394 mutex_lock(&fs_info->balance_mutex);
4395 /* we are good with balance_ctl ripped off from under us */
4396 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4397 atomic_dec(&fs_info->balance_pause_req);
4402 mutex_unlock(&fs_info->balance_mutex);
4406 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4408 mutex_lock(&fs_info->balance_mutex);
4409 if (!fs_info->balance_ctl) {
4410 mutex_unlock(&fs_info->balance_mutex);
4415 * A paused balance with the item stored on disk can be resumed at
4416 * mount time if the mount is read-write. Otherwise it's still paused
4417 * and we must not allow cancelling as it deletes the item.
4419 if (sb_rdonly(fs_info->sb)) {
4420 mutex_unlock(&fs_info->balance_mutex);
4424 atomic_inc(&fs_info->balance_cancel_req);
4426 * if we are running just wait and return, balance item is
4427 * deleted in btrfs_balance in this case
4429 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4430 mutex_unlock(&fs_info->balance_mutex);
4431 wait_event(fs_info->balance_wait_q,
4432 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4433 mutex_lock(&fs_info->balance_mutex);
4435 mutex_unlock(&fs_info->balance_mutex);
4437 * Lock released to allow other waiters to continue, we'll
4438 * reexamine the status again.
4440 mutex_lock(&fs_info->balance_mutex);
4442 if (fs_info->balance_ctl) {
4443 reset_balance_state(fs_info);
4444 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4445 btrfs_info(fs_info, "balance: canceled");
4449 BUG_ON(fs_info->balance_ctl ||
4450 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4451 atomic_dec(&fs_info->balance_cancel_req);
4452 mutex_unlock(&fs_info->balance_mutex);
4456 static int btrfs_uuid_scan_kthread(void *data)
4458 struct btrfs_fs_info *fs_info = data;
4459 struct btrfs_root *root = fs_info->tree_root;
4460 struct btrfs_key key;
4461 struct btrfs_path *path = NULL;
4463 struct extent_buffer *eb;
4465 struct btrfs_root_item root_item;
4467 struct btrfs_trans_handle *trans = NULL;
4469 path = btrfs_alloc_path();
4476 key.type = BTRFS_ROOT_ITEM_KEY;
4480 ret = btrfs_search_forward(root, &key, path,
4481 BTRFS_OLDEST_GENERATION);
4488 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4489 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4490 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4491 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4494 eb = path->nodes[0];
4495 slot = path->slots[0];
4496 item_size = btrfs_item_size_nr(eb, slot);
4497 if (item_size < sizeof(root_item))
4500 read_extent_buffer(eb, &root_item,
4501 btrfs_item_ptr_offset(eb, slot),
4502 (int)sizeof(root_item));
4503 if (btrfs_root_refs(&root_item) == 0)
4506 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4507 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4511 btrfs_release_path(path);
4513 * 1 - subvol uuid item
4514 * 1 - received_subvol uuid item
4516 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4517 if (IS_ERR(trans)) {
4518 ret = PTR_ERR(trans);
4526 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4527 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4528 BTRFS_UUID_KEY_SUBVOL,
4531 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4537 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4538 ret = btrfs_uuid_tree_add(trans,
4539 root_item.received_uuid,
4540 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4543 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4551 ret = btrfs_end_transaction(trans);
4557 btrfs_release_path(path);
4558 if (key.offset < (u64)-1) {
4560 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4562 key.type = BTRFS_ROOT_ITEM_KEY;
4563 } else if (key.objectid < (u64)-1) {
4565 key.type = BTRFS_ROOT_ITEM_KEY;
4574 btrfs_free_path(path);
4575 if (trans && !IS_ERR(trans))
4576 btrfs_end_transaction(trans);
4578 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4580 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4581 up(&fs_info->uuid_tree_rescan_sem);
4586 * Callback for btrfs_uuid_tree_iterate().
4588 * 0 check succeeded, the entry is not outdated.
4589 * < 0 if an error occurred.
4590 * > 0 if the check failed, which means the caller shall remove the entry.
4592 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4593 u8 *uuid, u8 type, u64 subid)
4595 struct btrfs_key key;
4597 struct btrfs_root *subvol_root;
4599 if (type != BTRFS_UUID_KEY_SUBVOL &&
4600 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4603 key.objectid = subid;
4604 key.type = BTRFS_ROOT_ITEM_KEY;
4605 key.offset = (u64)-1;
4606 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4607 if (IS_ERR(subvol_root)) {
4608 ret = PTR_ERR(subvol_root);
4615 case BTRFS_UUID_KEY_SUBVOL:
4616 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4619 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4620 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4630 static int btrfs_uuid_rescan_kthread(void *data)
4632 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4636 * 1st step is to iterate through the existing UUID tree and
4637 * to delete all entries that contain outdated data.
4638 * 2nd step is to add all missing entries to the UUID tree.
4640 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4642 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4643 up(&fs_info->uuid_tree_rescan_sem);
4646 return btrfs_uuid_scan_kthread(data);
4649 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4651 struct btrfs_trans_handle *trans;
4652 struct btrfs_root *tree_root = fs_info->tree_root;
4653 struct btrfs_root *uuid_root;
4654 struct task_struct *task;
4661 trans = btrfs_start_transaction(tree_root, 2);
4663 return PTR_ERR(trans);
4665 uuid_root = btrfs_create_tree(trans, fs_info,
4666 BTRFS_UUID_TREE_OBJECTID);
4667 if (IS_ERR(uuid_root)) {
4668 ret = PTR_ERR(uuid_root);
4669 btrfs_abort_transaction(trans, ret);
4670 btrfs_end_transaction(trans);
4674 fs_info->uuid_root = uuid_root;
4676 ret = btrfs_commit_transaction(trans);
4680 down(&fs_info->uuid_tree_rescan_sem);
4681 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4683 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4684 btrfs_warn(fs_info, "failed to start uuid_scan task");
4685 up(&fs_info->uuid_tree_rescan_sem);
4686 return PTR_ERR(task);
4692 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4694 struct task_struct *task;
4696 down(&fs_info->uuid_tree_rescan_sem);
4697 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4699 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4700 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4701 up(&fs_info->uuid_tree_rescan_sem);
4702 return PTR_ERR(task);
4709 * shrinking a device means finding all of the device extents past
4710 * the new size, and then following the back refs to the chunks.
4711 * The chunk relocation code actually frees the device extent
4713 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4715 struct btrfs_fs_info *fs_info = device->fs_info;
4716 struct btrfs_root *root = fs_info->dev_root;
4717 struct btrfs_trans_handle *trans;
4718 struct btrfs_dev_extent *dev_extent = NULL;
4719 struct btrfs_path *path;
4725 bool retried = false;
4726 bool checked_pending_chunks = false;
4727 struct extent_buffer *l;
4728 struct btrfs_key key;
4729 struct btrfs_super_block *super_copy = fs_info->super_copy;
4730 u64 old_total = btrfs_super_total_bytes(super_copy);
4731 u64 old_size = btrfs_device_get_total_bytes(device);
4734 new_size = round_down(new_size, fs_info->sectorsize);
4735 diff = round_down(old_size - new_size, fs_info->sectorsize);
4737 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4740 path = btrfs_alloc_path();
4744 path->reada = READA_BACK;
4746 mutex_lock(&fs_info->chunk_mutex);
4748 btrfs_device_set_total_bytes(device, new_size);
4749 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4750 device->fs_devices->total_rw_bytes -= diff;
4751 atomic64_sub(diff, &fs_info->free_chunk_space);
4753 mutex_unlock(&fs_info->chunk_mutex);
4756 key.objectid = device->devid;
4757 key.offset = (u64)-1;
4758 key.type = BTRFS_DEV_EXTENT_KEY;
4761 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4762 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4764 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4768 ret = btrfs_previous_item(root, path, 0, key.type);
4770 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4775 btrfs_release_path(path);
4780 slot = path->slots[0];
4781 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4783 if (key.objectid != device->devid) {
4784 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4785 btrfs_release_path(path);
4789 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4790 length = btrfs_dev_extent_length(l, dev_extent);
4792 if (key.offset + length <= new_size) {
4793 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4794 btrfs_release_path(path);
4798 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4799 btrfs_release_path(path);
4802 * We may be relocating the only data chunk we have,
4803 * which could potentially end up with losing data's
4804 * raid profile, so lets allocate an empty one in
4807 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4809 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4813 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4814 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4815 if (ret == -ENOSPC) {
4818 if (ret == -ETXTBSY) {
4820 "could not shrink block group %llu due to active swapfile",
4825 } while (key.offset-- > 0);
4827 if (failed && !retried) {
4831 } else if (failed && retried) {
4836 /* Shrinking succeeded, else we would be at "done". */
4837 trans = btrfs_start_transaction(root, 0);
4838 if (IS_ERR(trans)) {
4839 ret = PTR_ERR(trans);
4843 mutex_lock(&fs_info->chunk_mutex);
4846 * We checked in the above loop all device extents that were already in
4847 * the device tree. However before we have updated the device's
4848 * total_bytes to the new size, we might have had chunk allocations that
4849 * have not complete yet (new block groups attached to transaction
4850 * handles), and therefore their device extents were not yet in the
4851 * device tree and we missed them in the loop above. So if we have any
4852 * pending chunk using a device extent that overlaps the device range
4853 * that we can not use anymore, commit the current transaction and
4854 * repeat the search on the device tree - this way we guarantee we will
4855 * not have chunks using device extents that end beyond 'new_size'.
4857 if (!checked_pending_chunks) {
4858 u64 start = new_size;
4859 u64 len = old_size - new_size;
4861 if (contains_pending_extent(trans->transaction, device,
4863 mutex_unlock(&fs_info->chunk_mutex);
4864 checked_pending_chunks = true;
4867 ret = btrfs_commit_transaction(trans);
4874 btrfs_device_set_disk_total_bytes(device, new_size);
4875 if (list_empty(&device->resized_list))
4876 list_add_tail(&device->resized_list,
4877 &fs_info->fs_devices->resized_devices);
4879 WARN_ON(diff > old_total);
4880 btrfs_set_super_total_bytes(super_copy,
4881 round_down(old_total - diff, fs_info->sectorsize));
4882 mutex_unlock(&fs_info->chunk_mutex);
4884 /* Now btrfs_update_device() will change the on-disk size. */
4885 ret = btrfs_update_device(trans, device);
4887 btrfs_abort_transaction(trans, ret);
4888 btrfs_end_transaction(trans);
4890 ret = btrfs_commit_transaction(trans);
4893 btrfs_free_path(path);
4895 mutex_lock(&fs_info->chunk_mutex);
4896 btrfs_device_set_total_bytes(device, old_size);
4897 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4898 device->fs_devices->total_rw_bytes += diff;
4899 atomic64_add(diff, &fs_info->free_chunk_space);
4900 mutex_unlock(&fs_info->chunk_mutex);
4905 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4906 struct btrfs_key *key,
4907 struct btrfs_chunk *chunk, int item_size)
4909 struct btrfs_super_block *super_copy = fs_info->super_copy;
4910 struct btrfs_disk_key disk_key;
4914 mutex_lock(&fs_info->chunk_mutex);
4915 array_size = btrfs_super_sys_array_size(super_copy);
4916 if (array_size + item_size + sizeof(disk_key)
4917 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4918 mutex_unlock(&fs_info->chunk_mutex);
4922 ptr = super_copy->sys_chunk_array + array_size;
4923 btrfs_cpu_key_to_disk(&disk_key, key);
4924 memcpy(ptr, &disk_key, sizeof(disk_key));
4925 ptr += sizeof(disk_key);
4926 memcpy(ptr, chunk, item_size);
4927 item_size += sizeof(disk_key);
4928 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4929 mutex_unlock(&fs_info->chunk_mutex);
4935 * sort the devices in descending order by max_avail, total_avail
4937 static int btrfs_cmp_device_info(const void *a, const void *b)
4939 const struct btrfs_device_info *di_a = a;
4940 const struct btrfs_device_info *di_b = b;
4942 if (di_a->max_avail > di_b->max_avail)
4944 if (di_a->max_avail < di_b->max_avail)
4946 if (di_a->total_avail > di_b->total_avail)
4948 if (di_a->total_avail < di_b->total_avail)
4953 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4955 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4958 btrfs_set_fs_incompat(info, RAID56);
4961 #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \
4962 - sizeof(struct btrfs_chunk)) \
4963 / sizeof(struct btrfs_stripe) + 1)
4965 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4966 - 2 * sizeof(struct btrfs_disk_key) \
4967 - 2 * sizeof(struct btrfs_chunk)) \
4968 / sizeof(struct btrfs_stripe) + 1)
4970 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4971 u64 start, u64 type)
4973 struct btrfs_fs_info *info = trans->fs_info;
4974 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4975 struct btrfs_device *device;
4976 struct map_lookup *map = NULL;
4977 struct extent_map_tree *em_tree;
4978 struct extent_map *em;
4979 struct btrfs_device_info *devices_info = NULL;
4981 int num_stripes; /* total number of stripes to allocate */
4982 int data_stripes; /* number of stripes that count for
4984 int sub_stripes; /* sub_stripes info for map */
4985 int dev_stripes; /* stripes per dev */
4986 int devs_max; /* max devs to use */
4987 int devs_min; /* min devs needed */
4988 int devs_increment; /* ndevs has to be a multiple of this */
4989 int ncopies; /* how many copies to data has */
4990 int nparity; /* number of stripes worth of bytes to
4991 store parity information */
4993 u64 max_stripe_size;
5002 BUG_ON(!alloc_profile_is_valid(type, 0));
5004 if (list_empty(&fs_devices->alloc_list)) {
5005 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5006 btrfs_debug(info, "%s: no writable device", __func__);
5010 index = btrfs_bg_flags_to_raid_index(type);
5012 sub_stripes = btrfs_raid_array[index].sub_stripes;
5013 dev_stripes = btrfs_raid_array[index].dev_stripes;
5014 devs_max = btrfs_raid_array[index].devs_max;
5015 devs_min = btrfs_raid_array[index].devs_min;
5016 devs_increment = btrfs_raid_array[index].devs_increment;
5017 ncopies = btrfs_raid_array[index].ncopies;
5018 nparity = btrfs_raid_array[index].nparity;
5020 if (type & BTRFS_BLOCK_GROUP_DATA) {
5021 max_stripe_size = SZ_1G;
5022 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
5024 devs_max = BTRFS_MAX_DEVS(info);
5025 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5026 /* for larger filesystems, use larger metadata chunks */
5027 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
5028 max_stripe_size = SZ_1G;
5030 max_stripe_size = SZ_256M;
5031 max_chunk_size = max_stripe_size;
5033 devs_max = BTRFS_MAX_DEVS(info);
5034 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5035 max_stripe_size = SZ_32M;
5036 max_chunk_size = 2 * max_stripe_size;
5038 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
5040 btrfs_err(info, "invalid chunk type 0x%llx requested",
5045 /* We don't want a chunk larger than 10% of writable space */
5046 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
5049 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5055 * in the first pass through the devices list, we gather information
5056 * about the available holes on each device.
5059 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5063 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5065 "BTRFS: read-only device in alloc_list\n");
5069 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5070 &device->dev_state) ||
5071 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5074 if (device->total_bytes > device->bytes_used)
5075 total_avail = device->total_bytes - device->bytes_used;
5079 /* If there is no space on this device, skip it. */
5080 if (total_avail == 0)
5083 ret = find_free_dev_extent(trans, device,
5084 max_stripe_size * dev_stripes,
5085 &dev_offset, &max_avail);
5086 if (ret && ret != -ENOSPC)
5090 max_avail = max_stripe_size * dev_stripes;
5092 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
5093 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5095 "%s: devid %llu has no free space, have=%llu want=%u",
5096 __func__, device->devid, max_avail,
5097 BTRFS_STRIPE_LEN * dev_stripes);
5101 if (ndevs == fs_devices->rw_devices) {
5102 WARN(1, "%s: found more than %llu devices\n",
5103 __func__, fs_devices->rw_devices);
5106 devices_info[ndevs].dev_offset = dev_offset;
5107 devices_info[ndevs].max_avail = max_avail;
5108 devices_info[ndevs].total_avail = total_avail;
5109 devices_info[ndevs].dev = device;
5114 * now sort the devices by hole size / available space
5116 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5117 btrfs_cmp_device_info, NULL);
5119 /* round down to number of usable stripes */
5120 ndevs = round_down(ndevs, devs_increment);
5122 if (ndevs < devs_min) {
5124 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5126 "%s: not enough devices with free space: have=%d minimum required=%d",
5127 __func__, ndevs, devs_min);
5132 ndevs = min(ndevs, devs_max);
5135 * The primary goal is to maximize the number of stripes, so use as
5136 * many devices as possible, even if the stripes are not maximum sized.
5138 * The DUP profile stores more than one stripe per device, the
5139 * max_avail is the total size so we have to adjust.
5141 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
5142 num_stripes = ndevs * dev_stripes;
5145 * this will have to be fixed for RAID1 and RAID10 over
5148 data_stripes = (num_stripes - nparity) / ncopies;
5151 * Use the number of data stripes to figure out how big this chunk
5152 * is really going to be in terms of logical address space,
5153 * and compare that answer with the max chunk size. If it's higher,
5154 * we try to reduce stripe_size.
5156 if (stripe_size * data_stripes > max_chunk_size) {
5158 * Reduce stripe_size, round it up to a 16MB boundary again and
5159 * then use it, unless it ends up being even bigger than the
5160 * previous value we had already.
5162 stripe_size = min(round_up(div_u64(max_chunk_size,
5163 data_stripes), SZ_16M),
5167 /* align to BTRFS_STRIPE_LEN */
5168 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
5170 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5175 map->num_stripes = num_stripes;
5177 for (i = 0; i < ndevs; ++i) {
5178 for (j = 0; j < dev_stripes; ++j) {
5179 int s = i * dev_stripes + j;
5180 map->stripes[s].dev = devices_info[i].dev;
5181 map->stripes[s].physical = devices_info[i].dev_offset +
5185 map->stripe_len = BTRFS_STRIPE_LEN;
5186 map->io_align = BTRFS_STRIPE_LEN;
5187 map->io_width = BTRFS_STRIPE_LEN;
5189 map->sub_stripes = sub_stripes;
5191 chunk_size = stripe_size * data_stripes;
5193 trace_btrfs_chunk_alloc(info, map, start, chunk_size);
5195 em = alloc_extent_map();
5201 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5202 em->map_lookup = map;
5204 em->len = chunk_size;
5205 em->block_start = 0;
5206 em->block_len = em->len;
5207 em->orig_block_len = stripe_size;
5209 em_tree = &info->mapping_tree.map_tree;
5210 write_lock(&em_tree->lock);
5211 ret = add_extent_mapping(em_tree, em, 0);
5213 write_unlock(&em_tree->lock);
5214 free_extent_map(em);
5218 list_add_tail(&em->list, &trans->transaction->pending_chunks);
5219 refcount_inc(&em->refs);
5220 write_unlock(&em_tree->lock);
5222 ret = btrfs_make_block_group(trans, 0, type, start, chunk_size);
5224 goto error_del_extent;
5226 for (i = 0; i < map->num_stripes; i++)
5227 btrfs_device_set_bytes_used(map->stripes[i].dev,
5228 map->stripes[i].dev->bytes_used + stripe_size);
5230 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
5232 free_extent_map(em);
5233 check_raid56_incompat_flag(info, type);
5235 kfree(devices_info);
5239 write_lock(&em_tree->lock);
5240 remove_extent_mapping(em_tree, em);
5241 write_unlock(&em_tree->lock);
5243 /* One for our allocation */
5244 free_extent_map(em);
5245 /* One for the tree reference */
5246 free_extent_map(em);
5247 /* One for the pending_chunks list reference */
5248 free_extent_map(em);
5250 kfree(devices_info);
5254 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5255 u64 chunk_offset, u64 chunk_size)
5257 struct btrfs_fs_info *fs_info = trans->fs_info;
5258 struct btrfs_root *extent_root = fs_info->extent_root;
5259 struct btrfs_root *chunk_root = fs_info->chunk_root;
5260 struct btrfs_key key;
5261 struct btrfs_device *device;
5262 struct btrfs_chunk *chunk;
5263 struct btrfs_stripe *stripe;
5264 struct extent_map *em;
5265 struct map_lookup *map;
5272 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5276 map = em->map_lookup;
5277 item_size = btrfs_chunk_item_size(map->num_stripes);
5278 stripe_size = em->orig_block_len;
5280 chunk = kzalloc(item_size, GFP_NOFS);
5287 * Take the device list mutex to prevent races with the final phase of
5288 * a device replace operation that replaces the device object associated
5289 * with the map's stripes, because the device object's id can change
5290 * at any time during that final phase of the device replace operation
5291 * (dev-replace.c:btrfs_dev_replace_finishing()).
5293 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5294 for (i = 0; i < map->num_stripes; i++) {
5295 device = map->stripes[i].dev;
5296 dev_offset = map->stripes[i].physical;
5298 ret = btrfs_update_device(trans, device);
5301 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5302 dev_offset, stripe_size);
5307 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5311 stripe = &chunk->stripe;
5312 for (i = 0; i < map->num_stripes; i++) {
5313 device = map->stripes[i].dev;
5314 dev_offset = map->stripes[i].physical;
5316 btrfs_set_stack_stripe_devid(stripe, device->devid);
5317 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5318 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5321 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5323 btrfs_set_stack_chunk_length(chunk, chunk_size);
5324 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5325 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5326 btrfs_set_stack_chunk_type(chunk, map->type);
5327 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5328 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5329 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5330 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5331 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5333 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5334 key.type = BTRFS_CHUNK_ITEM_KEY;
5335 key.offset = chunk_offset;
5337 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5338 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5340 * TODO: Cleanup of inserted chunk root in case of
5343 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5348 free_extent_map(em);
5353 * Chunk allocation falls into two parts. The first part does work
5354 * that makes the new allocated chunk usable, but does not do any operation
5355 * that modifies the chunk tree. The second part does the work that
5356 * requires modifying the chunk tree. This division is important for the
5357 * bootstrap process of adding storage to a seed btrfs.
5359 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5363 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5364 chunk_offset = find_next_chunk(trans->fs_info);
5365 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5368 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5369 struct btrfs_fs_info *fs_info)
5372 u64 sys_chunk_offset;
5376 chunk_offset = find_next_chunk(fs_info);
5377 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5378 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5382 sys_chunk_offset = find_next_chunk(fs_info);
5383 alloc_profile = btrfs_system_alloc_profile(fs_info);
5384 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5388 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5392 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5393 BTRFS_BLOCK_GROUP_RAID10 |
5394 BTRFS_BLOCK_GROUP_RAID5 |
5395 BTRFS_BLOCK_GROUP_DUP)) {
5397 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5406 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5408 struct extent_map *em;
5409 struct map_lookup *map;
5414 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5418 map = em->map_lookup;
5419 for (i = 0; i < map->num_stripes; i++) {
5420 if (test_bit(BTRFS_DEV_STATE_MISSING,
5421 &map->stripes[i].dev->dev_state)) {
5425 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5426 &map->stripes[i].dev->dev_state)) {
5433 * If the number of missing devices is larger than max errors,
5434 * we can not write the data into that chunk successfully, so
5437 if (miss_ndevs > btrfs_chunk_max_errors(map))
5440 free_extent_map(em);
5444 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5446 extent_map_tree_init(&tree->map_tree);
5449 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5451 struct extent_map *em;
5454 write_lock(&tree->map_tree.lock);
5455 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5457 remove_extent_mapping(&tree->map_tree, em);
5458 write_unlock(&tree->map_tree.lock);
5462 free_extent_map(em);
5463 /* once for the tree */
5464 free_extent_map(em);
5468 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5470 struct extent_map *em;
5471 struct map_lookup *map;
5474 em = btrfs_get_chunk_map(fs_info, logical, len);
5477 * We could return errors for these cases, but that could get
5478 * ugly and we'd probably do the same thing which is just not do
5479 * anything else and exit, so return 1 so the callers don't try
5480 * to use other copies.
5484 map = em->map_lookup;
5485 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5486 ret = map->num_stripes;
5487 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5488 ret = map->sub_stripes;
5489 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5491 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5493 * There could be two corrupted data stripes, we need
5494 * to loop retry in order to rebuild the correct data.
5496 * Fail a stripe at a time on every retry except the
5497 * stripe under reconstruction.
5499 ret = map->num_stripes;
5502 free_extent_map(em);
5504 down_read(&fs_info->dev_replace.rwsem);
5505 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5506 fs_info->dev_replace.tgtdev)
5508 up_read(&fs_info->dev_replace.rwsem);
5513 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5516 struct extent_map *em;
5517 struct map_lookup *map;
5518 unsigned long len = fs_info->sectorsize;
5520 em = btrfs_get_chunk_map(fs_info, logical, len);
5522 if (!WARN_ON(IS_ERR(em))) {
5523 map = em->map_lookup;
5524 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5525 len = map->stripe_len * nr_data_stripes(map);
5526 free_extent_map(em);
5531 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5533 struct extent_map *em;
5534 struct map_lookup *map;
5537 em = btrfs_get_chunk_map(fs_info, logical, len);
5539 if(!WARN_ON(IS_ERR(em))) {
5540 map = em->map_lookup;
5541 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5543 free_extent_map(em);
5548 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5549 struct map_lookup *map, int first,
5550 int dev_replace_is_ongoing)
5554 int preferred_mirror;
5556 struct btrfs_device *srcdev;
5559 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5561 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5562 num_stripes = map->sub_stripes;
5564 num_stripes = map->num_stripes;
5566 preferred_mirror = first + current->pid % num_stripes;
5568 if (dev_replace_is_ongoing &&
5569 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5570 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5571 srcdev = fs_info->dev_replace.srcdev;
5576 * try to avoid the drive that is the source drive for a
5577 * dev-replace procedure, only choose it if no other non-missing
5578 * mirror is available
5580 for (tolerance = 0; tolerance < 2; tolerance++) {
5581 if (map->stripes[preferred_mirror].dev->bdev &&
5582 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5583 return preferred_mirror;
5584 for (i = first; i < first + num_stripes; i++) {
5585 if (map->stripes[i].dev->bdev &&
5586 (tolerance || map->stripes[i].dev != srcdev))
5591 /* we couldn't find one that doesn't fail. Just return something
5592 * and the io error handling code will clean up eventually
5594 return preferred_mirror;
5597 static inline int parity_smaller(u64 a, u64 b)
5602 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5603 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5605 struct btrfs_bio_stripe s;
5612 for (i = 0; i < num_stripes - 1; i++) {
5613 if (parity_smaller(bbio->raid_map[i],
5614 bbio->raid_map[i+1])) {
5615 s = bbio->stripes[i];
5616 l = bbio->raid_map[i];
5617 bbio->stripes[i] = bbio->stripes[i+1];
5618 bbio->raid_map[i] = bbio->raid_map[i+1];
5619 bbio->stripes[i+1] = s;
5620 bbio->raid_map[i+1] = l;
5628 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5630 struct btrfs_bio *bbio = kzalloc(
5631 /* the size of the btrfs_bio */
5632 sizeof(struct btrfs_bio) +
5633 /* plus the variable array for the stripes */
5634 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5635 /* plus the variable array for the tgt dev */
5636 sizeof(int) * (real_stripes) +
5638 * plus the raid_map, which includes both the tgt dev
5641 sizeof(u64) * (total_stripes),
5642 GFP_NOFS|__GFP_NOFAIL);
5644 atomic_set(&bbio->error, 0);
5645 refcount_set(&bbio->refs, 1);
5650 void btrfs_get_bbio(struct btrfs_bio *bbio)
5652 WARN_ON(!refcount_read(&bbio->refs));
5653 refcount_inc(&bbio->refs);
5656 void btrfs_put_bbio(struct btrfs_bio *bbio)
5660 if (refcount_dec_and_test(&bbio->refs))
5664 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5666 * Please note that, discard won't be sent to target device of device
5669 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5670 u64 logical, u64 length,
5671 struct btrfs_bio **bbio_ret)
5673 struct extent_map *em;
5674 struct map_lookup *map;
5675 struct btrfs_bio *bbio;
5679 u64 stripe_end_offset;
5686 u32 sub_stripes = 0;
5687 u64 stripes_per_dev = 0;
5688 u32 remaining_stripes = 0;
5689 u32 last_stripe = 0;
5693 /* discard always return a bbio */
5696 em = btrfs_get_chunk_map(fs_info, logical, length);
5700 map = em->map_lookup;
5701 /* we don't discard raid56 yet */
5702 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5707 offset = logical - em->start;
5708 length = min_t(u64, em->len - offset, length);
5710 stripe_len = map->stripe_len;
5712 * stripe_nr counts the total number of stripes we have to stride
5713 * to get to this block
5715 stripe_nr = div64_u64(offset, stripe_len);
5717 /* stripe_offset is the offset of this block in its stripe */
5718 stripe_offset = offset - stripe_nr * stripe_len;
5720 stripe_nr_end = round_up(offset + length, map->stripe_len);
5721 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5722 stripe_cnt = stripe_nr_end - stripe_nr;
5723 stripe_end_offset = stripe_nr_end * map->stripe_len -
5726 * after this, stripe_nr is the number of stripes on this
5727 * device we have to walk to find the data, and stripe_index is
5728 * the number of our device in the stripe array
5732 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5733 BTRFS_BLOCK_GROUP_RAID10)) {
5734 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5737 sub_stripes = map->sub_stripes;
5739 factor = map->num_stripes / sub_stripes;
5740 num_stripes = min_t(u64, map->num_stripes,
5741 sub_stripes * stripe_cnt);
5742 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5743 stripe_index *= sub_stripes;
5744 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5745 &remaining_stripes);
5746 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5747 last_stripe *= sub_stripes;
5748 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5749 BTRFS_BLOCK_GROUP_DUP)) {
5750 num_stripes = map->num_stripes;
5752 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5756 bbio = alloc_btrfs_bio(num_stripes, 0);
5762 for (i = 0; i < num_stripes; i++) {
5763 bbio->stripes[i].physical =
5764 map->stripes[stripe_index].physical +
5765 stripe_offset + stripe_nr * map->stripe_len;
5766 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5768 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5769 BTRFS_BLOCK_GROUP_RAID10)) {
5770 bbio->stripes[i].length = stripes_per_dev *
5773 if (i / sub_stripes < remaining_stripes)
5774 bbio->stripes[i].length +=
5778 * Special for the first stripe and
5781 * |-------|...|-------|
5785 if (i < sub_stripes)
5786 bbio->stripes[i].length -=
5789 if (stripe_index >= last_stripe &&
5790 stripe_index <= (last_stripe +
5792 bbio->stripes[i].length -=
5795 if (i == sub_stripes - 1)
5798 bbio->stripes[i].length = length;
5802 if (stripe_index == map->num_stripes) {
5809 bbio->map_type = map->type;
5810 bbio->num_stripes = num_stripes;
5812 free_extent_map(em);
5817 * In dev-replace case, for repair case (that's the only case where the mirror
5818 * is selected explicitly when calling btrfs_map_block), blocks left of the
5819 * left cursor can also be read from the target drive.
5821 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5823 * For READ, it also needs to be supported using the same mirror number.
5825 * If the requested block is not left of the left cursor, EIO is returned. This
5826 * can happen because btrfs_num_copies() returns one more in the dev-replace
5829 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5830 u64 logical, u64 length,
5831 u64 srcdev_devid, int *mirror_num,
5834 struct btrfs_bio *bbio = NULL;
5836 int index_srcdev = 0;
5838 u64 physical_of_found = 0;
5842 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5843 logical, &length, &bbio, 0, 0);
5845 ASSERT(bbio == NULL);
5849 num_stripes = bbio->num_stripes;
5850 if (*mirror_num > num_stripes) {
5852 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5853 * that means that the requested area is not left of the left
5856 btrfs_put_bbio(bbio);
5861 * process the rest of the function using the mirror_num of the source
5862 * drive. Therefore look it up first. At the end, patch the device
5863 * pointer to the one of the target drive.
5865 for (i = 0; i < num_stripes; i++) {
5866 if (bbio->stripes[i].dev->devid != srcdev_devid)
5870 * In case of DUP, in order to keep it simple, only add the
5871 * mirror with the lowest physical address
5874 physical_of_found <= bbio->stripes[i].physical)
5879 physical_of_found = bbio->stripes[i].physical;
5882 btrfs_put_bbio(bbio);
5888 *mirror_num = index_srcdev + 1;
5889 *physical = physical_of_found;
5893 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5894 struct btrfs_bio **bbio_ret,
5895 struct btrfs_dev_replace *dev_replace,
5896 int *num_stripes_ret, int *max_errors_ret)
5898 struct btrfs_bio *bbio = *bbio_ret;
5899 u64 srcdev_devid = dev_replace->srcdev->devid;
5900 int tgtdev_indexes = 0;
5901 int num_stripes = *num_stripes_ret;
5902 int max_errors = *max_errors_ret;
5905 if (op == BTRFS_MAP_WRITE) {
5906 int index_where_to_add;
5909 * duplicate the write operations while the dev replace
5910 * procedure is running. Since the copying of the old disk to
5911 * the new disk takes place at run time while the filesystem is
5912 * mounted writable, the regular write operations to the old
5913 * disk have to be duplicated to go to the new disk as well.
5915 * Note that device->missing is handled by the caller, and that
5916 * the write to the old disk is already set up in the stripes
5919 index_where_to_add = num_stripes;
5920 for (i = 0; i < num_stripes; i++) {
5921 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5922 /* write to new disk, too */
5923 struct btrfs_bio_stripe *new =
5924 bbio->stripes + index_where_to_add;
5925 struct btrfs_bio_stripe *old =
5928 new->physical = old->physical;
5929 new->length = old->length;
5930 new->dev = dev_replace->tgtdev;
5931 bbio->tgtdev_map[i] = index_where_to_add;
5932 index_where_to_add++;
5937 num_stripes = index_where_to_add;
5938 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5939 int index_srcdev = 0;
5941 u64 physical_of_found = 0;
5944 * During the dev-replace procedure, the target drive can also
5945 * be used to read data in case it is needed to repair a corrupt
5946 * block elsewhere. This is possible if the requested area is
5947 * left of the left cursor. In this area, the target drive is a
5948 * full copy of the source drive.
5950 for (i = 0; i < num_stripes; i++) {
5951 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5953 * In case of DUP, in order to keep it simple,
5954 * only add the mirror with the lowest physical
5958 physical_of_found <=
5959 bbio->stripes[i].physical)
5963 physical_of_found = bbio->stripes[i].physical;
5967 struct btrfs_bio_stripe *tgtdev_stripe =
5968 bbio->stripes + num_stripes;
5970 tgtdev_stripe->physical = physical_of_found;
5971 tgtdev_stripe->length =
5972 bbio->stripes[index_srcdev].length;
5973 tgtdev_stripe->dev = dev_replace->tgtdev;
5974 bbio->tgtdev_map[index_srcdev] = num_stripes;
5981 *num_stripes_ret = num_stripes;
5982 *max_errors_ret = max_errors;
5983 bbio->num_tgtdevs = tgtdev_indexes;
5987 static bool need_full_stripe(enum btrfs_map_op op)
5989 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5992 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5993 enum btrfs_map_op op,
5994 u64 logical, u64 *length,
5995 struct btrfs_bio **bbio_ret,
5996 int mirror_num, int need_raid_map)
5998 struct extent_map *em;
5999 struct map_lookup *map;
6009 int tgtdev_indexes = 0;
6010 struct btrfs_bio *bbio = NULL;
6011 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6012 int dev_replace_is_ongoing = 0;
6013 int num_alloc_stripes;
6014 int patch_the_first_stripe_for_dev_replace = 0;
6015 u64 physical_to_patch_in_first_stripe = 0;
6016 u64 raid56_full_stripe_start = (u64)-1;
6018 if (op == BTRFS_MAP_DISCARD)
6019 return __btrfs_map_block_for_discard(fs_info, logical,
6022 em = btrfs_get_chunk_map(fs_info, logical, *length);
6026 map = em->map_lookup;
6027 offset = logical - em->start;
6029 stripe_len = map->stripe_len;
6032 * stripe_nr counts the total number of stripes we have to stride
6033 * to get to this block
6035 stripe_nr = div64_u64(stripe_nr, stripe_len);
6037 stripe_offset = stripe_nr * stripe_len;
6038 if (offset < stripe_offset) {
6040 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
6041 stripe_offset, offset, em->start, logical,
6043 free_extent_map(em);
6047 /* stripe_offset is the offset of this block in its stripe*/
6048 stripe_offset = offset - stripe_offset;
6050 /* if we're here for raid56, we need to know the stripe aligned start */
6051 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6052 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
6053 raid56_full_stripe_start = offset;
6055 /* allow a write of a full stripe, but make sure we don't
6056 * allow straddling of stripes
6058 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6060 raid56_full_stripe_start *= full_stripe_len;
6063 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6065 /* For writes to RAID[56], allow a full stripeset across all disks.
6066 For other RAID types and for RAID[56] reads, just allow a single
6067 stripe (on a single disk). */
6068 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6069 (op == BTRFS_MAP_WRITE)) {
6070 max_len = stripe_len * nr_data_stripes(map) -
6071 (offset - raid56_full_stripe_start);
6073 /* we limit the length of each bio to what fits in a stripe */
6074 max_len = stripe_len - stripe_offset;
6076 *length = min_t(u64, em->len - offset, max_len);
6078 *length = em->len - offset;
6082 * This is for when we're called from btrfs_bio_fits_in_stripe and all
6083 * it cares about is the length
6088 down_read(&dev_replace->rwsem);
6089 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6091 * Hold the semaphore for read during the whole operation, write is
6092 * requested at commit time but must wait.
6094 if (!dev_replace_is_ongoing)
6095 up_read(&dev_replace->rwsem);
6097 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6098 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6099 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6100 dev_replace->srcdev->devid,
6102 &physical_to_patch_in_first_stripe);
6106 patch_the_first_stripe_for_dev_replace = 1;
6107 } else if (mirror_num > map->num_stripes) {
6113 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6114 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6116 if (!need_full_stripe(op))
6118 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
6119 if (need_full_stripe(op))
6120 num_stripes = map->num_stripes;
6121 else if (mirror_num)
6122 stripe_index = mirror_num - 1;
6124 stripe_index = find_live_mirror(fs_info, map, 0,
6125 dev_replace_is_ongoing);
6126 mirror_num = stripe_index + 1;
6129 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6130 if (need_full_stripe(op)) {
6131 num_stripes = map->num_stripes;
6132 } else if (mirror_num) {
6133 stripe_index = mirror_num - 1;
6138 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6139 u32 factor = map->num_stripes / map->sub_stripes;
6141 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6142 stripe_index *= map->sub_stripes;
6144 if (need_full_stripe(op))
6145 num_stripes = map->sub_stripes;
6146 else if (mirror_num)
6147 stripe_index += mirror_num - 1;
6149 int old_stripe_index = stripe_index;
6150 stripe_index = find_live_mirror(fs_info, map,
6152 dev_replace_is_ongoing);
6153 mirror_num = stripe_index - old_stripe_index + 1;
6156 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6157 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6158 /* push stripe_nr back to the start of the full stripe */
6159 stripe_nr = div64_u64(raid56_full_stripe_start,
6160 stripe_len * nr_data_stripes(map));
6162 /* RAID[56] write or recovery. Return all stripes */
6163 num_stripes = map->num_stripes;
6164 max_errors = nr_parity_stripes(map);
6166 *length = map->stripe_len;
6171 * Mirror #0 or #1 means the original data block.
6172 * Mirror #2 is RAID5 parity block.
6173 * Mirror #3 is RAID6 Q block.
6175 stripe_nr = div_u64_rem(stripe_nr,
6176 nr_data_stripes(map), &stripe_index);
6178 stripe_index = nr_data_stripes(map) +
6181 /* We distribute the parity blocks across stripes */
6182 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6184 if (!need_full_stripe(op) && mirror_num <= 1)
6189 * after this, stripe_nr is the number of stripes on this
6190 * device we have to walk to find the data, and stripe_index is
6191 * the number of our device in the stripe array
6193 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6195 mirror_num = stripe_index + 1;
6197 if (stripe_index >= map->num_stripes) {
6199 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6200 stripe_index, map->num_stripes);
6205 num_alloc_stripes = num_stripes;
6206 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6207 if (op == BTRFS_MAP_WRITE)
6208 num_alloc_stripes <<= 1;
6209 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6210 num_alloc_stripes++;
6211 tgtdev_indexes = num_stripes;
6214 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6219 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
6220 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
6222 /* build raid_map */
6223 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6224 (need_full_stripe(op) || mirror_num > 1)) {
6228 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6229 sizeof(struct btrfs_bio_stripe) *
6231 sizeof(int) * tgtdev_indexes);
6233 /* Work out the disk rotation on this stripe-set */
6234 div_u64_rem(stripe_nr, num_stripes, &rot);
6236 /* Fill in the logical address of each stripe */
6237 tmp = stripe_nr * nr_data_stripes(map);
6238 for (i = 0; i < nr_data_stripes(map); i++)
6239 bbio->raid_map[(i+rot) % num_stripes] =
6240 em->start + (tmp + i) * map->stripe_len;
6242 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6243 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6244 bbio->raid_map[(i+rot+1) % num_stripes] =
6249 for (i = 0; i < num_stripes; i++) {
6250 bbio->stripes[i].physical =
6251 map->stripes[stripe_index].physical +
6253 stripe_nr * map->stripe_len;
6254 bbio->stripes[i].dev =
6255 map->stripes[stripe_index].dev;
6259 if (need_full_stripe(op))
6260 max_errors = btrfs_chunk_max_errors(map);
6263 sort_parity_stripes(bbio, num_stripes);
6265 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6266 need_full_stripe(op)) {
6267 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6272 bbio->map_type = map->type;
6273 bbio->num_stripes = num_stripes;
6274 bbio->max_errors = max_errors;
6275 bbio->mirror_num = mirror_num;
6278 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6279 * mirror_num == num_stripes + 1 && dev_replace target drive is
6280 * available as a mirror
6282 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6283 WARN_ON(num_stripes > 1);
6284 bbio->stripes[0].dev = dev_replace->tgtdev;
6285 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6286 bbio->mirror_num = map->num_stripes + 1;
6289 if (dev_replace_is_ongoing) {
6290 lockdep_assert_held(&dev_replace->rwsem);
6291 /* Unlock and let waiting writers proceed */
6292 up_read(&dev_replace->rwsem);
6294 free_extent_map(em);
6298 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6299 u64 logical, u64 *length,
6300 struct btrfs_bio **bbio_ret, int mirror_num)
6302 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6306 /* For Scrub/replace */
6307 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6308 u64 logical, u64 *length,
6309 struct btrfs_bio **bbio_ret)
6311 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6314 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
6315 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
6317 struct extent_map *em;
6318 struct map_lookup *map;
6326 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
6330 map = em->map_lookup;
6332 rmap_len = map->stripe_len;
6334 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6335 length = div_u64(length, map->num_stripes / map->sub_stripes);
6336 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6337 length = div_u64(length, map->num_stripes);
6338 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6339 length = div_u64(length, nr_data_stripes(map));
6340 rmap_len = map->stripe_len * nr_data_stripes(map);
6343 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6344 BUG_ON(!buf); /* -ENOMEM */
6346 for (i = 0; i < map->num_stripes; i++) {
6347 if (map->stripes[i].physical > physical ||
6348 map->stripes[i].physical + length <= physical)
6351 stripe_nr = physical - map->stripes[i].physical;
6352 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6354 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6355 stripe_nr = stripe_nr * map->num_stripes + i;
6356 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6357 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6358 stripe_nr = stripe_nr * map->num_stripes + i;
6359 } /* else if RAID[56], multiply by nr_data_stripes().
6360 * Alternatively, just use rmap_len below instead of
6361 * map->stripe_len */
6363 bytenr = chunk_start + stripe_nr * rmap_len;
6364 WARN_ON(nr >= map->num_stripes);
6365 for (j = 0; j < nr; j++) {
6366 if (buf[j] == bytenr)
6370 WARN_ON(nr >= map->num_stripes);
6377 *stripe_len = rmap_len;
6379 free_extent_map(em);
6383 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6385 bio->bi_private = bbio->private;
6386 bio->bi_end_io = bbio->end_io;
6389 btrfs_put_bbio(bbio);
6392 static void btrfs_end_bio(struct bio *bio)
6394 struct btrfs_bio *bbio = bio->bi_private;
6395 int is_orig_bio = 0;
6397 if (bio->bi_status) {
6398 atomic_inc(&bbio->error);
6399 if (bio->bi_status == BLK_STS_IOERR ||
6400 bio->bi_status == BLK_STS_TARGET) {
6401 unsigned int stripe_index =
6402 btrfs_io_bio(bio)->stripe_index;
6403 struct btrfs_device *dev;
6405 BUG_ON(stripe_index >= bbio->num_stripes);
6406 dev = bbio->stripes[stripe_index].dev;
6408 if (bio_op(bio) == REQ_OP_WRITE)
6409 btrfs_dev_stat_inc_and_print(dev,
6410 BTRFS_DEV_STAT_WRITE_ERRS);
6412 btrfs_dev_stat_inc_and_print(dev,
6413 BTRFS_DEV_STAT_READ_ERRS);
6414 if (bio->bi_opf & REQ_PREFLUSH)
6415 btrfs_dev_stat_inc_and_print(dev,
6416 BTRFS_DEV_STAT_FLUSH_ERRS);
6421 if (bio == bbio->orig_bio)
6424 btrfs_bio_counter_dec(bbio->fs_info);
6426 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6429 bio = bbio->orig_bio;
6432 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6433 /* only send an error to the higher layers if it is
6434 * beyond the tolerance of the btrfs bio
6436 if (atomic_read(&bbio->error) > bbio->max_errors) {
6437 bio->bi_status = BLK_STS_IOERR;
6440 * this bio is actually up to date, we didn't
6441 * go over the max number of errors
6443 bio->bi_status = BLK_STS_OK;
6446 btrfs_end_bbio(bbio, bio);
6447 } else if (!is_orig_bio) {
6453 * see run_scheduled_bios for a description of why bios are collected for
6456 * This will add one bio to the pending list for a device and make sure
6457 * the work struct is scheduled.
6459 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6462 struct btrfs_fs_info *fs_info = device->fs_info;
6463 int should_queue = 1;
6464 struct btrfs_pending_bios *pending_bios;
6466 /* don't bother with additional async steps for reads, right now */
6467 if (bio_op(bio) == REQ_OP_READ) {
6468 btrfsic_submit_bio(bio);
6472 WARN_ON(bio->bi_next);
6473 bio->bi_next = NULL;
6475 spin_lock(&device->io_lock);
6476 if (op_is_sync(bio->bi_opf))
6477 pending_bios = &device->pending_sync_bios;
6479 pending_bios = &device->pending_bios;
6481 if (pending_bios->tail)
6482 pending_bios->tail->bi_next = bio;
6484 pending_bios->tail = bio;
6485 if (!pending_bios->head)
6486 pending_bios->head = bio;
6487 if (device->running_pending)
6490 spin_unlock(&device->io_lock);
6493 btrfs_queue_work(fs_info->submit_workers, &device->work);
6496 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6497 u64 physical, int dev_nr, int async)
6499 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6500 struct btrfs_fs_info *fs_info = bbio->fs_info;
6502 bio->bi_private = bbio;
6503 btrfs_io_bio(bio)->stripe_index = dev_nr;
6504 bio->bi_end_io = btrfs_end_bio;
6505 bio->bi_iter.bi_sector = physical >> 9;
6506 btrfs_debug_in_rcu(fs_info,
6507 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6508 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6509 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6510 bio->bi_iter.bi_size);
6511 bio_set_dev(bio, dev->bdev);
6513 btrfs_bio_counter_inc_noblocked(fs_info);
6516 btrfs_schedule_bio(dev, bio);
6518 btrfsic_submit_bio(bio);
6521 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6523 atomic_inc(&bbio->error);
6524 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6525 /* Should be the original bio. */
6526 WARN_ON(bio != bbio->orig_bio);
6528 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6529 bio->bi_iter.bi_sector = logical >> 9;
6530 if (atomic_read(&bbio->error) > bbio->max_errors)
6531 bio->bi_status = BLK_STS_IOERR;
6533 bio->bi_status = BLK_STS_OK;
6534 btrfs_end_bbio(bbio, bio);
6538 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6539 int mirror_num, int async_submit)
6541 struct btrfs_device *dev;
6542 struct bio *first_bio = bio;
6543 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6549 struct btrfs_bio *bbio = NULL;
6551 length = bio->bi_iter.bi_size;
6552 map_length = length;
6554 btrfs_bio_counter_inc_blocked(fs_info);
6555 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6556 &map_length, &bbio, mirror_num, 1);
6558 btrfs_bio_counter_dec(fs_info);
6559 return errno_to_blk_status(ret);
6562 total_devs = bbio->num_stripes;
6563 bbio->orig_bio = first_bio;
6564 bbio->private = first_bio->bi_private;
6565 bbio->end_io = first_bio->bi_end_io;
6566 bbio->fs_info = fs_info;
6567 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6569 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6570 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6571 /* In this case, map_length has been set to the length of
6572 a single stripe; not the whole write */
6573 if (bio_op(bio) == REQ_OP_WRITE) {
6574 ret = raid56_parity_write(fs_info, bio, bbio,
6577 ret = raid56_parity_recover(fs_info, bio, bbio,
6578 map_length, mirror_num, 1);
6581 btrfs_bio_counter_dec(fs_info);
6582 return errno_to_blk_status(ret);
6585 if (map_length < length) {
6587 "mapping failed logical %llu bio len %llu len %llu",
6588 logical, length, map_length);
6592 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6593 dev = bbio->stripes[dev_nr].dev;
6594 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6596 (bio_op(first_bio) == REQ_OP_WRITE &&
6597 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6598 bbio_error(bbio, first_bio, logical);
6602 if (dev_nr < total_devs - 1)
6603 bio = btrfs_bio_clone(first_bio);
6607 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6608 dev_nr, async_submit);
6610 btrfs_bio_counter_dec(fs_info);
6615 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6618 * If devid and uuid are both specified, the match must be exact, otherwise
6619 * only devid is used.
6621 * If @seed is true, traverse through the seed devices.
6623 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6624 u64 devid, u8 *uuid, u8 *fsid,
6627 struct btrfs_device *device;
6629 while (fs_devices) {
6631 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6632 list_for_each_entry(device, &fs_devices->devices,
6634 if (device->devid == devid &&
6635 (!uuid || memcmp(device->uuid, uuid,
6636 BTRFS_UUID_SIZE) == 0))
6641 fs_devices = fs_devices->seed;
6648 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6649 u64 devid, u8 *dev_uuid)
6651 struct btrfs_device *device;
6653 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6657 list_add(&device->dev_list, &fs_devices->devices);
6658 device->fs_devices = fs_devices;
6659 fs_devices->num_devices++;
6661 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6662 fs_devices->missing_devices++;
6668 * btrfs_alloc_device - allocate struct btrfs_device
6669 * @fs_info: used only for generating a new devid, can be NULL if
6670 * devid is provided (i.e. @devid != NULL).
6671 * @devid: a pointer to devid for this device. If NULL a new devid
6673 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6676 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6677 * on error. Returned struct is not linked onto any lists and must be
6678 * destroyed with btrfs_free_device.
6680 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6684 struct btrfs_device *dev;
6687 if (WARN_ON(!devid && !fs_info))
6688 return ERR_PTR(-EINVAL);
6690 dev = __alloc_device();
6699 ret = find_next_devid(fs_info, &tmp);
6701 btrfs_free_device(dev);
6702 return ERR_PTR(ret);
6708 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6710 generate_random_uuid(dev->uuid);
6712 btrfs_init_work(&dev->work, btrfs_submit_helper,
6713 pending_bios_fn, NULL, NULL);
6718 /* Return -EIO if any error, otherwise return 0. */
6719 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6720 struct extent_buffer *leaf,
6721 struct btrfs_chunk *chunk, u64 logical)
6731 length = btrfs_chunk_length(leaf, chunk);
6732 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6733 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6734 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6735 type = btrfs_chunk_type(leaf, chunk);
6738 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6742 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6743 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6746 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6747 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6748 btrfs_chunk_sector_size(leaf, chunk));
6751 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6752 btrfs_err(fs_info, "invalid chunk length %llu", length);
6755 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6756 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6760 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6762 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6763 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6764 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6765 btrfs_chunk_type(leaf, chunk));
6769 if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == 0) {
6770 btrfs_err(fs_info, "missing chunk type flag: 0x%llx", type);
6774 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) &&
6775 (type & (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA))) {
6777 "system chunk with data or metadata type: 0x%llx", type);
6781 features = btrfs_super_incompat_flags(fs_info->super_copy);
6782 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
6786 if ((type & BTRFS_BLOCK_GROUP_METADATA) &&
6787 (type & BTRFS_BLOCK_GROUP_DATA)) {
6789 "mixed chunk type in non-mixed mode: 0x%llx", type);
6794 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6795 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6796 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6797 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6798 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6799 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6800 num_stripes != 1)) {
6802 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6803 num_stripes, sub_stripes,
6804 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6811 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6812 u64 devid, u8 *uuid, bool error)
6815 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6818 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6822 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6823 struct extent_buffer *leaf,
6824 struct btrfs_chunk *chunk)
6826 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6827 struct map_lookup *map;
6828 struct extent_map *em;
6832 u8 uuid[BTRFS_UUID_SIZE];
6837 logical = key->offset;
6838 length = btrfs_chunk_length(leaf, chunk);
6839 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6841 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6845 read_lock(&map_tree->map_tree.lock);
6846 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6847 read_unlock(&map_tree->map_tree.lock);
6849 /* already mapped? */
6850 if (em && em->start <= logical && em->start + em->len > logical) {
6851 free_extent_map(em);
6854 free_extent_map(em);
6857 em = alloc_extent_map();
6860 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6862 free_extent_map(em);
6866 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6867 em->map_lookup = map;
6868 em->start = logical;
6871 em->block_start = 0;
6872 em->block_len = em->len;
6874 map->num_stripes = num_stripes;
6875 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6876 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6877 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6878 map->type = btrfs_chunk_type(leaf, chunk);
6879 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6880 map->verified_stripes = 0;
6881 for (i = 0; i < num_stripes; i++) {
6882 map->stripes[i].physical =
6883 btrfs_stripe_offset_nr(leaf, chunk, i);
6884 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6885 read_extent_buffer(leaf, uuid, (unsigned long)
6886 btrfs_stripe_dev_uuid_nr(chunk, i),
6888 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6889 devid, uuid, NULL, true);
6890 if (!map->stripes[i].dev &&
6891 !btrfs_test_opt(fs_info, DEGRADED)) {
6892 free_extent_map(em);
6893 btrfs_report_missing_device(fs_info, devid, uuid, true);
6896 if (!map->stripes[i].dev) {
6897 map->stripes[i].dev =
6898 add_missing_dev(fs_info->fs_devices, devid,
6900 if (IS_ERR(map->stripes[i].dev)) {
6901 free_extent_map(em);
6903 "failed to init missing dev %llu: %ld",
6904 devid, PTR_ERR(map->stripes[i].dev));
6905 return PTR_ERR(map->stripes[i].dev);
6907 btrfs_report_missing_device(fs_info, devid, uuid, false);
6909 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6910 &(map->stripes[i].dev->dev_state));
6914 write_lock(&map_tree->map_tree.lock);
6915 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6916 write_unlock(&map_tree->map_tree.lock);
6919 "failed to add chunk map, start=%llu len=%llu: %d",
6920 em->start, em->len, ret);
6922 free_extent_map(em);
6927 static void fill_device_from_item(struct extent_buffer *leaf,
6928 struct btrfs_dev_item *dev_item,
6929 struct btrfs_device *device)
6933 device->devid = btrfs_device_id(leaf, dev_item);
6934 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6935 device->total_bytes = device->disk_total_bytes;
6936 device->commit_total_bytes = device->disk_total_bytes;
6937 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6938 device->commit_bytes_used = device->bytes_used;
6939 device->type = btrfs_device_type(leaf, dev_item);
6940 device->io_align = btrfs_device_io_align(leaf, dev_item);
6941 device->io_width = btrfs_device_io_width(leaf, dev_item);
6942 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6943 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6944 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6946 ptr = btrfs_device_uuid(dev_item);
6947 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6950 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6953 struct btrfs_fs_devices *fs_devices;
6956 lockdep_assert_held(&uuid_mutex);
6959 fs_devices = fs_info->fs_devices->seed;
6960 while (fs_devices) {
6961 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6964 fs_devices = fs_devices->seed;
6967 fs_devices = find_fsid(fsid, NULL);
6969 if (!btrfs_test_opt(fs_info, DEGRADED))
6970 return ERR_PTR(-ENOENT);
6972 fs_devices = alloc_fs_devices(fsid, NULL);
6973 if (IS_ERR(fs_devices))
6976 fs_devices->seeding = 1;
6977 fs_devices->opened = 1;
6981 fs_devices = clone_fs_devices(fs_devices);
6982 if (IS_ERR(fs_devices))
6985 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6987 free_fs_devices(fs_devices);
6988 fs_devices = ERR_PTR(ret);
6992 if (!fs_devices->seeding) {
6993 close_fs_devices(fs_devices);
6994 free_fs_devices(fs_devices);
6995 fs_devices = ERR_PTR(-EINVAL);
6999 fs_devices->seed = fs_info->fs_devices->seed;
7000 fs_info->fs_devices->seed = fs_devices;
7005 static int read_one_dev(struct btrfs_fs_info *fs_info,
7006 struct extent_buffer *leaf,
7007 struct btrfs_dev_item *dev_item)
7009 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7010 struct btrfs_device *device;
7013 u8 fs_uuid[BTRFS_FSID_SIZE];
7014 u8 dev_uuid[BTRFS_UUID_SIZE];
7016 devid = btrfs_device_id(leaf, dev_item);
7017 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7019 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7022 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7023 fs_devices = open_seed_devices(fs_info, fs_uuid);
7024 if (IS_ERR(fs_devices))
7025 return PTR_ERR(fs_devices);
7028 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
7031 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7032 btrfs_report_missing_device(fs_info, devid,
7037 device = add_missing_dev(fs_devices, devid, dev_uuid);
7038 if (IS_ERR(device)) {
7040 "failed to add missing dev %llu: %ld",
7041 devid, PTR_ERR(device));
7042 return PTR_ERR(device);
7044 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7046 if (!device->bdev) {
7047 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7048 btrfs_report_missing_device(fs_info,
7049 devid, dev_uuid, true);
7052 btrfs_report_missing_device(fs_info, devid,
7056 if (!device->bdev &&
7057 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7059 * this happens when a device that was properly setup
7060 * in the device info lists suddenly goes bad.
7061 * device->bdev is NULL, and so we have to set
7062 * device->missing to one here
7064 device->fs_devices->missing_devices++;
7065 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7068 /* Move the device to its own fs_devices */
7069 if (device->fs_devices != fs_devices) {
7070 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7071 &device->dev_state));
7073 list_move(&device->dev_list, &fs_devices->devices);
7074 device->fs_devices->num_devices--;
7075 fs_devices->num_devices++;
7077 device->fs_devices->missing_devices--;
7078 fs_devices->missing_devices++;
7080 device->fs_devices = fs_devices;
7084 if (device->fs_devices != fs_info->fs_devices) {
7085 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7086 if (device->generation !=
7087 btrfs_device_generation(leaf, dev_item))
7091 fill_device_from_item(leaf, dev_item, device);
7092 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7093 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7094 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7095 device->fs_devices->total_rw_bytes += device->total_bytes;
7096 atomic64_add(device->total_bytes - device->bytes_used,
7097 &fs_info->free_chunk_space);
7103 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7105 struct btrfs_root *root = fs_info->tree_root;
7106 struct btrfs_super_block *super_copy = fs_info->super_copy;
7107 struct extent_buffer *sb;
7108 struct btrfs_disk_key *disk_key;
7109 struct btrfs_chunk *chunk;
7111 unsigned long sb_array_offset;
7118 struct btrfs_key key;
7120 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7122 * This will create extent buffer of nodesize, superblock size is
7123 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7124 * overallocate but we can keep it as-is, only the first page is used.
7126 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
7129 set_extent_buffer_uptodate(sb);
7130 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
7132 * The sb extent buffer is artificial and just used to read the system array.
7133 * set_extent_buffer_uptodate() call does not properly mark all it's
7134 * pages up-to-date when the page is larger: extent does not cover the
7135 * whole page and consequently check_page_uptodate does not find all
7136 * the page's extents up-to-date (the hole beyond sb),
7137 * write_extent_buffer then triggers a WARN_ON.
7139 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7140 * but sb spans only this function. Add an explicit SetPageUptodate call
7141 * to silence the warning eg. on PowerPC 64.
7143 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
7144 SetPageUptodate(sb->pages[0]);
7146 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7147 array_size = btrfs_super_sys_array_size(super_copy);
7149 array_ptr = super_copy->sys_chunk_array;
7150 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7153 while (cur_offset < array_size) {
7154 disk_key = (struct btrfs_disk_key *)array_ptr;
7155 len = sizeof(*disk_key);
7156 if (cur_offset + len > array_size)
7157 goto out_short_read;
7159 btrfs_disk_key_to_cpu(&key, disk_key);
7162 sb_array_offset += len;
7165 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
7166 chunk = (struct btrfs_chunk *)sb_array_offset;
7168 * At least one btrfs_chunk with one stripe must be
7169 * present, exact stripe count check comes afterwards
7171 len = btrfs_chunk_item_size(1);
7172 if (cur_offset + len > array_size)
7173 goto out_short_read;
7175 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7178 "invalid number of stripes %u in sys_array at offset %u",
7179 num_stripes, cur_offset);
7184 type = btrfs_chunk_type(sb, chunk);
7185 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7187 "invalid chunk type %llu in sys_array at offset %u",
7193 len = btrfs_chunk_item_size(num_stripes);
7194 if (cur_offset + len > array_size)
7195 goto out_short_read;
7197 ret = read_one_chunk(fs_info, &key, sb, chunk);
7202 "unexpected item type %u in sys_array at offset %u",
7203 (u32)key.type, cur_offset);
7208 sb_array_offset += len;
7211 clear_extent_buffer_uptodate(sb);
7212 free_extent_buffer_stale(sb);
7216 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7218 clear_extent_buffer_uptodate(sb);
7219 free_extent_buffer_stale(sb);
7224 * Check if all chunks in the fs are OK for read-write degraded mount
7226 * If the @failing_dev is specified, it's accounted as missing.
7228 * Return true if all chunks meet the minimal RW mount requirements.
7229 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7231 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7232 struct btrfs_device *failing_dev)
7234 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
7235 struct extent_map *em;
7239 read_lock(&map_tree->map_tree.lock);
7240 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
7241 read_unlock(&map_tree->map_tree.lock);
7242 /* No chunk at all? Return false anyway */
7248 struct map_lookup *map;
7253 map = em->map_lookup;
7255 btrfs_get_num_tolerated_disk_barrier_failures(
7257 for (i = 0; i < map->num_stripes; i++) {
7258 struct btrfs_device *dev = map->stripes[i].dev;
7260 if (!dev || !dev->bdev ||
7261 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7262 dev->last_flush_error)
7264 else if (failing_dev && failing_dev == dev)
7267 if (missing > max_tolerated) {
7270 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7271 em->start, missing, max_tolerated);
7272 free_extent_map(em);
7276 next_start = extent_map_end(em);
7277 free_extent_map(em);
7279 read_lock(&map_tree->map_tree.lock);
7280 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
7281 (u64)(-1) - next_start);
7282 read_unlock(&map_tree->map_tree.lock);
7288 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7290 struct btrfs_root *root = fs_info->chunk_root;
7291 struct btrfs_path *path;
7292 struct extent_buffer *leaf;
7293 struct btrfs_key key;
7294 struct btrfs_key found_key;
7299 path = btrfs_alloc_path();
7304 * uuid_mutex is needed only if we are mounting a sprout FS
7305 * otherwise we don't need it.
7307 mutex_lock(&uuid_mutex);
7308 mutex_lock(&fs_info->chunk_mutex);
7311 * Read all device items, and then all the chunk items. All
7312 * device items are found before any chunk item (their object id
7313 * is smaller than the lowest possible object id for a chunk
7314 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7316 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7319 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7323 leaf = path->nodes[0];
7324 slot = path->slots[0];
7325 if (slot >= btrfs_header_nritems(leaf)) {
7326 ret = btrfs_next_leaf(root, path);
7333 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7334 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7335 struct btrfs_dev_item *dev_item;
7336 dev_item = btrfs_item_ptr(leaf, slot,
7337 struct btrfs_dev_item);
7338 ret = read_one_dev(fs_info, leaf, dev_item);
7342 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7343 struct btrfs_chunk *chunk;
7344 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7345 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
7353 * After loading chunk tree, we've got all device information,
7354 * do another round of validation checks.
7356 if (total_dev != fs_info->fs_devices->total_devices) {
7358 "super_num_devices %llu mismatch with num_devices %llu found here",
7359 btrfs_super_num_devices(fs_info->super_copy),
7364 if (btrfs_super_total_bytes(fs_info->super_copy) <
7365 fs_info->fs_devices->total_rw_bytes) {
7367 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7368 btrfs_super_total_bytes(fs_info->super_copy),
7369 fs_info->fs_devices->total_rw_bytes);
7375 mutex_unlock(&fs_info->chunk_mutex);
7376 mutex_unlock(&uuid_mutex);
7378 btrfs_free_path(path);
7382 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7384 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7385 struct btrfs_device *device;
7387 while (fs_devices) {
7388 mutex_lock(&fs_devices->device_list_mutex);
7389 list_for_each_entry(device, &fs_devices->devices, dev_list)
7390 device->fs_info = fs_info;
7391 mutex_unlock(&fs_devices->device_list_mutex);
7393 fs_devices = fs_devices->seed;
7397 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7401 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7402 btrfs_dev_stat_reset(dev, i);
7405 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7407 struct btrfs_key key;
7408 struct btrfs_key found_key;
7409 struct btrfs_root *dev_root = fs_info->dev_root;
7410 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7411 struct extent_buffer *eb;
7414 struct btrfs_device *device;
7415 struct btrfs_path *path = NULL;
7418 path = btrfs_alloc_path();
7424 mutex_lock(&fs_devices->device_list_mutex);
7425 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7427 struct btrfs_dev_stats_item *ptr;
7429 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7430 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7431 key.offset = device->devid;
7432 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7434 __btrfs_reset_dev_stats(device);
7435 device->dev_stats_valid = 1;
7436 btrfs_release_path(path);
7439 slot = path->slots[0];
7440 eb = path->nodes[0];
7441 btrfs_item_key_to_cpu(eb, &found_key, slot);
7442 item_size = btrfs_item_size_nr(eb, slot);
7444 ptr = btrfs_item_ptr(eb, slot,
7445 struct btrfs_dev_stats_item);
7447 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7448 if (item_size >= (1 + i) * sizeof(__le64))
7449 btrfs_dev_stat_set(device, i,
7450 btrfs_dev_stats_value(eb, ptr, i));
7452 btrfs_dev_stat_reset(device, i);
7455 device->dev_stats_valid = 1;
7456 btrfs_dev_stat_print_on_load(device);
7457 btrfs_release_path(path);
7459 mutex_unlock(&fs_devices->device_list_mutex);
7462 btrfs_free_path(path);
7463 return ret < 0 ? ret : 0;
7466 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7467 struct btrfs_device *device)
7469 struct btrfs_fs_info *fs_info = trans->fs_info;
7470 struct btrfs_root *dev_root = fs_info->dev_root;
7471 struct btrfs_path *path;
7472 struct btrfs_key key;
7473 struct extent_buffer *eb;
7474 struct btrfs_dev_stats_item *ptr;
7478 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7479 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7480 key.offset = device->devid;
7482 path = btrfs_alloc_path();
7485 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7487 btrfs_warn_in_rcu(fs_info,
7488 "error %d while searching for dev_stats item for device %s",
7489 ret, rcu_str_deref(device->name));
7494 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7495 /* need to delete old one and insert a new one */
7496 ret = btrfs_del_item(trans, dev_root, path);
7498 btrfs_warn_in_rcu(fs_info,
7499 "delete too small dev_stats item for device %s failed %d",
7500 rcu_str_deref(device->name), ret);
7507 /* need to insert a new item */
7508 btrfs_release_path(path);
7509 ret = btrfs_insert_empty_item(trans, dev_root, path,
7510 &key, sizeof(*ptr));
7512 btrfs_warn_in_rcu(fs_info,
7513 "insert dev_stats item for device %s failed %d",
7514 rcu_str_deref(device->name), ret);
7519 eb = path->nodes[0];
7520 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7521 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7522 btrfs_set_dev_stats_value(eb, ptr, i,
7523 btrfs_dev_stat_read(device, i));
7524 btrfs_mark_buffer_dirty(eb);
7527 btrfs_free_path(path);
7532 * called from commit_transaction. Writes all changed device stats to disk.
7534 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7535 struct btrfs_fs_info *fs_info)
7537 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7538 struct btrfs_device *device;
7542 mutex_lock(&fs_devices->device_list_mutex);
7543 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7544 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7545 if (!device->dev_stats_valid || stats_cnt == 0)
7550 * There is a LOAD-LOAD control dependency between the value of
7551 * dev_stats_ccnt and updating the on-disk values which requires
7552 * reading the in-memory counters. Such control dependencies
7553 * require explicit read memory barriers.
7555 * This memory barriers pairs with smp_mb__before_atomic in
7556 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7557 * barrier implied by atomic_xchg in
7558 * btrfs_dev_stats_read_and_reset
7562 ret = update_dev_stat_item(trans, device);
7564 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7566 mutex_unlock(&fs_devices->device_list_mutex);
7571 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7573 btrfs_dev_stat_inc(dev, index);
7574 btrfs_dev_stat_print_on_error(dev);
7577 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7579 if (!dev->dev_stats_valid)
7581 btrfs_err_rl_in_rcu(dev->fs_info,
7582 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7583 rcu_str_deref(dev->name),
7584 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7585 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7586 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7587 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7588 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7591 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7595 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7596 if (btrfs_dev_stat_read(dev, i) != 0)
7598 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7599 return; /* all values == 0, suppress message */
7601 btrfs_info_in_rcu(dev->fs_info,
7602 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7603 rcu_str_deref(dev->name),
7604 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7605 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7606 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7607 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7608 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7611 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7612 struct btrfs_ioctl_get_dev_stats *stats)
7614 struct btrfs_device *dev;
7615 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7618 mutex_lock(&fs_devices->device_list_mutex);
7619 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7621 mutex_unlock(&fs_devices->device_list_mutex);
7624 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7626 } else if (!dev->dev_stats_valid) {
7627 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7629 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7630 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7631 if (stats->nr_items > i)
7633 btrfs_dev_stat_read_and_reset(dev, i);
7635 btrfs_dev_stat_reset(dev, i);
7638 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7639 if (stats->nr_items > i)
7640 stats->values[i] = btrfs_dev_stat_read(dev, i);
7642 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7643 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7647 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7649 struct buffer_head *bh;
7650 struct btrfs_super_block *disk_super;
7656 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7659 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7662 disk_super = (struct btrfs_super_block *)bh->b_data;
7664 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7665 set_buffer_dirty(bh);
7666 sync_dirty_buffer(bh);
7670 /* Notify udev that device has changed */
7671 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7673 /* Update ctime/mtime for device path for libblkid */
7674 update_dev_time(device_path);
7678 * Update the size of all devices, which is used for writing out the
7681 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7683 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7684 struct btrfs_device *curr, *next;
7686 if (list_empty(&fs_devices->resized_devices))
7689 mutex_lock(&fs_devices->device_list_mutex);
7690 mutex_lock(&fs_info->chunk_mutex);
7691 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7693 list_del_init(&curr->resized_list);
7694 curr->commit_total_bytes = curr->disk_total_bytes;
7696 mutex_unlock(&fs_info->chunk_mutex);
7697 mutex_unlock(&fs_devices->device_list_mutex);
7700 /* Must be invoked during the transaction commit */
7701 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7703 struct btrfs_fs_info *fs_info = trans->fs_info;
7704 struct extent_map *em;
7705 struct map_lookup *map;
7706 struct btrfs_device *dev;
7709 if (list_empty(&trans->pending_chunks))
7712 /* In order to kick the device replace finish process */
7713 mutex_lock(&fs_info->chunk_mutex);
7714 list_for_each_entry(em, &trans->pending_chunks, list) {
7715 map = em->map_lookup;
7717 for (i = 0; i < map->num_stripes; i++) {
7718 dev = map->stripes[i].dev;
7719 dev->commit_bytes_used = dev->bytes_used;
7722 mutex_unlock(&fs_info->chunk_mutex);
7725 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7727 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7728 while (fs_devices) {
7729 fs_devices->fs_info = fs_info;
7730 fs_devices = fs_devices->seed;
7734 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7736 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7737 while (fs_devices) {
7738 fs_devices->fs_info = NULL;
7739 fs_devices = fs_devices->seed;
7744 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7746 int btrfs_bg_type_to_factor(u64 flags)
7748 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
7749 BTRFS_BLOCK_GROUP_RAID10))
7755 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
7757 int index = btrfs_bg_flags_to_raid_index(type);
7758 int ncopies = btrfs_raid_array[index].ncopies;
7761 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
7762 case BTRFS_BLOCK_GROUP_RAID5:
7763 data_stripes = num_stripes - 1;
7765 case BTRFS_BLOCK_GROUP_RAID6:
7766 data_stripes = num_stripes - 2;
7769 data_stripes = num_stripes / ncopies;
7772 return div_u64(chunk_len, data_stripes);
7775 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7776 u64 chunk_offset, u64 devid,
7777 u64 physical_offset, u64 physical_len)
7779 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7780 struct extent_map *em;
7781 struct map_lookup *map;
7782 struct btrfs_device *dev;
7788 read_lock(&em_tree->lock);
7789 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7790 read_unlock(&em_tree->lock);
7794 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7795 physical_offset, devid);
7800 map = em->map_lookup;
7801 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7802 if (physical_len != stripe_len) {
7804 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7805 physical_offset, devid, em->start, physical_len,
7811 for (i = 0; i < map->num_stripes; i++) {
7812 if (map->stripes[i].dev->devid == devid &&
7813 map->stripes[i].physical == physical_offset) {
7815 if (map->verified_stripes >= map->num_stripes) {
7817 "too many dev extents for chunk %llu found",
7822 map->verified_stripes++;
7828 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7829 physical_offset, devid);
7833 /* Make sure no dev extent is beyond device bondary */
7834 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7836 btrfs_err(fs_info, "failed to find devid %llu", devid);
7841 /* It's possible this device is a dummy for seed device */
7842 if (dev->disk_total_bytes == 0) {
7843 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7846 btrfs_err(fs_info, "failed to find seed devid %llu",
7853 if (physical_offset + physical_len > dev->disk_total_bytes) {
7855 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7856 devid, physical_offset, physical_len,
7857 dev->disk_total_bytes);
7862 free_extent_map(em);
7866 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7868 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7869 struct extent_map *em;
7870 struct rb_node *node;
7873 read_lock(&em_tree->lock);
7874 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7875 em = rb_entry(node, struct extent_map, rb_node);
7876 if (em->map_lookup->num_stripes !=
7877 em->map_lookup->verified_stripes) {
7879 "chunk %llu has missing dev extent, have %d expect %d",
7880 em->start, em->map_lookup->verified_stripes,
7881 em->map_lookup->num_stripes);
7887 read_unlock(&em_tree->lock);
7892 * Ensure that all dev extents are mapped to correct chunk, otherwise
7893 * later chunk allocation/free would cause unexpected behavior.
7895 * NOTE: This will iterate through the whole device tree, which should be of
7896 * the same size level as the chunk tree. This slightly increases mount time.
7898 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7900 struct btrfs_path *path;
7901 struct btrfs_root *root = fs_info->dev_root;
7902 struct btrfs_key key;
7904 u64 prev_dev_ext_end = 0;
7908 key.type = BTRFS_DEV_EXTENT_KEY;
7911 path = btrfs_alloc_path();
7915 path->reada = READA_FORWARD;
7916 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7920 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7921 ret = btrfs_next_item(root, path);
7924 /* No dev extents at all? Not good */
7931 struct extent_buffer *leaf = path->nodes[0];
7932 struct btrfs_dev_extent *dext;
7933 int slot = path->slots[0];
7935 u64 physical_offset;
7939 btrfs_item_key_to_cpu(leaf, &key, slot);
7940 if (key.type != BTRFS_DEV_EXTENT_KEY)
7942 devid = key.objectid;
7943 physical_offset = key.offset;
7945 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7946 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7947 physical_len = btrfs_dev_extent_length(leaf, dext);
7949 /* Check if this dev extent overlaps with the previous one */
7950 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7952 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7953 devid, physical_offset, prev_dev_ext_end);
7958 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7959 physical_offset, physical_len);
7963 prev_dev_ext_end = physical_offset + physical_len;
7965 ret = btrfs_next_item(root, path);
7974 /* Ensure all chunks have corresponding dev extents */
7975 ret = verify_chunk_dev_extent_mapping(fs_info);
7977 btrfs_free_path(path);
7982 * Check whether the given block group or device is pinned by any inode being
7983 * used as a swapfile.
7985 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7987 struct btrfs_swapfile_pin *sp;
7988 struct rb_node *node;
7990 spin_lock(&fs_info->swapfile_pins_lock);
7991 node = fs_info->swapfile_pins.rb_node;
7993 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7995 node = node->rb_left;
7996 else if (ptr > sp->ptr)
7997 node = node->rb_right;
8001 spin_unlock(&fs_info->swapfile_pins_lock);
8002 return node != NULL;