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"
30 #include "tree-checker.h"
32 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
33 [BTRFS_RAID_RAID10] = {
36 .devs_max = 0, /* 0 == as many as possible */
38 .tolerated_failures = 1,
42 .raid_name = "raid10",
43 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
44 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
46 [BTRFS_RAID_RAID1] = {
51 .tolerated_failures = 1,
56 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
57 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
64 .tolerated_failures = 0,
69 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
72 [BTRFS_RAID_RAID0] = {
77 .tolerated_failures = 0,
82 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
85 [BTRFS_RAID_SINGLE] = {
90 .tolerated_failures = 0,
94 .raid_name = "single",
98 [BTRFS_RAID_RAID5] = {
103 .tolerated_failures = 1,
107 .raid_name = "raid5",
108 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
109 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
111 [BTRFS_RAID_RAID6] = {
116 .tolerated_failures = 2,
120 .raid_name = "raid6",
121 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
122 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
126 const char *get_raid_name(enum btrfs_raid_types type)
128 if (type >= BTRFS_NR_RAID_TYPES)
131 return btrfs_raid_array[type].raid_name;
135 * Fill @buf with textual description of @bg_flags, no more than @size_buf
136 * bytes including terminating null byte.
138 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
143 u64 flags = bg_flags;
144 u32 size_bp = size_buf;
151 #define DESCRIBE_FLAG(flag, desc) \
153 if (flags & (flag)) { \
154 ret = snprintf(bp, size_bp, "%s|", (desc)); \
155 if (ret < 0 || ret >= size_bp) \
163 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
164 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
165 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
167 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
168 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
169 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
170 btrfs_raid_array[i].raid_name);
174 ret = snprintf(bp, size_bp, "0x%llx|", flags);
178 if (size_bp < size_buf)
179 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
182 * The text is trimmed, it's up to the caller to provide sufficiently
188 static int init_first_rw_device(struct btrfs_trans_handle *trans,
189 struct btrfs_fs_info *fs_info);
190 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
191 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
192 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
193 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
194 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
195 enum btrfs_map_op op,
196 u64 logical, u64 *length,
197 struct btrfs_bio **bbio_ret,
198 int mirror_num, int need_raid_map);
204 * There are several mutexes that protect manipulation of devices and low-level
205 * structures like chunks but not block groups, extents or files
207 * uuid_mutex (global lock)
208 * ------------------------
209 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
210 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
211 * device) or requested by the device= mount option
213 * the mutex can be very coarse and can cover long-running operations
215 * protects: updates to fs_devices counters like missing devices, rw devices,
216 * seeding, structure cloning, opening/closing devices at mount/umount time
218 * global::fs_devs - add, remove, updates to the global list
220 * does not protect: manipulation of the fs_devices::devices list!
222 * btrfs_device::name - renames (write side), read is RCU
224 * fs_devices::device_list_mutex (per-fs, with RCU)
225 * ------------------------------------------------
226 * protects updates to fs_devices::devices, ie. adding and deleting
228 * simple list traversal with read-only actions can be done with RCU protection
230 * may be used to exclude some operations from running concurrently without any
231 * modifications to the list (see write_all_supers)
235 * protects balance structures (status, state) and context accessed from
236 * several places (internally, ioctl)
240 * protects chunks, adding or removing during allocation, trim or when a new
241 * device is added/removed
245 * a big lock that is held by the cleaner thread and prevents running subvolume
246 * cleaning together with relocation or delayed iputs
259 * Exclusive operations, BTRFS_FS_EXCL_OP
260 * ======================================
262 * Maintains the exclusivity of the following operations that apply to the
263 * whole filesystem and cannot run in parallel.
268 * - Device replace (*)
271 * The device operations (as above) can be in one of the following states:
277 * Only device operations marked with (*) can go into the Paused state for the
280 * - ioctl (only Balance can be Paused through ioctl)
281 * - filesystem remounted as read-only
282 * - filesystem unmounted and mounted as read-only
283 * - system power-cycle and filesystem mounted as read-only
284 * - filesystem or device errors leading to forced read-only
286 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
287 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
288 * A device operation in Paused or Running state can be canceled or resumed
289 * either by ioctl (Balance only) or when remounted as read-write.
290 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
294 DEFINE_MUTEX(uuid_mutex);
295 static LIST_HEAD(fs_uuids);
296 struct list_head *btrfs_get_fs_uuids(void)
302 * alloc_fs_devices - allocate struct btrfs_fs_devices
303 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
304 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
306 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
307 * The returned struct is not linked onto any lists and can be destroyed with
308 * kfree() right away.
310 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
311 const u8 *metadata_fsid)
313 struct btrfs_fs_devices *fs_devs;
315 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
317 return ERR_PTR(-ENOMEM);
319 mutex_init(&fs_devs->device_list_mutex);
321 INIT_LIST_HEAD(&fs_devs->devices);
322 INIT_LIST_HEAD(&fs_devs->resized_devices);
323 INIT_LIST_HEAD(&fs_devs->alloc_list);
324 INIT_LIST_HEAD(&fs_devs->fs_list);
326 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
329 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
331 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
336 void btrfs_free_device(struct btrfs_device *device)
338 rcu_string_free(device->name);
339 bio_put(device->flush_bio);
343 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
345 struct btrfs_device *device;
346 WARN_ON(fs_devices->opened);
347 while (!list_empty(&fs_devices->devices)) {
348 device = list_entry(fs_devices->devices.next,
349 struct btrfs_device, dev_list);
350 list_del(&device->dev_list);
351 btrfs_free_device(device);
356 static void btrfs_kobject_uevent(struct block_device *bdev,
357 enum kobject_action action)
361 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
363 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
365 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
366 &disk_to_dev(bdev->bd_disk)->kobj);
369 void __exit btrfs_cleanup_fs_uuids(void)
371 struct btrfs_fs_devices *fs_devices;
373 while (!list_empty(&fs_uuids)) {
374 fs_devices = list_entry(fs_uuids.next,
375 struct btrfs_fs_devices, fs_list);
376 list_del(&fs_devices->fs_list);
377 free_fs_devices(fs_devices);
382 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
383 * Returned struct is not linked onto any lists and must be destroyed using
386 static struct btrfs_device *__alloc_device(void)
388 struct btrfs_device *dev;
390 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
392 return ERR_PTR(-ENOMEM);
395 * Preallocate a bio that's always going to be used for flushing device
396 * barriers and matches the device lifespan
398 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
399 if (!dev->flush_bio) {
401 return ERR_PTR(-ENOMEM);
404 INIT_LIST_HEAD(&dev->dev_list);
405 INIT_LIST_HEAD(&dev->dev_alloc_list);
406 INIT_LIST_HEAD(&dev->resized_list);
408 spin_lock_init(&dev->io_lock);
410 atomic_set(&dev->reada_in_flight, 0);
411 atomic_set(&dev->dev_stats_ccnt, 0);
412 btrfs_device_data_ordered_init(dev);
413 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
414 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
419 static noinline struct btrfs_fs_devices *find_fsid(
420 const u8 *fsid, const u8 *metadata_fsid)
422 struct btrfs_fs_devices *fs_devices;
428 * Handle scanned device having completed its fsid change but
429 * belonging to a fs_devices that was created by first scanning
430 * a device which didn't have its fsid/metadata_uuid changed
431 * at all and the CHANGING_FSID_V2 flag set.
433 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
434 if (fs_devices->fsid_change &&
435 memcmp(metadata_fsid, fs_devices->fsid,
436 BTRFS_FSID_SIZE) == 0 &&
437 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
438 BTRFS_FSID_SIZE) == 0) {
443 * Handle scanned device having completed its fsid change but
444 * belonging to a fs_devices that was created by a device that
445 * has an outdated pair of fsid/metadata_uuid and
446 * CHANGING_FSID_V2 flag set.
448 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
449 if (fs_devices->fsid_change &&
450 memcmp(fs_devices->metadata_uuid,
451 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
452 memcmp(metadata_fsid, fs_devices->metadata_uuid,
453 BTRFS_FSID_SIZE) == 0) {
459 /* Handle non-split brain cases */
460 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
462 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
463 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
464 BTRFS_FSID_SIZE) == 0)
467 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
475 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
476 int flush, struct block_device **bdev,
477 struct buffer_head **bh)
481 *bdev = blkdev_get_by_path(device_path, flags, holder);
484 ret = PTR_ERR(*bdev);
489 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
490 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
492 blkdev_put(*bdev, flags);
495 invalidate_bdev(*bdev);
496 *bh = btrfs_read_dev_super(*bdev);
499 blkdev_put(*bdev, flags);
511 static void requeue_list(struct btrfs_pending_bios *pending_bios,
512 struct bio *head, struct bio *tail)
515 struct bio *old_head;
517 old_head = pending_bios->head;
518 pending_bios->head = head;
519 if (pending_bios->tail)
520 tail->bi_next = old_head;
522 pending_bios->tail = tail;
526 * we try to collect pending bios for a device so we don't get a large
527 * number of procs sending bios down to the same device. This greatly
528 * improves the schedulers ability to collect and merge the bios.
530 * But, it also turns into a long list of bios to process and that is sure
531 * to eventually make the worker thread block. The solution here is to
532 * make some progress and then put this work struct back at the end of
533 * the list if the block device is congested. This way, multiple devices
534 * can make progress from a single worker thread.
536 static noinline void run_scheduled_bios(struct btrfs_device *device)
538 struct btrfs_fs_info *fs_info = device->fs_info;
540 struct backing_dev_info *bdi;
541 struct btrfs_pending_bios *pending_bios;
545 unsigned long num_run;
546 unsigned long batch_run = 0;
547 unsigned long last_waited = 0;
549 int sync_pending = 0;
550 struct blk_plug plug;
553 * this function runs all the bios we've collected for
554 * a particular device. We don't want to wander off to
555 * another device without first sending all of these down.
556 * So, setup a plug here and finish it off before we return
558 blk_start_plug(&plug);
560 bdi = device->bdev->bd_bdi;
563 spin_lock(&device->io_lock);
568 /* take all the bios off the list at once and process them
569 * later on (without the lock held). But, remember the
570 * tail and other pointers so the bios can be properly reinserted
571 * into the list if we hit congestion
573 if (!force_reg && device->pending_sync_bios.head) {
574 pending_bios = &device->pending_sync_bios;
577 pending_bios = &device->pending_bios;
581 pending = pending_bios->head;
582 tail = pending_bios->tail;
583 WARN_ON(pending && !tail);
586 * if pending was null this time around, no bios need processing
587 * at all and we can stop. Otherwise it'll loop back up again
588 * and do an additional check so no bios are missed.
590 * device->running_pending is used to synchronize with the
593 if (device->pending_sync_bios.head == NULL &&
594 device->pending_bios.head == NULL) {
596 device->running_pending = 0;
599 device->running_pending = 1;
602 pending_bios->head = NULL;
603 pending_bios->tail = NULL;
605 spin_unlock(&device->io_lock);
610 /* we want to work on both lists, but do more bios on the
611 * sync list than the regular list
614 pending_bios != &device->pending_sync_bios &&
615 device->pending_sync_bios.head) ||
616 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
617 device->pending_bios.head)) {
618 spin_lock(&device->io_lock);
619 requeue_list(pending_bios, pending, tail);
624 pending = pending->bi_next;
627 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
630 * if we're doing the sync list, record that our
631 * plug has some sync requests on it
633 * If we're doing the regular list and there are
634 * sync requests sitting around, unplug before
637 if (pending_bios == &device->pending_sync_bios) {
639 } else if (sync_pending) {
640 blk_finish_plug(&plug);
641 blk_start_plug(&plug);
645 btrfsic_submit_bio(cur);
652 * we made progress, there is more work to do and the bdi
653 * is now congested. Back off and let other work structs
656 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
657 fs_info->fs_devices->open_devices > 1) {
658 struct io_context *ioc;
660 ioc = current->io_context;
663 * the main goal here is that we don't want to
664 * block if we're going to be able to submit
665 * more requests without blocking.
667 * This code does two great things, it pokes into
668 * the elevator code from a filesystem _and_
669 * it makes assumptions about how batching works.
671 if (ioc && ioc->nr_batch_requests > 0 &&
672 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
674 ioc->last_waited == last_waited)) {
676 * we want to go through our batch of
677 * requests and stop. So, we copy out
678 * the ioc->last_waited time and test
679 * against it before looping
681 last_waited = ioc->last_waited;
685 spin_lock(&device->io_lock);
686 requeue_list(pending_bios, pending, tail);
687 device->running_pending = 1;
689 spin_unlock(&device->io_lock);
690 btrfs_queue_work(fs_info->submit_workers,
700 spin_lock(&device->io_lock);
701 if (device->pending_bios.head || device->pending_sync_bios.head)
703 spin_unlock(&device->io_lock);
706 blk_finish_plug(&plug);
709 static void pending_bios_fn(struct btrfs_work *work)
711 struct btrfs_device *device;
713 device = container_of(work, struct btrfs_device, work);
714 run_scheduled_bios(device);
717 static bool device_path_matched(const char *path, struct btrfs_device *device)
722 found = strcmp(rcu_str_deref(device->name), path);
729 * Search and remove all stale (devices which are not mounted) devices.
730 * When both inputs are NULL, it will search and release all stale devices.
731 * path: Optional. When provided will it release all unmounted devices
732 * matching this path only.
733 * skip_dev: Optional. Will skip this device when searching for the stale
735 * Return: 0 for success or if @path is NULL.
736 * -EBUSY if @path is a mounted device.
737 * -ENOENT if @path does not match any device in the list.
739 static int btrfs_free_stale_devices(const char *path,
740 struct btrfs_device *skip_device)
742 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
743 struct btrfs_device *device, *tmp_device;
749 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
751 mutex_lock(&fs_devices->device_list_mutex);
752 list_for_each_entry_safe(device, tmp_device,
753 &fs_devices->devices, dev_list) {
754 if (skip_device && skip_device == device)
756 if (path && !device->name)
758 if (path && !device_path_matched(path, device))
760 if (fs_devices->opened) {
761 /* for an already deleted device return 0 */
762 if (path && ret != 0)
767 /* delete the stale device */
768 fs_devices->num_devices--;
769 list_del(&device->dev_list);
770 btrfs_free_device(device);
773 if (fs_devices->num_devices == 0)
776 mutex_unlock(&fs_devices->device_list_mutex);
778 if (fs_devices->num_devices == 0) {
779 btrfs_sysfs_remove_fsid(fs_devices);
780 list_del(&fs_devices->fs_list);
781 free_fs_devices(fs_devices);
788 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
789 struct btrfs_device *device, fmode_t flags,
792 struct request_queue *q;
793 struct block_device *bdev;
794 struct buffer_head *bh;
795 struct btrfs_super_block *disk_super;
804 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
809 disk_super = (struct btrfs_super_block *)bh->b_data;
810 devid = btrfs_stack_device_id(&disk_super->dev_item);
811 if (devid != device->devid)
814 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
817 device->generation = btrfs_super_generation(disk_super);
819 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
820 if (btrfs_super_incompat_flags(disk_super) &
821 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
823 "BTRFS: Invalid seeding and uuid-changed device detected\n");
827 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
828 fs_devices->seeding = 1;
830 if (bdev_read_only(bdev))
831 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
833 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
836 q = bdev_get_queue(bdev);
837 if (!blk_queue_nonrot(q))
838 fs_devices->rotating = 1;
841 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
842 device->mode = flags;
844 fs_devices->open_devices++;
845 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
846 device->devid != BTRFS_DEV_REPLACE_DEVID) {
847 fs_devices->rw_devices++;
848 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
856 blkdev_put(bdev, flags);
862 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
863 * being created with a disk that has already completed its fsid change.
865 static struct btrfs_fs_devices *find_fsid_inprogress(
866 struct btrfs_super_block *disk_super)
868 struct btrfs_fs_devices *fs_devices;
870 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
871 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
872 BTRFS_FSID_SIZE) != 0 &&
873 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
874 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
883 static struct btrfs_fs_devices *find_fsid_changed(
884 struct btrfs_super_block *disk_super)
886 struct btrfs_fs_devices *fs_devices;
889 * Handles the case where scanned device is part of an fs that had
890 * multiple successful changes of FSID but curently device didn't
891 * observe it. Meaning our fsid will be different than theirs.
893 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
894 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
895 BTRFS_FSID_SIZE) != 0 &&
896 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
897 BTRFS_FSID_SIZE) == 0 &&
898 memcmp(fs_devices->fsid, disk_super->fsid,
899 BTRFS_FSID_SIZE) != 0) {
907 * Add new device to list of registered devices
910 * device pointer which was just added or updated when successful
911 * error pointer when failed
913 static noinline struct btrfs_device *device_list_add(const char *path,
914 struct btrfs_super_block *disk_super,
915 bool *new_device_added)
917 struct btrfs_device *device;
918 struct btrfs_fs_devices *fs_devices = NULL;
919 struct rcu_string *name;
920 u64 found_transid = btrfs_super_generation(disk_super);
921 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
922 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
923 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
924 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
925 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
927 if (fsid_change_in_progress) {
928 if (!has_metadata_uuid) {
930 * When we have an image which has CHANGING_FSID_V2 set
931 * it might belong to either a filesystem which has
932 * disks with completed fsid change or it might belong
933 * to fs with no UUID changes in effect, handle both.
935 fs_devices = find_fsid_inprogress(disk_super);
937 fs_devices = find_fsid(disk_super->fsid, NULL);
939 fs_devices = find_fsid_changed(disk_super);
941 } else if (has_metadata_uuid) {
942 fs_devices = find_fsid(disk_super->fsid,
943 disk_super->metadata_uuid);
945 fs_devices = find_fsid(disk_super->fsid, NULL);
950 if (has_metadata_uuid)
951 fs_devices = alloc_fs_devices(disk_super->fsid,
952 disk_super->metadata_uuid);
954 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
956 if (IS_ERR(fs_devices))
957 return ERR_CAST(fs_devices);
959 fs_devices->fsid_change = fsid_change_in_progress;
961 mutex_lock(&fs_devices->device_list_mutex);
962 list_add(&fs_devices->fs_list, &fs_uuids);
966 mutex_lock(&fs_devices->device_list_mutex);
967 device = btrfs_find_device(fs_devices, devid,
968 disk_super->dev_item.uuid, NULL, false);
971 * If this disk has been pulled into an fs devices created by
972 * a device which had the CHANGING_FSID_V2 flag then replace the
973 * metadata_uuid/fsid values of the fs_devices.
975 if (has_metadata_uuid && fs_devices->fsid_change &&
976 found_transid > fs_devices->latest_generation) {
977 memcpy(fs_devices->fsid, disk_super->fsid,
979 memcpy(fs_devices->metadata_uuid,
980 disk_super->metadata_uuid, BTRFS_FSID_SIZE);
982 fs_devices->fsid_change = false;
987 if (fs_devices->opened) {
988 mutex_unlock(&fs_devices->device_list_mutex);
989 return ERR_PTR(-EBUSY);
992 device = btrfs_alloc_device(NULL, &devid,
993 disk_super->dev_item.uuid);
994 if (IS_ERR(device)) {
995 mutex_unlock(&fs_devices->device_list_mutex);
996 /* we can safely leave the fs_devices entry around */
1000 name = rcu_string_strdup(path, GFP_NOFS);
1002 btrfs_free_device(device);
1003 mutex_unlock(&fs_devices->device_list_mutex);
1004 return ERR_PTR(-ENOMEM);
1006 rcu_assign_pointer(device->name, name);
1008 list_add_rcu(&device->dev_list, &fs_devices->devices);
1009 fs_devices->num_devices++;
1011 device->fs_devices = fs_devices;
1012 *new_device_added = true;
1014 if (disk_super->label[0])
1015 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
1016 disk_super->label, devid, found_transid, path);
1018 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
1019 disk_super->fsid, devid, found_transid, path);
1021 } else if (!device->name || strcmp(device->name->str, path)) {
1023 * When FS is already mounted.
1024 * 1. If you are here and if the device->name is NULL that
1025 * means this device was missing at time of FS mount.
1026 * 2. If you are here and if the device->name is different
1027 * from 'path' that means either
1028 * a. The same device disappeared and reappeared with
1029 * different name. or
1030 * b. The missing-disk-which-was-replaced, has
1033 * We must allow 1 and 2a above. But 2b would be a spurious
1034 * and unintentional.
1036 * Further in case of 1 and 2a above, the disk at 'path'
1037 * would have missed some transaction when it was away and
1038 * in case of 2a the stale bdev has to be updated as well.
1039 * 2b must not be allowed at all time.
1043 * For now, we do allow update to btrfs_fs_device through the
1044 * btrfs dev scan cli after FS has been mounted. We're still
1045 * tracking a problem where systems fail mount by subvolume id
1046 * when we reject replacement on a mounted FS.
1048 if (!fs_devices->opened && found_transid < device->generation) {
1050 * That is if the FS is _not_ mounted and if you
1051 * are here, that means there is more than one
1052 * disk with same uuid and devid.We keep the one
1053 * with larger generation number or the last-in if
1054 * generation are equal.
1056 mutex_unlock(&fs_devices->device_list_mutex);
1057 return ERR_PTR(-EEXIST);
1061 * We are going to replace the device path for a given devid,
1062 * make sure it's the same device if the device is mounted
1065 struct block_device *path_bdev;
1067 path_bdev = lookup_bdev(path);
1068 if (IS_ERR(path_bdev)) {
1069 mutex_unlock(&fs_devices->device_list_mutex);
1070 return ERR_CAST(path_bdev);
1073 if (device->bdev != path_bdev) {
1075 mutex_unlock(&fs_devices->device_list_mutex);
1076 btrfs_warn_in_rcu(device->fs_info,
1077 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
1078 disk_super->fsid, devid,
1079 rcu_str_deref(device->name), path);
1080 return ERR_PTR(-EEXIST);
1083 btrfs_info_in_rcu(device->fs_info,
1084 "device fsid %pU devid %llu moved old:%s new:%s",
1085 disk_super->fsid, devid,
1086 rcu_str_deref(device->name), path);
1089 name = rcu_string_strdup(path, GFP_NOFS);
1091 mutex_unlock(&fs_devices->device_list_mutex);
1092 return ERR_PTR(-ENOMEM);
1094 rcu_string_free(device->name);
1095 rcu_assign_pointer(device->name, name);
1096 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1097 fs_devices->missing_devices--;
1098 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1103 * Unmount does not free the btrfs_device struct but would zero
1104 * generation along with most of the other members. So just update
1105 * it back. We need it to pick the disk with largest generation
1108 if (!fs_devices->opened) {
1109 device->generation = found_transid;
1110 fs_devices->latest_generation = max_t(u64, found_transid,
1111 fs_devices->latest_generation);
1114 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
1116 mutex_unlock(&fs_devices->device_list_mutex);
1120 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1122 struct btrfs_fs_devices *fs_devices;
1123 struct btrfs_device *device;
1124 struct btrfs_device *orig_dev;
1126 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1127 if (IS_ERR(fs_devices))
1130 mutex_lock(&orig->device_list_mutex);
1131 fs_devices->total_devices = orig->total_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 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4962 u64 start, u64 type)
4964 struct btrfs_fs_info *info = trans->fs_info;
4965 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4966 struct btrfs_device *device;
4967 struct map_lookup *map = NULL;
4968 struct extent_map_tree *em_tree;
4969 struct extent_map *em;
4970 struct btrfs_device_info *devices_info = NULL;
4972 int num_stripes; /* total number of stripes to allocate */
4973 int data_stripes; /* number of stripes that count for
4975 int sub_stripes; /* sub_stripes info for map */
4976 int dev_stripes; /* stripes per dev */
4977 int devs_max; /* max devs to use */
4978 int devs_min; /* min devs needed */
4979 int devs_increment; /* ndevs has to be a multiple of this */
4980 int ncopies; /* how many copies to data has */
4981 int nparity; /* number of stripes worth of bytes to
4982 store parity information */
4984 u64 max_stripe_size;
4993 BUG_ON(!alloc_profile_is_valid(type, 0));
4995 if (list_empty(&fs_devices->alloc_list)) {
4996 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4997 btrfs_debug(info, "%s: no writable device", __func__);
5001 index = btrfs_bg_flags_to_raid_index(type);
5003 sub_stripes = btrfs_raid_array[index].sub_stripes;
5004 dev_stripes = btrfs_raid_array[index].dev_stripes;
5005 devs_max = btrfs_raid_array[index].devs_max;
5006 devs_min = btrfs_raid_array[index].devs_min;
5007 devs_increment = btrfs_raid_array[index].devs_increment;
5008 ncopies = btrfs_raid_array[index].ncopies;
5009 nparity = btrfs_raid_array[index].nparity;
5011 if (type & BTRFS_BLOCK_GROUP_DATA) {
5012 max_stripe_size = SZ_1G;
5013 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
5015 devs_max = BTRFS_MAX_DEVS(info);
5016 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5017 /* for larger filesystems, use larger metadata chunks */
5018 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
5019 max_stripe_size = SZ_1G;
5021 max_stripe_size = SZ_256M;
5022 max_chunk_size = max_stripe_size;
5024 devs_max = BTRFS_MAX_DEVS(info);
5025 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5026 max_stripe_size = SZ_32M;
5027 max_chunk_size = 2 * max_stripe_size;
5029 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
5031 btrfs_err(info, "invalid chunk type 0x%llx requested",
5036 /* We don't want a chunk larger than 10% of writable space */
5037 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
5040 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5046 * in the first pass through the devices list, we gather information
5047 * about the available holes on each device.
5050 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5054 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5056 "BTRFS: read-only device in alloc_list\n");
5060 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5061 &device->dev_state) ||
5062 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5065 if (device->total_bytes > device->bytes_used)
5066 total_avail = device->total_bytes - device->bytes_used;
5070 /* If there is no space on this device, skip it. */
5071 if (total_avail == 0)
5074 ret = find_free_dev_extent(trans, device,
5075 max_stripe_size * dev_stripes,
5076 &dev_offset, &max_avail);
5077 if (ret && ret != -ENOSPC)
5081 max_avail = max_stripe_size * dev_stripes;
5083 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
5084 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5086 "%s: devid %llu has no free space, have=%llu want=%u",
5087 __func__, device->devid, max_avail,
5088 BTRFS_STRIPE_LEN * dev_stripes);
5092 if (ndevs == fs_devices->rw_devices) {
5093 WARN(1, "%s: found more than %llu devices\n",
5094 __func__, fs_devices->rw_devices);
5097 devices_info[ndevs].dev_offset = dev_offset;
5098 devices_info[ndevs].max_avail = max_avail;
5099 devices_info[ndevs].total_avail = total_avail;
5100 devices_info[ndevs].dev = device;
5105 * now sort the devices by hole size / available space
5107 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5108 btrfs_cmp_device_info, NULL);
5110 /* round down to number of usable stripes */
5111 ndevs = round_down(ndevs, devs_increment);
5113 if (ndevs < devs_min) {
5115 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5117 "%s: not enough devices with free space: have=%d minimum required=%d",
5118 __func__, ndevs, devs_min);
5123 ndevs = min(ndevs, devs_max);
5126 * The primary goal is to maximize the number of stripes, so use as
5127 * many devices as possible, even if the stripes are not maximum sized.
5129 * The DUP profile stores more than one stripe per device, the
5130 * max_avail is the total size so we have to adjust.
5132 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
5133 num_stripes = ndevs * dev_stripes;
5136 * this will have to be fixed for RAID1 and RAID10 over
5139 data_stripes = (num_stripes - nparity) / ncopies;
5142 * Use the number of data stripes to figure out how big this chunk
5143 * is really going to be in terms of logical address space,
5144 * and compare that answer with the max chunk size. If it's higher,
5145 * we try to reduce stripe_size.
5147 if (stripe_size * data_stripes > max_chunk_size) {
5149 * Reduce stripe_size, round it up to a 16MB boundary again and
5150 * then use it, unless it ends up being even bigger than the
5151 * previous value we had already.
5153 stripe_size = min(round_up(div_u64(max_chunk_size,
5154 data_stripes), SZ_16M),
5158 /* align to BTRFS_STRIPE_LEN */
5159 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
5161 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5166 map->num_stripes = num_stripes;
5168 for (i = 0; i < ndevs; ++i) {
5169 for (j = 0; j < dev_stripes; ++j) {
5170 int s = i * dev_stripes + j;
5171 map->stripes[s].dev = devices_info[i].dev;
5172 map->stripes[s].physical = devices_info[i].dev_offset +
5176 map->stripe_len = BTRFS_STRIPE_LEN;
5177 map->io_align = BTRFS_STRIPE_LEN;
5178 map->io_width = BTRFS_STRIPE_LEN;
5180 map->sub_stripes = sub_stripes;
5182 chunk_size = stripe_size * data_stripes;
5184 trace_btrfs_chunk_alloc(info, map, start, chunk_size);
5186 em = alloc_extent_map();
5192 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5193 em->map_lookup = map;
5195 em->len = chunk_size;
5196 em->block_start = 0;
5197 em->block_len = em->len;
5198 em->orig_block_len = stripe_size;
5200 em_tree = &info->mapping_tree.map_tree;
5201 write_lock(&em_tree->lock);
5202 ret = add_extent_mapping(em_tree, em, 0);
5204 write_unlock(&em_tree->lock);
5205 free_extent_map(em);
5209 list_add_tail(&em->list, &trans->transaction->pending_chunks);
5210 refcount_inc(&em->refs);
5211 write_unlock(&em_tree->lock);
5213 ret = btrfs_make_block_group(trans, 0, type, start, chunk_size);
5215 goto error_del_extent;
5217 for (i = 0; i < map->num_stripes; i++)
5218 btrfs_device_set_bytes_used(map->stripes[i].dev,
5219 map->stripes[i].dev->bytes_used + stripe_size);
5221 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
5223 free_extent_map(em);
5224 check_raid56_incompat_flag(info, type);
5226 kfree(devices_info);
5230 write_lock(&em_tree->lock);
5231 remove_extent_mapping(em_tree, em);
5232 write_unlock(&em_tree->lock);
5234 /* One for our allocation */
5235 free_extent_map(em);
5236 /* One for the tree reference */
5237 free_extent_map(em);
5238 /* One for the pending_chunks list reference */
5239 free_extent_map(em);
5241 kfree(devices_info);
5245 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5246 u64 chunk_offset, u64 chunk_size)
5248 struct btrfs_fs_info *fs_info = trans->fs_info;
5249 struct btrfs_root *extent_root = fs_info->extent_root;
5250 struct btrfs_root *chunk_root = fs_info->chunk_root;
5251 struct btrfs_key key;
5252 struct btrfs_device *device;
5253 struct btrfs_chunk *chunk;
5254 struct btrfs_stripe *stripe;
5255 struct extent_map *em;
5256 struct map_lookup *map;
5263 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5267 map = em->map_lookup;
5268 item_size = btrfs_chunk_item_size(map->num_stripes);
5269 stripe_size = em->orig_block_len;
5271 chunk = kzalloc(item_size, GFP_NOFS);
5278 * Take the device list mutex to prevent races with the final phase of
5279 * a device replace operation that replaces the device object associated
5280 * with the map's stripes, because the device object's id can change
5281 * at any time during that final phase of the device replace operation
5282 * (dev-replace.c:btrfs_dev_replace_finishing()).
5284 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5285 for (i = 0; i < map->num_stripes; i++) {
5286 device = map->stripes[i].dev;
5287 dev_offset = map->stripes[i].physical;
5289 ret = btrfs_update_device(trans, device);
5292 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5293 dev_offset, stripe_size);
5298 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5302 stripe = &chunk->stripe;
5303 for (i = 0; i < map->num_stripes; i++) {
5304 device = map->stripes[i].dev;
5305 dev_offset = map->stripes[i].physical;
5307 btrfs_set_stack_stripe_devid(stripe, device->devid);
5308 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5309 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5312 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5314 btrfs_set_stack_chunk_length(chunk, chunk_size);
5315 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5316 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5317 btrfs_set_stack_chunk_type(chunk, map->type);
5318 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5319 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5320 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5321 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5322 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5324 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5325 key.type = BTRFS_CHUNK_ITEM_KEY;
5326 key.offset = chunk_offset;
5328 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5329 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5331 * TODO: Cleanup of inserted chunk root in case of
5334 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5339 free_extent_map(em);
5344 * Chunk allocation falls into two parts. The first part does work
5345 * that makes the new allocated chunk usable, but does not do any operation
5346 * that modifies the chunk tree. The second part does the work that
5347 * requires modifying the chunk tree. This division is important for the
5348 * bootstrap process of adding storage to a seed btrfs.
5350 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5354 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5355 chunk_offset = find_next_chunk(trans->fs_info);
5356 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5359 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5360 struct btrfs_fs_info *fs_info)
5363 u64 sys_chunk_offset;
5367 chunk_offset = find_next_chunk(fs_info);
5368 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5369 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5373 sys_chunk_offset = find_next_chunk(fs_info);
5374 alloc_profile = btrfs_system_alloc_profile(fs_info);
5375 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5379 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5383 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5384 BTRFS_BLOCK_GROUP_RAID10 |
5385 BTRFS_BLOCK_GROUP_RAID5 |
5386 BTRFS_BLOCK_GROUP_DUP)) {
5388 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5397 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5399 struct extent_map *em;
5400 struct map_lookup *map;
5405 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5409 map = em->map_lookup;
5410 for (i = 0; i < map->num_stripes; i++) {
5411 if (test_bit(BTRFS_DEV_STATE_MISSING,
5412 &map->stripes[i].dev->dev_state)) {
5416 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5417 &map->stripes[i].dev->dev_state)) {
5424 * If the number of missing devices is larger than max errors,
5425 * we can not write the data into that chunk successfully, so
5428 if (miss_ndevs > btrfs_chunk_max_errors(map))
5431 free_extent_map(em);
5435 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5437 extent_map_tree_init(&tree->map_tree);
5440 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5442 struct extent_map *em;
5445 write_lock(&tree->map_tree.lock);
5446 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5448 remove_extent_mapping(&tree->map_tree, em);
5449 write_unlock(&tree->map_tree.lock);
5453 free_extent_map(em);
5454 /* once for the tree */
5455 free_extent_map(em);
5459 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5461 struct extent_map *em;
5462 struct map_lookup *map;
5465 em = btrfs_get_chunk_map(fs_info, logical, len);
5468 * We could return errors for these cases, but that could get
5469 * ugly and we'd probably do the same thing which is just not do
5470 * anything else and exit, so return 1 so the callers don't try
5471 * to use other copies.
5475 map = em->map_lookup;
5476 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5477 ret = map->num_stripes;
5478 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5479 ret = map->sub_stripes;
5480 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5482 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5484 * There could be two corrupted data stripes, we need
5485 * to loop retry in order to rebuild the correct data.
5487 * Fail a stripe at a time on every retry except the
5488 * stripe under reconstruction.
5490 ret = map->num_stripes;
5493 free_extent_map(em);
5495 down_read(&fs_info->dev_replace.rwsem);
5496 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5497 fs_info->dev_replace.tgtdev)
5499 up_read(&fs_info->dev_replace.rwsem);
5504 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5507 struct extent_map *em;
5508 struct map_lookup *map;
5509 unsigned long len = fs_info->sectorsize;
5511 em = btrfs_get_chunk_map(fs_info, logical, len);
5513 if (!WARN_ON(IS_ERR(em))) {
5514 map = em->map_lookup;
5515 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5516 len = map->stripe_len * nr_data_stripes(map);
5517 free_extent_map(em);
5522 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5524 struct extent_map *em;
5525 struct map_lookup *map;
5528 em = btrfs_get_chunk_map(fs_info, logical, len);
5530 if(!WARN_ON(IS_ERR(em))) {
5531 map = em->map_lookup;
5532 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5534 free_extent_map(em);
5539 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5540 struct map_lookup *map, int first,
5541 int dev_replace_is_ongoing)
5545 int preferred_mirror;
5547 struct btrfs_device *srcdev;
5550 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5552 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5553 num_stripes = map->sub_stripes;
5555 num_stripes = map->num_stripes;
5557 preferred_mirror = first + current->pid % num_stripes;
5559 if (dev_replace_is_ongoing &&
5560 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5561 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5562 srcdev = fs_info->dev_replace.srcdev;
5567 * try to avoid the drive that is the source drive for a
5568 * dev-replace procedure, only choose it if no other non-missing
5569 * mirror is available
5571 for (tolerance = 0; tolerance < 2; tolerance++) {
5572 if (map->stripes[preferred_mirror].dev->bdev &&
5573 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5574 return preferred_mirror;
5575 for (i = first; i < first + num_stripes; i++) {
5576 if (map->stripes[i].dev->bdev &&
5577 (tolerance || map->stripes[i].dev != srcdev))
5582 /* we couldn't find one that doesn't fail. Just return something
5583 * and the io error handling code will clean up eventually
5585 return preferred_mirror;
5588 static inline int parity_smaller(u64 a, u64 b)
5593 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5594 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5596 struct btrfs_bio_stripe s;
5603 for (i = 0; i < num_stripes - 1; i++) {
5604 if (parity_smaller(bbio->raid_map[i],
5605 bbio->raid_map[i+1])) {
5606 s = bbio->stripes[i];
5607 l = bbio->raid_map[i];
5608 bbio->stripes[i] = bbio->stripes[i+1];
5609 bbio->raid_map[i] = bbio->raid_map[i+1];
5610 bbio->stripes[i+1] = s;
5611 bbio->raid_map[i+1] = l;
5619 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5621 struct btrfs_bio *bbio = kzalloc(
5622 /* the size of the btrfs_bio */
5623 sizeof(struct btrfs_bio) +
5624 /* plus the variable array for the stripes */
5625 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5626 /* plus the variable array for the tgt dev */
5627 sizeof(int) * (real_stripes) +
5629 * plus the raid_map, which includes both the tgt dev
5632 sizeof(u64) * (total_stripes),
5633 GFP_NOFS|__GFP_NOFAIL);
5635 atomic_set(&bbio->error, 0);
5636 refcount_set(&bbio->refs, 1);
5641 void btrfs_get_bbio(struct btrfs_bio *bbio)
5643 WARN_ON(!refcount_read(&bbio->refs));
5644 refcount_inc(&bbio->refs);
5647 void btrfs_put_bbio(struct btrfs_bio *bbio)
5651 if (refcount_dec_and_test(&bbio->refs))
5655 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5657 * Please note that, discard won't be sent to target device of device
5660 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5661 u64 logical, u64 length,
5662 struct btrfs_bio **bbio_ret)
5664 struct extent_map *em;
5665 struct map_lookup *map;
5666 struct btrfs_bio *bbio;
5670 u64 stripe_end_offset;
5677 u32 sub_stripes = 0;
5678 u64 stripes_per_dev = 0;
5679 u32 remaining_stripes = 0;
5680 u32 last_stripe = 0;
5684 /* discard always return a bbio */
5687 em = btrfs_get_chunk_map(fs_info, logical, length);
5691 map = em->map_lookup;
5692 /* we don't discard raid56 yet */
5693 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5698 offset = logical - em->start;
5699 length = min_t(u64, em->len - offset, length);
5701 stripe_len = map->stripe_len;
5703 * stripe_nr counts the total number of stripes we have to stride
5704 * to get to this block
5706 stripe_nr = div64_u64(offset, stripe_len);
5708 /* stripe_offset is the offset of this block in its stripe */
5709 stripe_offset = offset - stripe_nr * stripe_len;
5711 stripe_nr_end = round_up(offset + length, map->stripe_len);
5712 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5713 stripe_cnt = stripe_nr_end - stripe_nr;
5714 stripe_end_offset = stripe_nr_end * map->stripe_len -
5717 * after this, stripe_nr is the number of stripes on this
5718 * device we have to walk to find the data, and stripe_index is
5719 * the number of our device in the stripe array
5723 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5724 BTRFS_BLOCK_GROUP_RAID10)) {
5725 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5728 sub_stripes = map->sub_stripes;
5730 factor = map->num_stripes / sub_stripes;
5731 num_stripes = min_t(u64, map->num_stripes,
5732 sub_stripes * stripe_cnt);
5733 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5734 stripe_index *= sub_stripes;
5735 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5736 &remaining_stripes);
5737 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5738 last_stripe *= sub_stripes;
5739 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5740 BTRFS_BLOCK_GROUP_DUP)) {
5741 num_stripes = map->num_stripes;
5743 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5747 bbio = alloc_btrfs_bio(num_stripes, 0);
5753 for (i = 0; i < num_stripes; i++) {
5754 bbio->stripes[i].physical =
5755 map->stripes[stripe_index].physical +
5756 stripe_offset + stripe_nr * map->stripe_len;
5757 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5759 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5760 BTRFS_BLOCK_GROUP_RAID10)) {
5761 bbio->stripes[i].length = stripes_per_dev *
5764 if (i / sub_stripes < remaining_stripes)
5765 bbio->stripes[i].length +=
5769 * Special for the first stripe and
5772 * |-------|...|-------|
5776 if (i < sub_stripes)
5777 bbio->stripes[i].length -=
5780 if (stripe_index >= last_stripe &&
5781 stripe_index <= (last_stripe +
5783 bbio->stripes[i].length -=
5786 if (i == sub_stripes - 1)
5789 bbio->stripes[i].length = length;
5793 if (stripe_index == map->num_stripes) {
5800 bbio->map_type = map->type;
5801 bbio->num_stripes = num_stripes;
5803 free_extent_map(em);
5808 * In dev-replace case, for repair case (that's the only case where the mirror
5809 * is selected explicitly when calling btrfs_map_block), blocks left of the
5810 * left cursor can also be read from the target drive.
5812 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5814 * For READ, it also needs to be supported using the same mirror number.
5816 * If the requested block is not left of the left cursor, EIO is returned. This
5817 * can happen because btrfs_num_copies() returns one more in the dev-replace
5820 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5821 u64 logical, u64 length,
5822 u64 srcdev_devid, int *mirror_num,
5825 struct btrfs_bio *bbio = NULL;
5827 int index_srcdev = 0;
5829 u64 physical_of_found = 0;
5833 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5834 logical, &length, &bbio, 0, 0);
5836 ASSERT(bbio == NULL);
5840 num_stripes = bbio->num_stripes;
5841 if (*mirror_num > num_stripes) {
5843 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5844 * that means that the requested area is not left of the left
5847 btrfs_put_bbio(bbio);
5852 * process the rest of the function using the mirror_num of the source
5853 * drive. Therefore look it up first. At the end, patch the device
5854 * pointer to the one of the target drive.
5856 for (i = 0; i < num_stripes; i++) {
5857 if (bbio->stripes[i].dev->devid != srcdev_devid)
5861 * In case of DUP, in order to keep it simple, only add the
5862 * mirror with the lowest physical address
5865 physical_of_found <= bbio->stripes[i].physical)
5870 physical_of_found = bbio->stripes[i].physical;
5873 btrfs_put_bbio(bbio);
5879 *mirror_num = index_srcdev + 1;
5880 *physical = physical_of_found;
5884 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5885 struct btrfs_bio **bbio_ret,
5886 struct btrfs_dev_replace *dev_replace,
5887 int *num_stripes_ret, int *max_errors_ret)
5889 struct btrfs_bio *bbio = *bbio_ret;
5890 u64 srcdev_devid = dev_replace->srcdev->devid;
5891 int tgtdev_indexes = 0;
5892 int num_stripes = *num_stripes_ret;
5893 int max_errors = *max_errors_ret;
5896 if (op == BTRFS_MAP_WRITE) {
5897 int index_where_to_add;
5900 * duplicate the write operations while the dev replace
5901 * procedure is running. Since the copying of the old disk to
5902 * the new disk takes place at run time while the filesystem is
5903 * mounted writable, the regular write operations to the old
5904 * disk have to be duplicated to go to the new disk as well.
5906 * Note that device->missing is handled by the caller, and that
5907 * the write to the old disk is already set up in the stripes
5910 index_where_to_add = num_stripes;
5911 for (i = 0; i < num_stripes; i++) {
5912 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5913 /* write to new disk, too */
5914 struct btrfs_bio_stripe *new =
5915 bbio->stripes + index_where_to_add;
5916 struct btrfs_bio_stripe *old =
5919 new->physical = old->physical;
5920 new->length = old->length;
5921 new->dev = dev_replace->tgtdev;
5922 bbio->tgtdev_map[i] = index_where_to_add;
5923 index_where_to_add++;
5928 num_stripes = index_where_to_add;
5929 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5930 int index_srcdev = 0;
5932 u64 physical_of_found = 0;
5935 * During the dev-replace procedure, the target drive can also
5936 * be used to read data in case it is needed to repair a corrupt
5937 * block elsewhere. This is possible if the requested area is
5938 * left of the left cursor. In this area, the target drive is a
5939 * full copy of the source drive.
5941 for (i = 0; i < num_stripes; i++) {
5942 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5944 * In case of DUP, in order to keep it simple,
5945 * only add the mirror with the lowest physical
5949 physical_of_found <=
5950 bbio->stripes[i].physical)
5954 physical_of_found = bbio->stripes[i].physical;
5958 struct btrfs_bio_stripe *tgtdev_stripe =
5959 bbio->stripes + num_stripes;
5961 tgtdev_stripe->physical = physical_of_found;
5962 tgtdev_stripe->length =
5963 bbio->stripes[index_srcdev].length;
5964 tgtdev_stripe->dev = dev_replace->tgtdev;
5965 bbio->tgtdev_map[index_srcdev] = num_stripes;
5972 *num_stripes_ret = num_stripes;
5973 *max_errors_ret = max_errors;
5974 bbio->num_tgtdevs = tgtdev_indexes;
5978 static bool need_full_stripe(enum btrfs_map_op op)
5980 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5983 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5984 enum btrfs_map_op op,
5985 u64 logical, u64 *length,
5986 struct btrfs_bio **bbio_ret,
5987 int mirror_num, int need_raid_map)
5989 struct extent_map *em;
5990 struct map_lookup *map;
6000 int tgtdev_indexes = 0;
6001 struct btrfs_bio *bbio = NULL;
6002 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6003 int dev_replace_is_ongoing = 0;
6004 int num_alloc_stripes;
6005 int patch_the_first_stripe_for_dev_replace = 0;
6006 u64 physical_to_patch_in_first_stripe = 0;
6007 u64 raid56_full_stripe_start = (u64)-1;
6009 if (op == BTRFS_MAP_DISCARD)
6010 return __btrfs_map_block_for_discard(fs_info, logical,
6013 em = btrfs_get_chunk_map(fs_info, logical, *length);
6017 map = em->map_lookup;
6018 offset = logical - em->start;
6020 stripe_len = map->stripe_len;
6023 * stripe_nr counts the total number of stripes we have to stride
6024 * to get to this block
6026 stripe_nr = div64_u64(stripe_nr, stripe_len);
6028 stripe_offset = stripe_nr * stripe_len;
6029 if (offset < stripe_offset) {
6031 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
6032 stripe_offset, offset, em->start, logical,
6034 free_extent_map(em);
6038 /* stripe_offset is the offset of this block in its stripe*/
6039 stripe_offset = offset - stripe_offset;
6041 /* if we're here for raid56, we need to know the stripe aligned start */
6042 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6043 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
6044 raid56_full_stripe_start = offset;
6046 /* allow a write of a full stripe, but make sure we don't
6047 * allow straddling of stripes
6049 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6051 raid56_full_stripe_start *= full_stripe_len;
6054 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6056 /* For writes to RAID[56], allow a full stripeset across all disks.
6057 For other RAID types and for RAID[56] reads, just allow a single
6058 stripe (on a single disk). */
6059 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6060 (op == BTRFS_MAP_WRITE)) {
6061 max_len = stripe_len * nr_data_stripes(map) -
6062 (offset - raid56_full_stripe_start);
6064 /* we limit the length of each bio to what fits in a stripe */
6065 max_len = stripe_len - stripe_offset;
6067 *length = min_t(u64, em->len - offset, max_len);
6069 *length = em->len - offset;
6073 * This is for when we're called from btrfs_bio_fits_in_stripe and all
6074 * it cares about is the length
6079 down_read(&dev_replace->rwsem);
6080 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6082 * Hold the semaphore for read during the whole operation, write is
6083 * requested at commit time but must wait.
6085 if (!dev_replace_is_ongoing)
6086 up_read(&dev_replace->rwsem);
6088 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6089 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6090 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6091 dev_replace->srcdev->devid,
6093 &physical_to_patch_in_first_stripe);
6097 patch_the_first_stripe_for_dev_replace = 1;
6098 } else if (mirror_num > map->num_stripes) {
6104 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6105 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6107 if (!need_full_stripe(op))
6109 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
6110 if (need_full_stripe(op))
6111 num_stripes = map->num_stripes;
6112 else if (mirror_num)
6113 stripe_index = mirror_num - 1;
6115 stripe_index = find_live_mirror(fs_info, map, 0,
6116 dev_replace_is_ongoing);
6117 mirror_num = stripe_index + 1;
6120 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6121 if (need_full_stripe(op)) {
6122 num_stripes = map->num_stripes;
6123 } else if (mirror_num) {
6124 stripe_index = mirror_num - 1;
6129 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6130 u32 factor = map->num_stripes / map->sub_stripes;
6132 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6133 stripe_index *= map->sub_stripes;
6135 if (need_full_stripe(op))
6136 num_stripes = map->sub_stripes;
6137 else if (mirror_num)
6138 stripe_index += mirror_num - 1;
6140 int old_stripe_index = stripe_index;
6141 stripe_index = find_live_mirror(fs_info, map,
6143 dev_replace_is_ongoing);
6144 mirror_num = stripe_index - old_stripe_index + 1;
6147 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6148 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6149 /* push stripe_nr back to the start of the full stripe */
6150 stripe_nr = div64_u64(raid56_full_stripe_start,
6151 stripe_len * nr_data_stripes(map));
6153 /* RAID[56] write or recovery. Return all stripes */
6154 num_stripes = map->num_stripes;
6155 max_errors = nr_parity_stripes(map);
6157 *length = map->stripe_len;
6162 * Mirror #0 or #1 means the original data block.
6163 * Mirror #2 is RAID5 parity block.
6164 * Mirror #3 is RAID6 Q block.
6166 stripe_nr = div_u64_rem(stripe_nr,
6167 nr_data_stripes(map), &stripe_index);
6169 stripe_index = nr_data_stripes(map) +
6172 /* We distribute the parity blocks across stripes */
6173 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6175 if (!need_full_stripe(op) && mirror_num <= 1)
6180 * after this, stripe_nr is the number of stripes on this
6181 * device we have to walk to find the data, and stripe_index is
6182 * the number of our device in the stripe array
6184 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6186 mirror_num = stripe_index + 1;
6188 if (stripe_index >= map->num_stripes) {
6190 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6191 stripe_index, map->num_stripes);
6196 num_alloc_stripes = num_stripes;
6197 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6198 if (op == BTRFS_MAP_WRITE)
6199 num_alloc_stripes <<= 1;
6200 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6201 num_alloc_stripes++;
6202 tgtdev_indexes = num_stripes;
6205 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6210 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
6211 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
6213 /* build raid_map */
6214 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6215 (need_full_stripe(op) || mirror_num > 1)) {
6219 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6220 sizeof(struct btrfs_bio_stripe) *
6222 sizeof(int) * tgtdev_indexes);
6224 /* Work out the disk rotation on this stripe-set */
6225 div_u64_rem(stripe_nr, num_stripes, &rot);
6227 /* Fill in the logical address of each stripe */
6228 tmp = stripe_nr * nr_data_stripes(map);
6229 for (i = 0; i < nr_data_stripes(map); i++)
6230 bbio->raid_map[(i+rot) % num_stripes] =
6231 em->start + (tmp + i) * map->stripe_len;
6233 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6234 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6235 bbio->raid_map[(i+rot+1) % num_stripes] =
6240 for (i = 0; i < num_stripes; i++) {
6241 bbio->stripes[i].physical =
6242 map->stripes[stripe_index].physical +
6244 stripe_nr * map->stripe_len;
6245 bbio->stripes[i].dev =
6246 map->stripes[stripe_index].dev;
6250 if (need_full_stripe(op))
6251 max_errors = btrfs_chunk_max_errors(map);
6254 sort_parity_stripes(bbio, num_stripes);
6256 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6257 need_full_stripe(op)) {
6258 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6263 bbio->map_type = map->type;
6264 bbio->num_stripes = num_stripes;
6265 bbio->max_errors = max_errors;
6266 bbio->mirror_num = mirror_num;
6269 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6270 * mirror_num == num_stripes + 1 && dev_replace target drive is
6271 * available as a mirror
6273 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6274 WARN_ON(num_stripes > 1);
6275 bbio->stripes[0].dev = dev_replace->tgtdev;
6276 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6277 bbio->mirror_num = map->num_stripes + 1;
6280 if (dev_replace_is_ongoing) {
6281 lockdep_assert_held(&dev_replace->rwsem);
6282 /* Unlock and let waiting writers proceed */
6283 up_read(&dev_replace->rwsem);
6285 free_extent_map(em);
6289 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6290 u64 logical, u64 *length,
6291 struct btrfs_bio **bbio_ret, int mirror_num)
6293 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6297 /* For Scrub/replace */
6298 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6299 u64 logical, u64 *length,
6300 struct btrfs_bio **bbio_ret)
6302 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6305 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
6306 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
6308 struct extent_map *em;
6309 struct map_lookup *map;
6317 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
6321 map = em->map_lookup;
6323 rmap_len = map->stripe_len;
6325 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6326 length = div_u64(length, map->num_stripes / map->sub_stripes);
6327 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6328 length = div_u64(length, map->num_stripes);
6329 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6330 length = div_u64(length, nr_data_stripes(map));
6331 rmap_len = map->stripe_len * nr_data_stripes(map);
6334 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6335 BUG_ON(!buf); /* -ENOMEM */
6337 for (i = 0; i < map->num_stripes; i++) {
6338 if (map->stripes[i].physical > physical ||
6339 map->stripes[i].physical + length <= physical)
6342 stripe_nr = physical - map->stripes[i].physical;
6343 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6345 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6346 stripe_nr = stripe_nr * map->num_stripes + i;
6347 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6348 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6349 stripe_nr = stripe_nr * map->num_stripes + i;
6350 } /* else if RAID[56], multiply by nr_data_stripes().
6351 * Alternatively, just use rmap_len below instead of
6352 * map->stripe_len */
6354 bytenr = chunk_start + stripe_nr * rmap_len;
6355 WARN_ON(nr >= map->num_stripes);
6356 for (j = 0; j < nr; j++) {
6357 if (buf[j] == bytenr)
6361 WARN_ON(nr >= map->num_stripes);
6368 *stripe_len = rmap_len;
6370 free_extent_map(em);
6374 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6376 bio->bi_private = bbio->private;
6377 bio->bi_end_io = bbio->end_io;
6380 btrfs_put_bbio(bbio);
6383 static void btrfs_end_bio(struct bio *bio)
6385 struct btrfs_bio *bbio = bio->bi_private;
6386 int is_orig_bio = 0;
6388 if (bio->bi_status) {
6389 atomic_inc(&bbio->error);
6390 if (bio->bi_status == BLK_STS_IOERR ||
6391 bio->bi_status == BLK_STS_TARGET) {
6392 unsigned int stripe_index =
6393 btrfs_io_bio(bio)->stripe_index;
6394 struct btrfs_device *dev;
6396 BUG_ON(stripe_index >= bbio->num_stripes);
6397 dev = bbio->stripes[stripe_index].dev;
6399 if (bio_op(bio) == REQ_OP_WRITE)
6400 btrfs_dev_stat_inc_and_print(dev,
6401 BTRFS_DEV_STAT_WRITE_ERRS);
6402 else if (!(bio->bi_opf & REQ_RAHEAD))
6403 btrfs_dev_stat_inc_and_print(dev,
6404 BTRFS_DEV_STAT_READ_ERRS);
6405 if (bio->bi_opf & REQ_PREFLUSH)
6406 btrfs_dev_stat_inc_and_print(dev,
6407 BTRFS_DEV_STAT_FLUSH_ERRS);
6412 if (bio == bbio->orig_bio)
6415 btrfs_bio_counter_dec(bbio->fs_info);
6417 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6420 bio = bbio->orig_bio;
6423 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6424 /* only send an error to the higher layers if it is
6425 * beyond the tolerance of the btrfs bio
6427 if (atomic_read(&bbio->error) > bbio->max_errors) {
6428 bio->bi_status = BLK_STS_IOERR;
6431 * this bio is actually up to date, we didn't
6432 * go over the max number of errors
6434 bio->bi_status = BLK_STS_OK;
6437 btrfs_end_bbio(bbio, bio);
6438 } else if (!is_orig_bio) {
6444 * see run_scheduled_bios for a description of why bios are collected for
6447 * This will add one bio to the pending list for a device and make sure
6448 * the work struct is scheduled.
6450 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6453 struct btrfs_fs_info *fs_info = device->fs_info;
6454 int should_queue = 1;
6455 struct btrfs_pending_bios *pending_bios;
6457 /* don't bother with additional async steps for reads, right now */
6458 if (bio_op(bio) == REQ_OP_READ) {
6459 btrfsic_submit_bio(bio);
6463 WARN_ON(bio->bi_next);
6464 bio->bi_next = NULL;
6466 spin_lock(&device->io_lock);
6467 if (op_is_sync(bio->bi_opf))
6468 pending_bios = &device->pending_sync_bios;
6470 pending_bios = &device->pending_bios;
6472 if (pending_bios->tail)
6473 pending_bios->tail->bi_next = bio;
6475 pending_bios->tail = bio;
6476 if (!pending_bios->head)
6477 pending_bios->head = bio;
6478 if (device->running_pending)
6481 spin_unlock(&device->io_lock);
6484 btrfs_queue_work(fs_info->submit_workers, &device->work);
6487 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6488 u64 physical, int dev_nr, int async)
6490 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6491 struct btrfs_fs_info *fs_info = bbio->fs_info;
6493 bio->bi_private = bbio;
6494 btrfs_io_bio(bio)->stripe_index = dev_nr;
6495 bio->bi_end_io = btrfs_end_bio;
6496 bio->bi_iter.bi_sector = physical >> 9;
6497 btrfs_debug_in_rcu(fs_info,
6498 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6499 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6500 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6501 bio->bi_iter.bi_size);
6502 bio_set_dev(bio, dev->bdev);
6504 btrfs_bio_counter_inc_noblocked(fs_info);
6507 btrfs_schedule_bio(dev, bio);
6509 btrfsic_submit_bio(bio);
6512 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6514 atomic_inc(&bbio->error);
6515 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6516 /* Should be the original bio. */
6517 WARN_ON(bio != bbio->orig_bio);
6519 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6520 bio->bi_iter.bi_sector = logical >> 9;
6521 if (atomic_read(&bbio->error) > bbio->max_errors)
6522 bio->bi_status = BLK_STS_IOERR;
6524 bio->bi_status = BLK_STS_OK;
6525 btrfs_end_bbio(bbio, bio);
6529 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6530 int mirror_num, int async_submit)
6532 struct btrfs_device *dev;
6533 struct bio *first_bio = bio;
6534 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6540 struct btrfs_bio *bbio = NULL;
6542 length = bio->bi_iter.bi_size;
6543 map_length = length;
6545 btrfs_bio_counter_inc_blocked(fs_info);
6546 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6547 &map_length, &bbio, mirror_num, 1);
6549 btrfs_bio_counter_dec(fs_info);
6550 return errno_to_blk_status(ret);
6553 total_devs = bbio->num_stripes;
6554 bbio->orig_bio = first_bio;
6555 bbio->private = first_bio->bi_private;
6556 bbio->end_io = first_bio->bi_end_io;
6557 bbio->fs_info = fs_info;
6558 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6560 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6561 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6562 /* In this case, map_length has been set to the length of
6563 a single stripe; not the whole write */
6564 if (bio_op(bio) == REQ_OP_WRITE) {
6565 ret = raid56_parity_write(fs_info, bio, bbio,
6568 ret = raid56_parity_recover(fs_info, bio, bbio,
6569 map_length, mirror_num, 1);
6572 btrfs_bio_counter_dec(fs_info);
6573 return errno_to_blk_status(ret);
6576 if (map_length < length) {
6578 "mapping failed logical %llu bio len %llu len %llu",
6579 logical, length, map_length);
6583 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6584 dev = bbio->stripes[dev_nr].dev;
6585 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6587 (bio_op(first_bio) == REQ_OP_WRITE &&
6588 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6589 bbio_error(bbio, first_bio, logical);
6593 if (dev_nr < total_devs - 1)
6594 bio = btrfs_bio_clone(first_bio);
6598 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6599 dev_nr, async_submit);
6601 btrfs_bio_counter_dec(fs_info);
6606 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6609 * If devid and uuid are both specified, the match must be exact, otherwise
6610 * only devid is used.
6612 * If @seed is true, traverse through the seed devices.
6614 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6615 u64 devid, u8 *uuid, u8 *fsid,
6618 struct btrfs_device *device;
6620 while (fs_devices) {
6622 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6623 list_for_each_entry(device, &fs_devices->devices,
6625 if (device->devid == devid &&
6626 (!uuid || memcmp(device->uuid, uuid,
6627 BTRFS_UUID_SIZE) == 0))
6632 fs_devices = fs_devices->seed;
6639 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6640 u64 devid, u8 *dev_uuid)
6642 struct btrfs_device *device;
6644 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6648 list_add(&device->dev_list, &fs_devices->devices);
6649 device->fs_devices = fs_devices;
6650 fs_devices->num_devices++;
6652 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6653 fs_devices->missing_devices++;
6659 * btrfs_alloc_device - allocate struct btrfs_device
6660 * @fs_info: used only for generating a new devid, can be NULL if
6661 * devid is provided (i.e. @devid != NULL).
6662 * @devid: a pointer to devid for this device. If NULL a new devid
6664 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6667 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6668 * on error. Returned struct is not linked onto any lists and must be
6669 * destroyed with btrfs_free_device.
6671 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6675 struct btrfs_device *dev;
6678 if (WARN_ON(!devid && !fs_info))
6679 return ERR_PTR(-EINVAL);
6681 dev = __alloc_device();
6690 ret = find_next_devid(fs_info, &tmp);
6692 btrfs_free_device(dev);
6693 return ERR_PTR(ret);
6699 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6701 generate_random_uuid(dev->uuid);
6703 btrfs_init_work(&dev->work, btrfs_submit_helper,
6704 pending_bios_fn, NULL, NULL);
6709 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6710 u64 devid, u8 *uuid, bool error)
6713 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6716 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6720 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6721 struct extent_buffer *leaf,
6722 struct btrfs_chunk *chunk)
6724 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6725 struct map_lookup *map;
6726 struct extent_map *em;
6730 u8 uuid[BTRFS_UUID_SIZE];
6735 logical = key->offset;
6736 length = btrfs_chunk_length(leaf, chunk);
6737 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6740 * Only need to verify chunk item if we're reading from sys chunk array,
6741 * as chunk item in tree block is already verified by tree-checker.
6743 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6744 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6749 read_lock(&map_tree->map_tree.lock);
6750 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6751 read_unlock(&map_tree->map_tree.lock);
6753 /* already mapped? */
6754 if (em && em->start <= logical && em->start + em->len > logical) {
6755 free_extent_map(em);
6758 free_extent_map(em);
6761 em = alloc_extent_map();
6764 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6766 free_extent_map(em);
6770 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6771 em->map_lookup = map;
6772 em->start = logical;
6775 em->block_start = 0;
6776 em->block_len = em->len;
6778 map->num_stripes = num_stripes;
6779 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6780 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6781 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6782 map->type = btrfs_chunk_type(leaf, chunk);
6783 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6784 map->verified_stripes = 0;
6785 for (i = 0; i < num_stripes; i++) {
6786 map->stripes[i].physical =
6787 btrfs_stripe_offset_nr(leaf, chunk, i);
6788 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6789 read_extent_buffer(leaf, uuid, (unsigned long)
6790 btrfs_stripe_dev_uuid_nr(chunk, i),
6792 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6793 devid, uuid, NULL, true);
6794 if (!map->stripes[i].dev &&
6795 !btrfs_test_opt(fs_info, DEGRADED)) {
6796 free_extent_map(em);
6797 btrfs_report_missing_device(fs_info, devid, uuid, true);
6800 if (!map->stripes[i].dev) {
6801 map->stripes[i].dev =
6802 add_missing_dev(fs_info->fs_devices, devid,
6804 if (IS_ERR(map->stripes[i].dev)) {
6805 free_extent_map(em);
6807 "failed to init missing dev %llu: %ld",
6808 devid, PTR_ERR(map->stripes[i].dev));
6809 return PTR_ERR(map->stripes[i].dev);
6811 btrfs_report_missing_device(fs_info, devid, uuid, false);
6813 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6814 &(map->stripes[i].dev->dev_state));
6818 write_lock(&map_tree->map_tree.lock);
6819 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6820 write_unlock(&map_tree->map_tree.lock);
6823 "failed to add chunk map, start=%llu len=%llu: %d",
6824 em->start, em->len, ret);
6826 free_extent_map(em);
6831 static void fill_device_from_item(struct extent_buffer *leaf,
6832 struct btrfs_dev_item *dev_item,
6833 struct btrfs_device *device)
6837 device->devid = btrfs_device_id(leaf, dev_item);
6838 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6839 device->total_bytes = device->disk_total_bytes;
6840 device->commit_total_bytes = device->disk_total_bytes;
6841 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6842 device->commit_bytes_used = device->bytes_used;
6843 device->type = btrfs_device_type(leaf, dev_item);
6844 device->io_align = btrfs_device_io_align(leaf, dev_item);
6845 device->io_width = btrfs_device_io_width(leaf, dev_item);
6846 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6847 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6848 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6850 ptr = btrfs_device_uuid(dev_item);
6851 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6854 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6857 struct btrfs_fs_devices *fs_devices;
6860 lockdep_assert_held(&uuid_mutex);
6863 fs_devices = fs_info->fs_devices->seed;
6864 while (fs_devices) {
6865 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6868 fs_devices = fs_devices->seed;
6871 fs_devices = find_fsid(fsid, NULL);
6873 if (!btrfs_test_opt(fs_info, DEGRADED))
6874 return ERR_PTR(-ENOENT);
6876 fs_devices = alloc_fs_devices(fsid, NULL);
6877 if (IS_ERR(fs_devices))
6880 fs_devices->seeding = 1;
6881 fs_devices->opened = 1;
6885 fs_devices = clone_fs_devices(fs_devices);
6886 if (IS_ERR(fs_devices))
6889 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6891 free_fs_devices(fs_devices);
6892 fs_devices = ERR_PTR(ret);
6896 if (!fs_devices->seeding) {
6897 close_fs_devices(fs_devices);
6898 free_fs_devices(fs_devices);
6899 fs_devices = ERR_PTR(-EINVAL);
6903 fs_devices->seed = fs_info->fs_devices->seed;
6904 fs_info->fs_devices->seed = fs_devices;
6909 static int read_one_dev(struct btrfs_fs_info *fs_info,
6910 struct extent_buffer *leaf,
6911 struct btrfs_dev_item *dev_item)
6913 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6914 struct btrfs_device *device;
6917 u8 fs_uuid[BTRFS_FSID_SIZE];
6918 u8 dev_uuid[BTRFS_UUID_SIZE];
6920 devid = btrfs_device_id(leaf, dev_item);
6921 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6923 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6926 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6927 fs_devices = open_seed_devices(fs_info, fs_uuid);
6928 if (IS_ERR(fs_devices))
6929 return PTR_ERR(fs_devices);
6932 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6935 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6936 btrfs_report_missing_device(fs_info, devid,
6941 device = add_missing_dev(fs_devices, devid, dev_uuid);
6942 if (IS_ERR(device)) {
6944 "failed to add missing dev %llu: %ld",
6945 devid, PTR_ERR(device));
6946 return PTR_ERR(device);
6948 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6950 if (!device->bdev) {
6951 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6952 btrfs_report_missing_device(fs_info,
6953 devid, dev_uuid, true);
6956 btrfs_report_missing_device(fs_info, devid,
6960 if (!device->bdev &&
6961 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6963 * this happens when a device that was properly setup
6964 * in the device info lists suddenly goes bad.
6965 * device->bdev is NULL, and so we have to set
6966 * device->missing to one here
6968 device->fs_devices->missing_devices++;
6969 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6972 /* Move the device to its own fs_devices */
6973 if (device->fs_devices != fs_devices) {
6974 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6975 &device->dev_state));
6977 list_move(&device->dev_list, &fs_devices->devices);
6978 device->fs_devices->num_devices--;
6979 fs_devices->num_devices++;
6981 device->fs_devices->missing_devices--;
6982 fs_devices->missing_devices++;
6984 device->fs_devices = fs_devices;
6988 if (device->fs_devices != fs_info->fs_devices) {
6989 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6990 if (device->generation !=
6991 btrfs_device_generation(leaf, dev_item))
6995 fill_device_from_item(leaf, dev_item, device);
6996 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6997 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6998 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6999 device->fs_devices->total_rw_bytes += device->total_bytes;
7000 atomic64_add(device->total_bytes - device->bytes_used,
7001 &fs_info->free_chunk_space);
7007 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7009 struct btrfs_root *root = fs_info->tree_root;
7010 struct btrfs_super_block *super_copy = fs_info->super_copy;
7011 struct extent_buffer *sb;
7012 struct btrfs_disk_key *disk_key;
7013 struct btrfs_chunk *chunk;
7015 unsigned long sb_array_offset;
7022 struct btrfs_key key;
7024 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7026 * This will create extent buffer of nodesize, superblock size is
7027 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7028 * overallocate but we can keep it as-is, only the first page is used.
7030 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
7033 set_extent_buffer_uptodate(sb);
7034 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
7036 * The sb extent buffer is artificial and just used to read the system array.
7037 * set_extent_buffer_uptodate() call does not properly mark all it's
7038 * pages up-to-date when the page is larger: extent does not cover the
7039 * whole page and consequently check_page_uptodate does not find all
7040 * the page's extents up-to-date (the hole beyond sb),
7041 * write_extent_buffer then triggers a WARN_ON.
7043 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7044 * but sb spans only this function. Add an explicit SetPageUptodate call
7045 * to silence the warning eg. on PowerPC 64.
7047 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
7048 SetPageUptodate(sb->pages[0]);
7050 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7051 array_size = btrfs_super_sys_array_size(super_copy);
7053 array_ptr = super_copy->sys_chunk_array;
7054 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7057 while (cur_offset < array_size) {
7058 disk_key = (struct btrfs_disk_key *)array_ptr;
7059 len = sizeof(*disk_key);
7060 if (cur_offset + len > array_size)
7061 goto out_short_read;
7063 btrfs_disk_key_to_cpu(&key, disk_key);
7066 sb_array_offset += len;
7069 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
7070 chunk = (struct btrfs_chunk *)sb_array_offset;
7072 * At least one btrfs_chunk with one stripe must be
7073 * present, exact stripe count check comes afterwards
7075 len = btrfs_chunk_item_size(1);
7076 if (cur_offset + len > array_size)
7077 goto out_short_read;
7079 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7082 "invalid number of stripes %u in sys_array at offset %u",
7083 num_stripes, cur_offset);
7088 type = btrfs_chunk_type(sb, chunk);
7089 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7091 "invalid chunk type %llu in sys_array at offset %u",
7097 len = btrfs_chunk_item_size(num_stripes);
7098 if (cur_offset + len > array_size)
7099 goto out_short_read;
7101 ret = read_one_chunk(fs_info, &key, sb, chunk);
7106 "unexpected item type %u in sys_array at offset %u",
7107 (u32)key.type, cur_offset);
7112 sb_array_offset += len;
7115 clear_extent_buffer_uptodate(sb);
7116 free_extent_buffer_stale(sb);
7120 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7122 clear_extent_buffer_uptodate(sb);
7123 free_extent_buffer_stale(sb);
7128 * Check if all chunks in the fs are OK for read-write degraded mount
7130 * If the @failing_dev is specified, it's accounted as missing.
7132 * Return true if all chunks meet the minimal RW mount requirements.
7133 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7135 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7136 struct btrfs_device *failing_dev)
7138 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
7139 struct extent_map *em;
7143 read_lock(&map_tree->map_tree.lock);
7144 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
7145 read_unlock(&map_tree->map_tree.lock);
7146 /* No chunk at all? Return false anyway */
7152 struct map_lookup *map;
7157 map = em->map_lookup;
7159 btrfs_get_num_tolerated_disk_barrier_failures(
7161 for (i = 0; i < map->num_stripes; i++) {
7162 struct btrfs_device *dev = map->stripes[i].dev;
7164 if (!dev || !dev->bdev ||
7165 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7166 dev->last_flush_error)
7168 else if (failing_dev && failing_dev == dev)
7171 if (missing > max_tolerated) {
7174 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7175 em->start, missing, max_tolerated);
7176 free_extent_map(em);
7180 next_start = extent_map_end(em);
7181 free_extent_map(em);
7183 read_lock(&map_tree->map_tree.lock);
7184 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
7185 (u64)(-1) - next_start);
7186 read_unlock(&map_tree->map_tree.lock);
7192 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7194 struct btrfs_root *root = fs_info->chunk_root;
7195 struct btrfs_path *path;
7196 struct extent_buffer *leaf;
7197 struct btrfs_key key;
7198 struct btrfs_key found_key;
7203 path = btrfs_alloc_path();
7208 * uuid_mutex is needed only if we are mounting a sprout FS
7209 * otherwise we don't need it.
7211 mutex_lock(&uuid_mutex);
7212 mutex_lock(&fs_info->chunk_mutex);
7215 * Read all device items, and then all the chunk items. All
7216 * device items are found before any chunk item (their object id
7217 * is smaller than the lowest possible object id for a chunk
7218 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7220 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7223 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7227 leaf = path->nodes[0];
7228 slot = path->slots[0];
7229 if (slot >= btrfs_header_nritems(leaf)) {
7230 ret = btrfs_next_leaf(root, path);
7237 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7238 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7239 struct btrfs_dev_item *dev_item;
7240 dev_item = btrfs_item_ptr(leaf, slot,
7241 struct btrfs_dev_item);
7242 ret = read_one_dev(fs_info, leaf, dev_item);
7246 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7247 struct btrfs_chunk *chunk;
7248 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7249 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
7257 * After loading chunk tree, we've got all device information,
7258 * do another round of validation checks.
7260 if (total_dev != fs_info->fs_devices->total_devices) {
7262 "super_num_devices %llu mismatch with num_devices %llu found here",
7263 btrfs_super_num_devices(fs_info->super_copy),
7268 if (btrfs_super_total_bytes(fs_info->super_copy) <
7269 fs_info->fs_devices->total_rw_bytes) {
7271 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7272 btrfs_super_total_bytes(fs_info->super_copy),
7273 fs_info->fs_devices->total_rw_bytes);
7279 mutex_unlock(&fs_info->chunk_mutex);
7280 mutex_unlock(&uuid_mutex);
7282 btrfs_free_path(path);
7286 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7288 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7289 struct btrfs_device *device;
7291 while (fs_devices) {
7292 mutex_lock(&fs_devices->device_list_mutex);
7293 list_for_each_entry(device, &fs_devices->devices, dev_list)
7294 device->fs_info = fs_info;
7295 mutex_unlock(&fs_devices->device_list_mutex);
7297 fs_devices = fs_devices->seed;
7301 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7305 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7306 btrfs_dev_stat_reset(dev, i);
7309 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7311 struct btrfs_key key;
7312 struct btrfs_key found_key;
7313 struct btrfs_root *dev_root = fs_info->dev_root;
7314 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7315 struct extent_buffer *eb;
7318 struct btrfs_device *device;
7319 struct btrfs_path *path = NULL;
7322 path = btrfs_alloc_path();
7328 mutex_lock(&fs_devices->device_list_mutex);
7329 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7331 struct btrfs_dev_stats_item *ptr;
7333 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7334 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7335 key.offset = device->devid;
7336 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7338 __btrfs_reset_dev_stats(device);
7339 device->dev_stats_valid = 1;
7340 btrfs_release_path(path);
7343 slot = path->slots[0];
7344 eb = path->nodes[0];
7345 btrfs_item_key_to_cpu(eb, &found_key, slot);
7346 item_size = btrfs_item_size_nr(eb, slot);
7348 ptr = btrfs_item_ptr(eb, slot,
7349 struct btrfs_dev_stats_item);
7351 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7352 if (item_size >= (1 + i) * sizeof(__le64))
7353 btrfs_dev_stat_set(device, i,
7354 btrfs_dev_stats_value(eb, ptr, i));
7356 btrfs_dev_stat_reset(device, i);
7359 device->dev_stats_valid = 1;
7360 btrfs_dev_stat_print_on_load(device);
7361 btrfs_release_path(path);
7363 mutex_unlock(&fs_devices->device_list_mutex);
7366 btrfs_free_path(path);
7367 return ret < 0 ? ret : 0;
7370 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7371 struct btrfs_device *device)
7373 struct btrfs_fs_info *fs_info = trans->fs_info;
7374 struct btrfs_root *dev_root = fs_info->dev_root;
7375 struct btrfs_path *path;
7376 struct btrfs_key key;
7377 struct extent_buffer *eb;
7378 struct btrfs_dev_stats_item *ptr;
7382 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7383 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7384 key.offset = device->devid;
7386 path = btrfs_alloc_path();
7389 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7391 btrfs_warn_in_rcu(fs_info,
7392 "error %d while searching for dev_stats item for device %s",
7393 ret, rcu_str_deref(device->name));
7398 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7399 /* need to delete old one and insert a new one */
7400 ret = btrfs_del_item(trans, dev_root, path);
7402 btrfs_warn_in_rcu(fs_info,
7403 "delete too small dev_stats item for device %s failed %d",
7404 rcu_str_deref(device->name), ret);
7411 /* need to insert a new item */
7412 btrfs_release_path(path);
7413 ret = btrfs_insert_empty_item(trans, dev_root, path,
7414 &key, sizeof(*ptr));
7416 btrfs_warn_in_rcu(fs_info,
7417 "insert dev_stats item for device %s failed %d",
7418 rcu_str_deref(device->name), ret);
7423 eb = path->nodes[0];
7424 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7425 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7426 btrfs_set_dev_stats_value(eb, ptr, i,
7427 btrfs_dev_stat_read(device, i));
7428 btrfs_mark_buffer_dirty(eb);
7431 btrfs_free_path(path);
7436 * called from commit_transaction. Writes all changed device stats to disk.
7438 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7439 struct btrfs_fs_info *fs_info)
7441 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7442 struct btrfs_device *device;
7446 mutex_lock(&fs_devices->device_list_mutex);
7447 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7448 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7449 if (!device->dev_stats_valid || stats_cnt == 0)
7454 * There is a LOAD-LOAD control dependency between the value of
7455 * dev_stats_ccnt and updating the on-disk values which requires
7456 * reading the in-memory counters. Such control dependencies
7457 * require explicit read memory barriers.
7459 * This memory barriers pairs with smp_mb__before_atomic in
7460 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7461 * barrier implied by atomic_xchg in
7462 * btrfs_dev_stats_read_and_reset
7466 ret = update_dev_stat_item(trans, device);
7468 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7470 mutex_unlock(&fs_devices->device_list_mutex);
7475 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7477 btrfs_dev_stat_inc(dev, index);
7478 btrfs_dev_stat_print_on_error(dev);
7481 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7483 if (!dev->dev_stats_valid)
7485 btrfs_err_rl_in_rcu(dev->fs_info,
7486 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7487 rcu_str_deref(dev->name),
7488 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7489 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7490 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7491 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7492 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7495 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7499 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7500 if (btrfs_dev_stat_read(dev, i) != 0)
7502 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7503 return; /* all values == 0, suppress message */
7505 btrfs_info_in_rcu(dev->fs_info,
7506 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7507 rcu_str_deref(dev->name),
7508 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7509 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7510 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7511 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7512 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7515 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7516 struct btrfs_ioctl_get_dev_stats *stats)
7518 struct btrfs_device *dev;
7519 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7522 mutex_lock(&fs_devices->device_list_mutex);
7523 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7525 mutex_unlock(&fs_devices->device_list_mutex);
7528 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7530 } else if (!dev->dev_stats_valid) {
7531 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7533 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7534 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7535 if (stats->nr_items > i)
7537 btrfs_dev_stat_read_and_reset(dev, i);
7539 btrfs_dev_stat_reset(dev, i);
7542 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7543 if (stats->nr_items > i)
7544 stats->values[i] = btrfs_dev_stat_read(dev, i);
7546 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7547 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7551 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7553 struct buffer_head *bh;
7554 struct btrfs_super_block *disk_super;
7560 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7563 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7566 disk_super = (struct btrfs_super_block *)bh->b_data;
7568 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7569 set_buffer_dirty(bh);
7570 sync_dirty_buffer(bh);
7574 /* Notify udev that device has changed */
7575 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7577 /* Update ctime/mtime for device path for libblkid */
7578 update_dev_time(device_path);
7582 * Update the size of all devices, which is used for writing out the
7585 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7587 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7588 struct btrfs_device *curr, *next;
7590 if (list_empty(&fs_devices->resized_devices))
7593 mutex_lock(&fs_devices->device_list_mutex);
7594 mutex_lock(&fs_info->chunk_mutex);
7595 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7597 list_del_init(&curr->resized_list);
7598 curr->commit_total_bytes = curr->disk_total_bytes;
7600 mutex_unlock(&fs_info->chunk_mutex);
7601 mutex_unlock(&fs_devices->device_list_mutex);
7604 /* Must be invoked during the transaction commit */
7605 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7607 struct btrfs_fs_info *fs_info = trans->fs_info;
7608 struct extent_map *em;
7609 struct map_lookup *map;
7610 struct btrfs_device *dev;
7613 if (list_empty(&trans->pending_chunks))
7616 /* In order to kick the device replace finish process */
7617 mutex_lock(&fs_info->chunk_mutex);
7618 list_for_each_entry(em, &trans->pending_chunks, list) {
7619 map = em->map_lookup;
7621 for (i = 0; i < map->num_stripes; i++) {
7622 dev = map->stripes[i].dev;
7623 dev->commit_bytes_used = dev->bytes_used;
7626 mutex_unlock(&fs_info->chunk_mutex);
7629 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7631 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7632 while (fs_devices) {
7633 fs_devices->fs_info = fs_info;
7634 fs_devices = fs_devices->seed;
7638 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7640 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7641 while (fs_devices) {
7642 fs_devices->fs_info = NULL;
7643 fs_devices = fs_devices->seed;
7648 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7650 int btrfs_bg_type_to_factor(u64 flags)
7652 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
7653 BTRFS_BLOCK_GROUP_RAID10))
7659 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
7661 int index = btrfs_bg_flags_to_raid_index(type);
7662 int ncopies = btrfs_raid_array[index].ncopies;
7665 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
7666 case BTRFS_BLOCK_GROUP_RAID5:
7667 data_stripes = num_stripes - 1;
7669 case BTRFS_BLOCK_GROUP_RAID6:
7670 data_stripes = num_stripes - 2;
7673 data_stripes = num_stripes / ncopies;
7676 return div_u64(chunk_len, data_stripes);
7679 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7680 u64 chunk_offset, u64 devid,
7681 u64 physical_offset, u64 physical_len)
7683 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7684 struct extent_map *em;
7685 struct map_lookup *map;
7686 struct btrfs_device *dev;
7692 read_lock(&em_tree->lock);
7693 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7694 read_unlock(&em_tree->lock);
7698 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7699 physical_offset, devid);
7704 map = em->map_lookup;
7705 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7706 if (physical_len != stripe_len) {
7708 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7709 physical_offset, devid, em->start, physical_len,
7715 for (i = 0; i < map->num_stripes; i++) {
7716 if (map->stripes[i].dev->devid == devid &&
7717 map->stripes[i].physical == physical_offset) {
7719 if (map->verified_stripes >= map->num_stripes) {
7721 "too many dev extents for chunk %llu found",
7726 map->verified_stripes++;
7732 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7733 physical_offset, devid);
7737 /* Make sure no dev extent is beyond device bondary */
7738 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7740 btrfs_err(fs_info, "failed to find devid %llu", devid);
7745 /* It's possible this device is a dummy for seed device */
7746 if (dev->disk_total_bytes == 0) {
7747 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7750 btrfs_err(fs_info, "failed to find seed devid %llu",
7757 if (physical_offset + physical_len > dev->disk_total_bytes) {
7759 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7760 devid, physical_offset, physical_len,
7761 dev->disk_total_bytes);
7766 free_extent_map(em);
7770 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7772 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7773 struct extent_map *em;
7774 struct rb_node *node;
7777 read_lock(&em_tree->lock);
7778 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7779 em = rb_entry(node, struct extent_map, rb_node);
7780 if (em->map_lookup->num_stripes !=
7781 em->map_lookup->verified_stripes) {
7783 "chunk %llu has missing dev extent, have %d expect %d",
7784 em->start, em->map_lookup->verified_stripes,
7785 em->map_lookup->num_stripes);
7791 read_unlock(&em_tree->lock);
7796 * Ensure that all dev extents are mapped to correct chunk, otherwise
7797 * later chunk allocation/free would cause unexpected behavior.
7799 * NOTE: This will iterate through the whole device tree, which should be of
7800 * the same size level as the chunk tree. This slightly increases mount time.
7802 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7804 struct btrfs_path *path;
7805 struct btrfs_root *root = fs_info->dev_root;
7806 struct btrfs_key key;
7808 u64 prev_dev_ext_end = 0;
7812 key.type = BTRFS_DEV_EXTENT_KEY;
7815 path = btrfs_alloc_path();
7819 path->reada = READA_FORWARD;
7820 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7824 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7825 ret = btrfs_next_item(root, path);
7828 /* No dev extents at all? Not good */
7835 struct extent_buffer *leaf = path->nodes[0];
7836 struct btrfs_dev_extent *dext;
7837 int slot = path->slots[0];
7839 u64 physical_offset;
7843 btrfs_item_key_to_cpu(leaf, &key, slot);
7844 if (key.type != BTRFS_DEV_EXTENT_KEY)
7846 devid = key.objectid;
7847 physical_offset = key.offset;
7849 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7850 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7851 physical_len = btrfs_dev_extent_length(leaf, dext);
7853 /* Check if this dev extent overlaps with the previous one */
7854 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7856 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7857 devid, physical_offset, prev_dev_ext_end);
7862 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7863 physical_offset, physical_len);
7867 prev_dev_ext_end = physical_offset + physical_len;
7869 ret = btrfs_next_item(root, path);
7878 /* Ensure all chunks have corresponding dev extents */
7879 ret = verify_chunk_dev_extent_mapping(fs_info);
7881 btrfs_free_path(path);
7886 * Check whether the given block group or device is pinned by any inode being
7887 * used as a swapfile.
7889 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7891 struct btrfs_swapfile_pin *sp;
7892 struct rb_node *node;
7894 spin_lock(&fs_info->swapfile_pins_lock);
7895 node = fs_info->swapfile_pins.rb_node;
7897 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7899 node = node->rb_left;
7900 else if (ptr > sp->ptr)
7901 node = node->rb_right;
7905 spin_unlock(&fs_info->swapfile_pins_lock);
7906 return node != NULL;