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->alloc_list);
323 INIT_LIST_HEAD(&fs_devs->fs_list);
325 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
328 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
330 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
335 void btrfs_free_device(struct btrfs_device *device)
337 WARN_ON(!list_empty(&device->post_commit_list));
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->post_commit_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;
2859 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2862 new_size = round_down(new_size, fs_info->sectorsize);
2864 mutex_lock(&fs_info->chunk_mutex);
2865 old_total = btrfs_super_total_bytes(super_copy);
2866 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2868 if (new_size <= device->total_bytes ||
2869 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2870 mutex_unlock(&fs_info->chunk_mutex);
2874 btrfs_set_super_total_bytes(super_copy,
2875 round_down(old_total + diff, fs_info->sectorsize));
2876 device->fs_devices->total_rw_bytes += diff;
2878 btrfs_device_set_total_bytes(device, new_size);
2879 btrfs_device_set_disk_total_bytes(device, new_size);
2880 btrfs_clear_space_info_full(device->fs_info);
2881 if (list_empty(&device->post_commit_list))
2882 list_add_tail(&device->post_commit_list,
2883 &trans->transaction->dev_update_list);
2884 mutex_unlock(&fs_info->chunk_mutex);
2886 return btrfs_update_device(trans, device);
2889 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2891 struct btrfs_fs_info *fs_info = trans->fs_info;
2892 struct btrfs_root *root = fs_info->chunk_root;
2894 struct btrfs_path *path;
2895 struct btrfs_key key;
2897 path = btrfs_alloc_path();
2901 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2902 key.offset = chunk_offset;
2903 key.type = BTRFS_CHUNK_ITEM_KEY;
2905 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2908 else if (ret > 0) { /* Logic error or corruption */
2909 btrfs_handle_fs_error(fs_info, -ENOENT,
2910 "Failed lookup while freeing chunk.");
2915 ret = btrfs_del_item(trans, root, path);
2917 btrfs_handle_fs_error(fs_info, ret,
2918 "Failed to delete chunk item.");
2920 btrfs_free_path(path);
2924 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2926 struct btrfs_super_block *super_copy = fs_info->super_copy;
2927 struct btrfs_disk_key *disk_key;
2928 struct btrfs_chunk *chunk;
2935 struct btrfs_key key;
2937 mutex_lock(&fs_info->chunk_mutex);
2938 array_size = btrfs_super_sys_array_size(super_copy);
2940 ptr = super_copy->sys_chunk_array;
2943 while (cur < array_size) {
2944 disk_key = (struct btrfs_disk_key *)ptr;
2945 btrfs_disk_key_to_cpu(&key, disk_key);
2947 len = sizeof(*disk_key);
2949 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2950 chunk = (struct btrfs_chunk *)(ptr + len);
2951 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2952 len += btrfs_chunk_item_size(num_stripes);
2957 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2958 key.offset == chunk_offset) {
2959 memmove(ptr, ptr + len, array_size - (cur + len));
2961 btrfs_set_super_sys_array_size(super_copy, array_size);
2967 mutex_unlock(&fs_info->chunk_mutex);
2972 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2973 * @logical: Logical block offset in bytes.
2974 * @length: Length of extent in bytes.
2976 * Return: Chunk mapping or ERR_PTR.
2978 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2979 u64 logical, u64 length)
2981 struct extent_map_tree *em_tree;
2982 struct extent_map *em;
2984 em_tree = &fs_info->mapping_tree.map_tree;
2985 read_lock(&em_tree->lock);
2986 em = lookup_extent_mapping(em_tree, logical, length);
2987 read_unlock(&em_tree->lock);
2990 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2992 return ERR_PTR(-EINVAL);
2995 if (em->start > logical || em->start + em->len < logical) {
2997 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2998 logical, length, em->start, em->start + em->len);
2999 free_extent_map(em);
3000 return ERR_PTR(-EINVAL);
3003 /* callers are responsible for dropping em's ref. */
3007 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3009 struct btrfs_fs_info *fs_info = trans->fs_info;
3010 struct extent_map *em;
3011 struct map_lookup *map;
3012 u64 dev_extent_len = 0;
3014 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3016 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3019 * This is a logic error, but we don't want to just rely on the
3020 * user having built with ASSERT enabled, so if ASSERT doesn't
3021 * do anything we still error out.
3026 map = em->map_lookup;
3027 mutex_lock(&fs_info->chunk_mutex);
3028 check_system_chunk(trans, map->type);
3029 mutex_unlock(&fs_info->chunk_mutex);
3032 * Take the device list mutex to prevent races with the final phase of
3033 * a device replace operation that replaces the device object associated
3034 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
3036 mutex_lock(&fs_devices->device_list_mutex);
3037 for (i = 0; i < map->num_stripes; i++) {
3038 struct btrfs_device *device = map->stripes[i].dev;
3039 ret = btrfs_free_dev_extent(trans, device,
3040 map->stripes[i].physical,
3043 mutex_unlock(&fs_devices->device_list_mutex);
3044 btrfs_abort_transaction(trans, ret);
3048 if (device->bytes_used > 0) {
3049 mutex_lock(&fs_info->chunk_mutex);
3050 btrfs_device_set_bytes_used(device,
3051 device->bytes_used - dev_extent_len);
3052 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3053 btrfs_clear_space_info_full(fs_info);
3054 mutex_unlock(&fs_info->chunk_mutex);
3057 ret = btrfs_update_device(trans, device);
3059 mutex_unlock(&fs_devices->device_list_mutex);
3060 btrfs_abort_transaction(trans, ret);
3064 mutex_unlock(&fs_devices->device_list_mutex);
3066 ret = btrfs_free_chunk(trans, chunk_offset);
3068 btrfs_abort_transaction(trans, ret);
3072 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3074 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3075 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3077 btrfs_abort_transaction(trans, ret);
3082 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3084 btrfs_abort_transaction(trans, ret);
3090 free_extent_map(em);
3094 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3096 struct btrfs_root *root = fs_info->chunk_root;
3097 struct btrfs_trans_handle *trans;
3101 * Prevent races with automatic removal of unused block groups.
3102 * After we relocate and before we remove the chunk with offset
3103 * chunk_offset, automatic removal of the block group can kick in,
3104 * resulting in a failure when calling btrfs_remove_chunk() below.
3106 * Make sure to acquire this mutex before doing a tree search (dev
3107 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3108 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3109 * we release the path used to search the chunk/dev tree and before
3110 * the current task acquires this mutex and calls us.
3112 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3114 ret = btrfs_can_relocate(fs_info, chunk_offset);
3118 /* step one, relocate all the extents inside this chunk */
3119 btrfs_scrub_pause(fs_info);
3120 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3121 btrfs_scrub_continue(fs_info);
3126 * We add the kobjects here (and after forcing data chunk creation)
3127 * since relocation is the only place we'll create chunks of a new
3128 * type at runtime. The only place where we'll remove the last
3129 * chunk of a type is the call immediately below this one. Even
3130 * so, we're protected against races with the cleaner thread since
3131 * we're covered by the delete_unused_bgs_mutex.
3133 btrfs_add_raid_kobjects(fs_info);
3135 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3137 if (IS_ERR(trans)) {
3138 ret = PTR_ERR(trans);
3139 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3144 * step two, delete the device extents and the
3145 * chunk tree entries
3147 ret = btrfs_remove_chunk(trans, chunk_offset);
3148 btrfs_end_transaction(trans);
3152 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3154 struct btrfs_root *chunk_root = fs_info->chunk_root;
3155 struct btrfs_path *path;
3156 struct extent_buffer *leaf;
3157 struct btrfs_chunk *chunk;
3158 struct btrfs_key key;
3159 struct btrfs_key found_key;
3161 bool retried = false;
3165 path = btrfs_alloc_path();
3170 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3171 key.offset = (u64)-1;
3172 key.type = BTRFS_CHUNK_ITEM_KEY;
3175 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3176 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3178 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3181 BUG_ON(ret == 0); /* Corruption */
3183 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3186 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3192 leaf = path->nodes[0];
3193 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3195 chunk = btrfs_item_ptr(leaf, path->slots[0],
3196 struct btrfs_chunk);
3197 chunk_type = btrfs_chunk_type(leaf, chunk);
3198 btrfs_release_path(path);
3200 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3201 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3207 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3209 if (found_key.offset == 0)
3211 key.offset = found_key.offset - 1;
3214 if (failed && !retried) {
3218 } else if (WARN_ON(failed && retried)) {
3222 btrfs_free_path(path);
3227 * return 1 : allocate a data chunk successfully,
3228 * return <0: errors during allocating a data chunk,
3229 * return 0 : no need to allocate a data chunk.
3231 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3234 struct btrfs_block_group_cache *cache;
3238 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3240 chunk_type = cache->flags;
3241 btrfs_put_block_group(cache);
3243 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3244 spin_lock(&fs_info->data_sinfo->lock);
3245 bytes_used = fs_info->data_sinfo->bytes_used;
3246 spin_unlock(&fs_info->data_sinfo->lock);
3249 struct btrfs_trans_handle *trans;
3252 trans = btrfs_join_transaction(fs_info->tree_root);
3254 return PTR_ERR(trans);
3256 ret = btrfs_force_chunk_alloc(trans,
3257 BTRFS_BLOCK_GROUP_DATA);
3258 btrfs_end_transaction(trans);
3262 btrfs_add_raid_kobjects(fs_info);
3270 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3271 struct btrfs_balance_control *bctl)
3273 struct btrfs_root *root = fs_info->tree_root;
3274 struct btrfs_trans_handle *trans;
3275 struct btrfs_balance_item *item;
3276 struct btrfs_disk_balance_args disk_bargs;
3277 struct btrfs_path *path;
3278 struct extent_buffer *leaf;
3279 struct btrfs_key key;
3282 path = btrfs_alloc_path();
3286 trans = btrfs_start_transaction(root, 0);
3287 if (IS_ERR(trans)) {
3288 btrfs_free_path(path);
3289 return PTR_ERR(trans);
3292 key.objectid = BTRFS_BALANCE_OBJECTID;
3293 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3296 ret = btrfs_insert_empty_item(trans, root, path, &key,
3301 leaf = path->nodes[0];
3302 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3304 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3306 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3307 btrfs_set_balance_data(leaf, item, &disk_bargs);
3308 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3309 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3310 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3311 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3313 btrfs_set_balance_flags(leaf, item, bctl->flags);
3315 btrfs_mark_buffer_dirty(leaf);
3317 btrfs_free_path(path);
3318 err = btrfs_commit_transaction(trans);
3324 static int del_balance_item(struct btrfs_fs_info *fs_info)
3326 struct btrfs_root *root = fs_info->tree_root;
3327 struct btrfs_trans_handle *trans;
3328 struct btrfs_path *path;
3329 struct btrfs_key key;
3332 path = btrfs_alloc_path();
3336 trans = btrfs_start_transaction(root, 0);
3337 if (IS_ERR(trans)) {
3338 btrfs_free_path(path);
3339 return PTR_ERR(trans);
3342 key.objectid = BTRFS_BALANCE_OBJECTID;
3343 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3346 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3354 ret = btrfs_del_item(trans, root, path);
3356 btrfs_free_path(path);
3357 err = btrfs_commit_transaction(trans);
3364 * This is a heuristic used to reduce the number of chunks balanced on
3365 * resume after balance was interrupted.
3367 static void update_balance_args(struct btrfs_balance_control *bctl)
3370 * Turn on soft mode for chunk types that were being converted.
3372 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3373 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3374 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3375 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3376 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3377 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3380 * Turn on usage filter if is not already used. The idea is
3381 * that chunks that we have already balanced should be
3382 * reasonably full. Don't do it for chunks that are being
3383 * converted - that will keep us from relocating unconverted
3384 * (albeit full) chunks.
3386 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3387 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3388 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3389 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3390 bctl->data.usage = 90;
3392 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3393 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3394 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3395 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3396 bctl->sys.usage = 90;
3398 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3399 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3400 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3401 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3402 bctl->meta.usage = 90;
3407 * Clear the balance status in fs_info and delete the balance item from disk.
3409 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3411 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3414 BUG_ON(!fs_info->balance_ctl);
3416 spin_lock(&fs_info->balance_lock);
3417 fs_info->balance_ctl = NULL;
3418 spin_unlock(&fs_info->balance_lock);
3421 ret = del_balance_item(fs_info);
3423 btrfs_handle_fs_error(fs_info, ret, NULL);
3427 * Balance filters. Return 1 if chunk should be filtered out
3428 * (should not be balanced).
3430 static int chunk_profiles_filter(u64 chunk_type,
3431 struct btrfs_balance_args *bargs)
3433 chunk_type = chunk_to_extended(chunk_type) &
3434 BTRFS_EXTENDED_PROFILE_MASK;
3436 if (bargs->profiles & chunk_type)
3442 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3443 struct btrfs_balance_args *bargs)
3445 struct btrfs_block_group_cache *cache;
3447 u64 user_thresh_min;
3448 u64 user_thresh_max;
3451 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3452 chunk_used = btrfs_block_group_used(&cache->item);
3454 if (bargs->usage_min == 0)
3455 user_thresh_min = 0;
3457 user_thresh_min = div_factor_fine(cache->key.offset,
3460 if (bargs->usage_max == 0)
3461 user_thresh_max = 1;
3462 else if (bargs->usage_max > 100)
3463 user_thresh_max = cache->key.offset;
3465 user_thresh_max = div_factor_fine(cache->key.offset,
3468 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3471 btrfs_put_block_group(cache);
3475 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3476 u64 chunk_offset, struct btrfs_balance_args *bargs)
3478 struct btrfs_block_group_cache *cache;
3479 u64 chunk_used, user_thresh;
3482 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3483 chunk_used = btrfs_block_group_used(&cache->item);
3485 if (bargs->usage_min == 0)
3487 else if (bargs->usage > 100)
3488 user_thresh = cache->key.offset;
3490 user_thresh = div_factor_fine(cache->key.offset,
3493 if (chunk_used < user_thresh)
3496 btrfs_put_block_group(cache);
3500 static int chunk_devid_filter(struct extent_buffer *leaf,
3501 struct btrfs_chunk *chunk,
3502 struct btrfs_balance_args *bargs)
3504 struct btrfs_stripe *stripe;
3505 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3508 for (i = 0; i < num_stripes; i++) {
3509 stripe = btrfs_stripe_nr(chunk, i);
3510 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3517 /* [pstart, pend) */
3518 static int chunk_drange_filter(struct extent_buffer *leaf,
3519 struct btrfs_chunk *chunk,
3520 struct btrfs_balance_args *bargs)
3522 struct btrfs_stripe *stripe;
3523 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3529 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3532 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3533 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3534 factor = num_stripes / 2;
3535 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3536 factor = num_stripes - 1;
3537 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3538 factor = num_stripes - 2;
3540 factor = num_stripes;
3543 for (i = 0; i < num_stripes; i++) {
3544 stripe = btrfs_stripe_nr(chunk, i);
3545 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3548 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3549 stripe_length = btrfs_chunk_length(leaf, chunk);
3550 stripe_length = div_u64(stripe_length, factor);
3552 if (stripe_offset < bargs->pend &&
3553 stripe_offset + stripe_length > bargs->pstart)
3560 /* [vstart, vend) */
3561 static int chunk_vrange_filter(struct extent_buffer *leaf,
3562 struct btrfs_chunk *chunk,
3564 struct btrfs_balance_args *bargs)
3566 if (chunk_offset < bargs->vend &&
3567 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3568 /* at least part of the chunk is inside this vrange */
3574 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3575 struct btrfs_chunk *chunk,
3576 struct btrfs_balance_args *bargs)
3578 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3580 if (bargs->stripes_min <= num_stripes
3581 && num_stripes <= bargs->stripes_max)
3587 static int chunk_soft_convert_filter(u64 chunk_type,
3588 struct btrfs_balance_args *bargs)
3590 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3593 chunk_type = chunk_to_extended(chunk_type) &
3594 BTRFS_EXTENDED_PROFILE_MASK;
3596 if (bargs->target == chunk_type)
3602 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3603 struct extent_buffer *leaf,
3604 struct btrfs_chunk *chunk, u64 chunk_offset)
3606 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3607 struct btrfs_balance_args *bargs = NULL;
3608 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3611 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3612 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3616 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3617 bargs = &bctl->data;
3618 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3620 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3621 bargs = &bctl->meta;
3623 /* profiles filter */
3624 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3625 chunk_profiles_filter(chunk_type, bargs)) {
3630 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3631 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3633 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3634 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3639 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3640 chunk_devid_filter(leaf, chunk, bargs)) {
3644 /* drange filter, makes sense only with devid filter */
3645 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3646 chunk_drange_filter(leaf, chunk, bargs)) {
3651 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3652 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3656 /* stripes filter */
3657 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3658 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3662 /* soft profile changing mode */
3663 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3664 chunk_soft_convert_filter(chunk_type, bargs)) {
3669 * limited by count, must be the last filter
3671 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3672 if (bargs->limit == 0)
3676 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3678 * Same logic as the 'limit' filter; the minimum cannot be
3679 * determined here because we do not have the global information
3680 * about the count of all chunks that satisfy the filters.
3682 if (bargs->limit_max == 0)
3691 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3693 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3694 struct btrfs_root *chunk_root = fs_info->chunk_root;
3696 struct btrfs_chunk *chunk;
3697 struct btrfs_path *path = NULL;
3698 struct btrfs_key key;
3699 struct btrfs_key found_key;
3700 struct extent_buffer *leaf;
3703 int enospc_errors = 0;
3704 bool counting = true;
3705 /* The single value limit and min/max limits use the same bytes in the */
3706 u64 limit_data = bctl->data.limit;
3707 u64 limit_meta = bctl->meta.limit;
3708 u64 limit_sys = bctl->sys.limit;
3712 int chunk_reserved = 0;
3714 path = btrfs_alloc_path();
3720 /* zero out stat counters */
3721 spin_lock(&fs_info->balance_lock);
3722 memset(&bctl->stat, 0, sizeof(bctl->stat));
3723 spin_unlock(&fs_info->balance_lock);
3727 * The single value limit and min/max limits use the same bytes
3730 bctl->data.limit = limit_data;
3731 bctl->meta.limit = limit_meta;
3732 bctl->sys.limit = limit_sys;
3734 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3735 key.offset = (u64)-1;
3736 key.type = BTRFS_CHUNK_ITEM_KEY;
3739 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3740 atomic_read(&fs_info->balance_cancel_req)) {
3745 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3746 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3748 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3753 * this shouldn't happen, it means the last relocate
3757 BUG(); /* FIXME break ? */
3759 ret = btrfs_previous_item(chunk_root, path, 0,
3760 BTRFS_CHUNK_ITEM_KEY);
3762 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3767 leaf = path->nodes[0];
3768 slot = path->slots[0];
3769 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3771 if (found_key.objectid != key.objectid) {
3772 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3776 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3777 chunk_type = btrfs_chunk_type(leaf, chunk);
3780 spin_lock(&fs_info->balance_lock);
3781 bctl->stat.considered++;
3782 spin_unlock(&fs_info->balance_lock);
3785 ret = should_balance_chunk(fs_info, leaf, chunk,
3788 btrfs_release_path(path);
3790 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3795 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3796 spin_lock(&fs_info->balance_lock);
3797 bctl->stat.expected++;
3798 spin_unlock(&fs_info->balance_lock);
3800 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3802 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3804 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3811 * Apply limit_min filter, no need to check if the LIMITS
3812 * filter is used, limit_min is 0 by default
3814 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3815 count_data < bctl->data.limit_min)
3816 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3817 count_meta < bctl->meta.limit_min)
3818 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3819 count_sys < bctl->sys.limit_min)) {
3820 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3824 if (!chunk_reserved) {
3826 * We may be relocating the only data chunk we have,
3827 * which could potentially end up with losing data's
3828 * raid profile, so lets allocate an empty one in
3831 ret = btrfs_may_alloc_data_chunk(fs_info,
3834 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3836 } else if (ret == 1) {
3841 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3842 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3843 if (ret == -ENOSPC) {
3845 } else if (ret == -ETXTBSY) {
3847 "skipping relocation of block group %llu due to active swapfile",
3853 spin_lock(&fs_info->balance_lock);
3854 bctl->stat.completed++;
3855 spin_unlock(&fs_info->balance_lock);
3858 if (found_key.offset == 0)
3860 key.offset = found_key.offset - 1;
3864 btrfs_release_path(path);
3869 btrfs_free_path(path);
3870 if (enospc_errors) {
3871 btrfs_info(fs_info, "%d enospc errors during balance",
3881 * alloc_profile_is_valid - see if a given profile is valid and reduced
3882 * @flags: profile to validate
3883 * @extended: if true @flags is treated as an extended profile
3885 static int alloc_profile_is_valid(u64 flags, int extended)
3887 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3888 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3890 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3892 /* 1) check that all other bits are zeroed */
3896 /* 2) see if profile is reduced */
3898 return !extended; /* "0" is valid for usual profiles */
3900 /* true if exactly one bit set */
3901 return is_power_of_2(flags);
3904 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3906 /* cancel requested || normal exit path */
3907 return atomic_read(&fs_info->balance_cancel_req) ||
3908 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3909 atomic_read(&fs_info->balance_cancel_req) == 0);
3912 /* Non-zero return value signifies invalidity */
3913 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3916 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3917 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3918 (bctl_arg->target & ~allowed)));
3922 * Fill @buf with textual description of balance filter flags @bargs, up to
3923 * @size_buf including the terminating null. The output may be trimmed if it
3924 * does not fit into the provided buffer.
3926 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3930 u32 size_bp = size_buf;
3932 u64 flags = bargs->flags;
3933 char tmp_buf[128] = {'\0'};
3938 #define CHECK_APPEND_NOARG(a) \
3940 ret = snprintf(bp, size_bp, (a)); \
3941 if (ret < 0 || ret >= size_bp) \
3942 goto out_overflow; \
3947 #define CHECK_APPEND_1ARG(a, v1) \
3949 ret = snprintf(bp, size_bp, (a), (v1)); \
3950 if (ret < 0 || ret >= size_bp) \
3951 goto out_overflow; \
3956 #define CHECK_APPEND_2ARG(a, v1, v2) \
3958 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3959 if (ret < 0 || ret >= size_bp) \
3960 goto out_overflow; \
3965 if (flags & BTRFS_BALANCE_ARGS_CONVERT) {
3966 int index = btrfs_bg_flags_to_raid_index(bargs->target);
3968 CHECK_APPEND_1ARG("convert=%s,", get_raid_name(index));
3971 if (flags & BTRFS_BALANCE_ARGS_SOFT)
3972 CHECK_APPEND_NOARG("soft,");
3974 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
3975 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
3977 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
3980 if (flags & BTRFS_BALANCE_ARGS_USAGE)
3981 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
3983 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
3984 CHECK_APPEND_2ARG("usage=%u..%u,",
3985 bargs->usage_min, bargs->usage_max);
3987 if (flags & BTRFS_BALANCE_ARGS_DEVID)
3988 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
3990 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
3991 CHECK_APPEND_2ARG("drange=%llu..%llu,",
3992 bargs->pstart, bargs->pend);
3994 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
3995 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
3996 bargs->vstart, bargs->vend);
3998 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
3999 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4001 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4002 CHECK_APPEND_2ARG("limit=%u..%u,",
4003 bargs->limit_min, bargs->limit_max);
4005 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4006 CHECK_APPEND_2ARG("stripes=%u..%u,",
4007 bargs->stripes_min, bargs->stripes_max);
4009 #undef CHECK_APPEND_2ARG
4010 #undef CHECK_APPEND_1ARG
4011 #undef CHECK_APPEND_NOARG
4015 if (size_bp < size_buf)
4016 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4021 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4023 u32 size_buf = 1024;
4024 char tmp_buf[192] = {'\0'};
4027 u32 size_bp = size_buf;
4029 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4031 buf = kzalloc(size_buf, GFP_KERNEL);
4037 #define CHECK_APPEND_1ARG(a, v1) \
4039 ret = snprintf(bp, size_bp, (a), (v1)); \
4040 if (ret < 0 || ret >= size_bp) \
4041 goto out_overflow; \
4046 if (bctl->flags & BTRFS_BALANCE_FORCE)
4047 CHECK_APPEND_1ARG("%s", "-f ");
4049 if (bctl->flags & BTRFS_BALANCE_DATA) {
4050 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4051 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4054 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4055 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4056 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4059 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4060 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4061 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4064 #undef CHECK_APPEND_1ARG
4068 if (size_bp < size_buf)
4069 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4070 btrfs_info(fs_info, "balance: %s %s",
4071 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4072 "resume" : "start", buf);
4078 * Should be called with balance mutexe held
4080 int btrfs_balance(struct btrfs_fs_info *fs_info,
4081 struct btrfs_balance_control *bctl,
4082 struct btrfs_ioctl_balance_args *bargs)
4084 u64 meta_target, data_target;
4090 bool reducing_integrity;
4092 if (btrfs_fs_closing(fs_info) ||
4093 atomic_read(&fs_info->balance_pause_req) ||
4094 atomic_read(&fs_info->balance_cancel_req)) {
4099 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4100 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4104 * In case of mixed groups both data and meta should be picked,
4105 * and identical options should be given for both of them.
4107 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4108 if (mixed && (bctl->flags & allowed)) {
4109 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4110 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4111 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4113 "balance: mixed groups data and metadata options must be the same");
4119 num_devices = btrfs_num_devices(fs_info);
4121 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
4122 if (num_devices > 1)
4123 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
4124 if (num_devices > 2)
4125 allowed |= BTRFS_BLOCK_GROUP_RAID5;
4126 if (num_devices > 3)
4127 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
4128 BTRFS_BLOCK_GROUP_RAID6);
4129 if (validate_convert_profile(&bctl->data, allowed)) {
4130 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
4133 "balance: invalid convert data profile %s",
4134 get_raid_name(index));
4138 if (validate_convert_profile(&bctl->meta, allowed)) {
4139 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
4142 "balance: invalid convert metadata profile %s",
4143 get_raid_name(index));
4147 if (validate_convert_profile(&bctl->sys, allowed)) {
4148 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
4151 "balance: invalid convert system profile %s",
4152 get_raid_name(index));
4157 /* allow to reduce meta or sys integrity only if force set */
4158 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
4159 BTRFS_BLOCK_GROUP_RAID10 |
4160 BTRFS_BLOCK_GROUP_RAID5 |
4161 BTRFS_BLOCK_GROUP_RAID6;
4163 seq = read_seqbegin(&fs_info->profiles_lock);
4165 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4166 (fs_info->avail_system_alloc_bits & allowed) &&
4167 !(bctl->sys.target & allowed)) ||
4168 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4169 (fs_info->avail_metadata_alloc_bits & allowed) &&
4170 !(bctl->meta.target & allowed)))
4171 reducing_integrity = true;
4173 reducing_integrity = false;
4175 /* if we're not converting, the target field is uninitialized */
4176 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4177 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4178 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4179 bctl->data.target : fs_info->avail_data_alloc_bits;
4180 } while (read_seqretry(&fs_info->profiles_lock, seq));
4182 if (reducing_integrity) {
4183 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4185 "balance: force reducing metadata integrity");
4188 "balance: reduces metadata integrity, use --force if you want this");
4194 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4195 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4196 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
4197 int data_index = btrfs_bg_flags_to_raid_index(data_target);
4200 "balance: metadata profile %s has lower redundancy than data profile %s",
4201 get_raid_name(meta_index), get_raid_name(data_index));
4204 ret = insert_balance_item(fs_info, bctl);
4205 if (ret && ret != -EEXIST)
4208 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4209 BUG_ON(ret == -EEXIST);
4210 BUG_ON(fs_info->balance_ctl);
4211 spin_lock(&fs_info->balance_lock);
4212 fs_info->balance_ctl = bctl;
4213 spin_unlock(&fs_info->balance_lock);
4215 BUG_ON(ret != -EEXIST);
4216 spin_lock(&fs_info->balance_lock);
4217 update_balance_args(bctl);
4218 spin_unlock(&fs_info->balance_lock);
4221 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4222 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4223 describe_balance_start_or_resume(fs_info);
4224 mutex_unlock(&fs_info->balance_mutex);
4226 ret = __btrfs_balance(fs_info);
4228 mutex_lock(&fs_info->balance_mutex);
4229 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4230 btrfs_info(fs_info, "balance: paused");
4231 else if (ret == -ECANCELED && atomic_read(&fs_info->balance_cancel_req))
4232 btrfs_info(fs_info, "balance: canceled");
4234 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4236 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4239 memset(bargs, 0, sizeof(*bargs));
4240 btrfs_update_ioctl_balance_args(fs_info, bargs);
4243 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4244 balance_need_close(fs_info)) {
4245 reset_balance_state(fs_info);
4246 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4249 wake_up(&fs_info->balance_wait_q);
4253 if (bctl->flags & BTRFS_BALANCE_RESUME)
4254 reset_balance_state(fs_info);
4257 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4262 static int balance_kthread(void *data)
4264 struct btrfs_fs_info *fs_info = data;
4267 mutex_lock(&fs_info->balance_mutex);
4268 if (fs_info->balance_ctl)
4269 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4270 mutex_unlock(&fs_info->balance_mutex);
4275 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4277 struct task_struct *tsk;
4279 mutex_lock(&fs_info->balance_mutex);
4280 if (!fs_info->balance_ctl) {
4281 mutex_unlock(&fs_info->balance_mutex);
4284 mutex_unlock(&fs_info->balance_mutex);
4286 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4287 btrfs_info(fs_info, "balance: resume skipped");
4292 * A ro->rw remount sequence should continue with the paused balance
4293 * regardless of who pauses it, system or the user as of now, so set
4296 spin_lock(&fs_info->balance_lock);
4297 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4298 spin_unlock(&fs_info->balance_lock);
4300 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4301 return PTR_ERR_OR_ZERO(tsk);
4304 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4306 struct btrfs_balance_control *bctl;
4307 struct btrfs_balance_item *item;
4308 struct btrfs_disk_balance_args disk_bargs;
4309 struct btrfs_path *path;
4310 struct extent_buffer *leaf;
4311 struct btrfs_key key;
4314 path = btrfs_alloc_path();
4318 key.objectid = BTRFS_BALANCE_OBJECTID;
4319 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4322 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4325 if (ret > 0) { /* ret = -ENOENT; */
4330 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4336 leaf = path->nodes[0];
4337 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4339 bctl->flags = btrfs_balance_flags(leaf, item);
4340 bctl->flags |= BTRFS_BALANCE_RESUME;
4342 btrfs_balance_data(leaf, item, &disk_bargs);
4343 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4344 btrfs_balance_meta(leaf, item, &disk_bargs);
4345 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4346 btrfs_balance_sys(leaf, item, &disk_bargs);
4347 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4350 * This should never happen, as the paused balance state is recovered
4351 * during mount without any chance of other exclusive ops to collide.
4353 * This gives the exclusive op status to balance and keeps in paused
4354 * state until user intervention (cancel or umount). If the ownership
4355 * cannot be assigned, show a message but do not fail. The balance
4356 * is in a paused state and must have fs_info::balance_ctl properly
4359 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4361 "balance: cannot set exclusive op status, resume manually");
4363 mutex_lock(&fs_info->balance_mutex);
4364 BUG_ON(fs_info->balance_ctl);
4365 spin_lock(&fs_info->balance_lock);
4366 fs_info->balance_ctl = bctl;
4367 spin_unlock(&fs_info->balance_lock);
4368 mutex_unlock(&fs_info->balance_mutex);
4370 btrfs_free_path(path);
4374 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4378 mutex_lock(&fs_info->balance_mutex);
4379 if (!fs_info->balance_ctl) {
4380 mutex_unlock(&fs_info->balance_mutex);
4384 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4385 atomic_inc(&fs_info->balance_pause_req);
4386 mutex_unlock(&fs_info->balance_mutex);
4388 wait_event(fs_info->balance_wait_q,
4389 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4391 mutex_lock(&fs_info->balance_mutex);
4392 /* we are good with balance_ctl ripped off from under us */
4393 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4394 atomic_dec(&fs_info->balance_pause_req);
4399 mutex_unlock(&fs_info->balance_mutex);
4403 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4405 mutex_lock(&fs_info->balance_mutex);
4406 if (!fs_info->balance_ctl) {
4407 mutex_unlock(&fs_info->balance_mutex);
4412 * A paused balance with the item stored on disk can be resumed at
4413 * mount time if the mount is read-write. Otherwise it's still paused
4414 * and we must not allow cancelling as it deletes the item.
4416 if (sb_rdonly(fs_info->sb)) {
4417 mutex_unlock(&fs_info->balance_mutex);
4421 atomic_inc(&fs_info->balance_cancel_req);
4423 * if we are running just wait and return, balance item is
4424 * deleted in btrfs_balance in this case
4426 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4427 mutex_unlock(&fs_info->balance_mutex);
4428 wait_event(fs_info->balance_wait_q,
4429 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4430 mutex_lock(&fs_info->balance_mutex);
4432 mutex_unlock(&fs_info->balance_mutex);
4434 * Lock released to allow other waiters to continue, we'll
4435 * reexamine the status again.
4437 mutex_lock(&fs_info->balance_mutex);
4439 if (fs_info->balance_ctl) {
4440 reset_balance_state(fs_info);
4441 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4442 btrfs_info(fs_info, "balance: canceled");
4446 BUG_ON(fs_info->balance_ctl ||
4447 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4448 atomic_dec(&fs_info->balance_cancel_req);
4449 mutex_unlock(&fs_info->balance_mutex);
4453 static int btrfs_uuid_scan_kthread(void *data)
4455 struct btrfs_fs_info *fs_info = data;
4456 struct btrfs_root *root = fs_info->tree_root;
4457 struct btrfs_key key;
4458 struct btrfs_path *path = NULL;
4460 struct extent_buffer *eb;
4462 struct btrfs_root_item root_item;
4464 struct btrfs_trans_handle *trans = NULL;
4466 path = btrfs_alloc_path();
4473 key.type = BTRFS_ROOT_ITEM_KEY;
4477 ret = btrfs_search_forward(root, &key, path,
4478 BTRFS_OLDEST_GENERATION);
4485 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4486 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4487 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4488 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4491 eb = path->nodes[0];
4492 slot = path->slots[0];
4493 item_size = btrfs_item_size_nr(eb, slot);
4494 if (item_size < sizeof(root_item))
4497 read_extent_buffer(eb, &root_item,
4498 btrfs_item_ptr_offset(eb, slot),
4499 (int)sizeof(root_item));
4500 if (btrfs_root_refs(&root_item) == 0)
4503 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4504 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4508 btrfs_release_path(path);
4510 * 1 - subvol uuid item
4511 * 1 - received_subvol uuid item
4513 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4514 if (IS_ERR(trans)) {
4515 ret = PTR_ERR(trans);
4523 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4524 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4525 BTRFS_UUID_KEY_SUBVOL,
4528 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4534 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4535 ret = btrfs_uuid_tree_add(trans,
4536 root_item.received_uuid,
4537 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4540 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4548 ret = btrfs_end_transaction(trans);
4554 btrfs_release_path(path);
4555 if (key.offset < (u64)-1) {
4557 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4559 key.type = BTRFS_ROOT_ITEM_KEY;
4560 } else if (key.objectid < (u64)-1) {
4562 key.type = BTRFS_ROOT_ITEM_KEY;
4571 btrfs_free_path(path);
4572 if (trans && !IS_ERR(trans))
4573 btrfs_end_transaction(trans);
4575 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4577 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4578 up(&fs_info->uuid_tree_rescan_sem);
4583 * Callback for btrfs_uuid_tree_iterate().
4585 * 0 check succeeded, the entry is not outdated.
4586 * < 0 if an error occurred.
4587 * > 0 if the check failed, which means the caller shall remove the entry.
4589 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4590 u8 *uuid, u8 type, u64 subid)
4592 struct btrfs_key key;
4594 struct btrfs_root *subvol_root;
4596 if (type != BTRFS_UUID_KEY_SUBVOL &&
4597 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4600 key.objectid = subid;
4601 key.type = BTRFS_ROOT_ITEM_KEY;
4602 key.offset = (u64)-1;
4603 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4604 if (IS_ERR(subvol_root)) {
4605 ret = PTR_ERR(subvol_root);
4612 case BTRFS_UUID_KEY_SUBVOL:
4613 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4616 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4617 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4627 static int btrfs_uuid_rescan_kthread(void *data)
4629 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4633 * 1st step is to iterate through the existing UUID tree and
4634 * to delete all entries that contain outdated data.
4635 * 2nd step is to add all missing entries to the UUID tree.
4637 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4639 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4640 up(&fs_info->uuid_tree_rescan_sem);
4643 return btrfs_uuid_scan_kthread(data);
4646 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4648 struct btrfs_trans_handle *trans;
4649 struct btrfs_root *tree_root = fs_info->tree_root;
4650 struct btrfs_root *uuid_root;
4651 struct task_struct *task;
4658 trans = btrfs_start_transaction(tree_root, 2);
4660 return PTR_ERR(trans);
4662 uuid_root = btrfs_create_tree(trans, fs_info,
4663 BTRFS_UUID_TREE_OBJECTID);
4664 if (IS_ERR(uuid_root)) {
4665 ret = PTR_ERR(uuid_root);
4666 btrfs_abort_transaction(trans, ret);
4667 btrfs_end_transaction(trans);
4671 fs_info->uuid_root = uuid_root;
4673 ret = btrfs_commit_transaction(trans);
4677 down(&fs_info->uuid_tree_rescan_sem);
4678 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4680 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4681 btrfs_warn(fs_info, "failed to start uuid_scan task");
4682 up(&fs_info->uuid_tree_rescan_sem);
4683 return PTR_ERR(task);
4689 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4691 struct task_struct *task;
4693 down(&fs_info->uuid_tree_rescan_sem);
4694 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4696 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4697 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4698 up(&fs_info->uuid_tree_rescan_sem);
4699 return PTR_ERR(task);
4706 * shrinking a device means finding all of the device extents past
4707 * the new size, and then following the back refs to the chunks.
4708 * The chunk relocation code actually frees the device extent
4710 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4712 struct btrfs_fs_info *fs_info = device->fs_info;
4713 struct btrfs_root *root = fs_info->dev_root;
4714 struct btrfs_trans_handle *trans;
4715 struct btrfs_dev_extent *dev_extent = NULL;
4716 struct btrfs_path *path;
4722 bool retried = false;
4723 bool checked_pending_chunks = false;
4724 struct extent_buffer *l;
4725 struct btrfs_key key;
4726 struct btrfs_super_block *super_copy = fs_info->super_copy;
4727 u64 old_total = btrfs_super_total_bytes(super_copy);
4728 u64 old_size = btrfs_device_get_total_bytes(device);
4731 new_size = round_down(new_size, fs_info->sectorsize);
4732 diff = round_down(old_size - new_size, fs_info->sectorsize);
4734 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4737 path = btrfs_alloc_path();
4741 path->reada = READA_BACK;
4743 mutex_lock(&fs_info->chunk_mutex);
4745 btrfs_device_set_total_bytes(device, new_size);
4746 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4747 device->fs_devices->total_rw_bytes -= diff;
4748 atomic64_sub(diff, &fs_info->free_chunk_space);
4750 mutex_unlock(&fs_info->chunk_mutex);
4753 key.objectid = device->devid;
4754 key.offset = (u64)-1;
4755 key.type = BTRFS_DEV_EXTENT_KEY;
4758 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4759 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4761 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4765 ret = btrfs_previous_item(root, path, 0, key.type);
4767 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4772 btrfs_release_path(path);
4777 slot = path->slots[0];
4778 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4780 if (key.objectid != device->devid) {
4781 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4782 btrfs_release_path(path);
4786 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4787 length = btrfs_dev_extent_length(l, dev_extent);
4789 if (key.offset + length <= new_size) {
4790 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4791 btrfs_release_path(path);
4795 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4796 btrfs_release_path(path);
4799 * We may be relocating the only data chunk we have,
4800 * which could potentially end up with losing data's
4801 * raid profile, so lets allocate an empty one in
4804 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4806 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4810 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4811 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4812 if (ret == -ENOSPC) {
4815 if (ret == -ETXTBSY) {
4817 "could not shrink block group %llu due to active swapfile",
4822 } while (key.offset-- > 0);
4824 if (failed && !retried) {
4828 } else if (failed && retried) {
4833 /* Shrinking succeeded, else we would be at "done". */
4834 trans = btrfs_start_transaction(root, 0);
4835 if (IS_ERR(trans)) {
4836 ret = PTR_ERR(trans);
4840 mutex_lock(&fs_info->chunk_mutex);
4843 * We checked in the above loop all device extents that were already in
4844 * the device tree. However before we have updated the device's
4845 * total_bytes to the new size, we might have had chunk allocations that
4846 * have not complete yet (new block groups attached to transaction
4847 * handles), and therefore their device extents were not yet in the
4848 * device tree and we missed them in the loop above. So if we have any
4849 * pending chunk using a device extent that overlaps the device range
4850 * that we can not use anymore, commit the current transaction and
4851 * repeat the search on the device tree - this way we guarantee we will
4852 * not have chunks using device extents that end beyond 'new_size'.
4854 if (!checked_pending_chunks) {
4855 u64 start = new_size;
4856 u64 len = old_size - new_size;
4858 if (contains_pending_extent(trans->transaction, device,
4860 mutex_unlock(&fs_info->chunk_mutex);
4861 checked_pending_chunks = true;
4864 ret = btrfs_commit_transaction(trans);
4871 btrfs_device_set_disk_total_bytes(device, new_size);
4872 if (list_empty(&device->post_commit_list))
4873 list_add_tail(&device->post_commit_list,
4874 &trans->transaction->dev_update_list);
4876 WARN_ON(diff > old_total);
4877 btrfs_set_super_total_bytes(super_copy,
4878 round_down(old_total - diff, fs_info->sectorsize));
4879 mutex_unlock(&fs_info->chunk_mutex);
4881 /* Now btrfs_update_device() will change the on-disk size. */
4882 ret = btrfs_update_device(trans, device);
4884 btrfs_abort_transaction(trans, ret);
4885 btrfs_end_transaction(trans);
4887 ret = btrfs_commit_transaction(trans);
4890 btrfs_free_path(path);
4892 mutex_lock(&fs_info->chunk_mutex);
4893 btrfs_device_set_total_bytes(device, old_size);
4894 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4895 device->fs_devices->total_rw_bytes += diff;
4896 atomic64_add(diff, &fs_info->free_chunk_space);
4897 mutex_unlock(&fs_info->chunk_mutex);
4902 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4903 struct btrfs_key *key,
4904 struct btrfs_chunk *chunk, int item_size)
4906 struct btrfs_super_block *super_copy = fs_info->super_copy;
4907 struct btrfs_disk_key disk_key;
4911 mutex_lock(&fs_info->chunk_mutex);
4912 array_size = btrfs_super_sys_array_size(super_copy);
4913 if (array_size + item_size + sizeof(disk_key)
4914 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4915 mutex_unlock(&fs_info->chunk_mutex);
4919 ptr = super_copy->sys_chunk_array + array_size;
4920 btrfs_cpu_key_to_disk(&disk_key, key);
4921 memcpy(ptr, &disk_key, sizeof(disk_key));
4922 ptr += sizeof(disk_key);
4923 memcpy(ptr, chunk, item_size);
4924 item_size += sizeof(disk_key);
4925 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4926 mutex_unlock(&fs_info->chunk_mutex);
4932 * sort the devices in descending order by max_avail, total_avail
4934 static int btrfs_cmp_device_info(const void *a, const void *b)
4936 const struct btrfs_device_info *di_a = a;
4937 const struct btrfs_device_info *di_b = b;
4939 if (di_a->max_avail > di_b->max_avail)
4941 if (di_a->max_avail < di_b->max_avail)
4943 if (di_a->total_avail > di_b->total_avail)
4945 if (di_a->total_avail < di_b->total_avail)
4950 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4952 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4955 btrfs_set_fs_incompat(info, RAID56);
4958 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4959 u64 start, u64 type)
4961 struct btrfs_fs_info *info = trans->fs_info;
4962 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4963 struct btrfs_device *device;
4964 struct map_lookup *map = NULL;
4965 struct extent_map_tree *em_tree;
4966 struct extent_map *em;
4967 struct btrfs_device_info *devices_info = NULL;
4969 int num_stripes; /* total number of stripes to allocate */
4970 int data_stripes; /* number of stripes that count for
4972 int sub_stripes; /* sub_stripes info for map */
4973 int dev_stripes; /* stripes per dev */
4974 int devs_max; /* max devs to use */
4975 int devs_min; /* min devs needed */
4976 int devs_increment; /* ndevs has to be a multiple of this */
4977 int ncopies; /* how many copies to data has */
4978 int nparity; /* number of stripes worth of bytes to
4979 store parity information */
4981 u64 max_stripe_size;
4990 BUG_ON(!alloc_profile_is_valid(type, 0));
4992 if (list_empty(&fs_devices->alloc_list)) {
4993 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4994 btrfs_debug(info, "%s: no writable device", __func__);
4998 index = btrfs_bg_flags_to_raid_index(type);
5000 sub_stripes = btrfs_raid_array[index].sub_stripes;
5001 dev_stripes = btrfs_raid_array[index].dev_stripes;
5002 devs_max = btrfs_raid_array[index].devs_max;
5003 devs_min = btrfs_raid_array[index].devs_min;
5004 devs_increment = btrfs_raid_array[index].devs_increment;
5005 ncopies = btrfs_raid_array[index].ncopies;
5006 nparity = btrfs_raid_array[index].nparity;
5008 if (type & BTRFS_BLOCK_GROUP_DATA) {
5009 max_stripe_size = SZ_1G;
5010 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
5012 devs_max = BTRFS_MAX_DEVS(info);
5013 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5014 /* for larger filesystems, use larger metadata chunks */
5015 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
5016 max_stripe_size = SZ_1G;
5018 max_stripe_size = SZ_256M;
5019 max_chunk_size = max_stripe_size;
5021 devs_max = BTRFS_MAX_DEVS(info);
5022 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5023 max_stripe_size = SZ_32M;
5024 max_chunk_size = 2 * max_stripe_size;
5026 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
5028 btrfs_err(info, "invalid chunk type 0x%llx requested",
5033 /* We don't want a chunk larger than 10% of writable space */
5034 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
5037 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5043 * in the first pass through the devices list, we gather information
5044 * about the available holes on each device.
5047 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5051 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5053 "BTRFS: read-only device in alloc_list\n");
5057 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5058 &device->dev_state) ||
5059 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5062 if (device->total_bytes > device->bytes_used)
5063 total_avail = device->total_bytes - device->bytes_used;
5067 /* If there is no space on this device, skip it. */
5068 if (total_avail == 0)
5071 ret = find_free_dev_extent(trans, device,
5072 max_stripe_size * dev_stripes,
5073 &dev_offset, &max_avail);
5074 if (ret && ret != -ENOSPC)
5078 max_avail = max_stripe_size * dev_stripes;
5080 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
5081 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5083 "%s: devid %llu has no free space, have=%llu want=%u",
5084 __func__, device->devid, max_avail,
5085 BTRFS_STRIPE_LEN * dev_stripes);
5089 if (ndevs == fs_devices->rw_devices) {
5090 WARN(1, "%s: found more than %llu devices\n",
5091 __func__, fs_devices->rw_devices);
5094 devices_info[ndevs].dev_offset = dev_offset;
5095 devices_info[ndevs].max_avail = max_avail;
5096 devices_info[ndevs].total_avail = total_avail;
5097 devices_info[ndevs].dev = device;
5102 * now sort the devices by hole size / available space
5104 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5105 btrfs_cmp_device_info, NULL);
5107 /* round down to number of usable stripes */
5108 ndevs = round_down(ndevs, devs_increment);
5110 if (ndevs < devs_min) {
5112 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5114 "%s: not enough devices with free space: have=%d minimum required=%d",
5115 __func__, ndevs, devs_min);
5120 ndevs = min(ndevs, devs_max);
5123 * The primary goal is to maximize the number of stripes, so use as
5124 * many devices as possible, even if the stripes are not maximum sized.
5126 * The DUP profile stores more than one stripe per device, the
5127 * max_avail is the total size so we have to adjust.
5129 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
5130 num_stripes = ndevs * dev_stripes;
5133 * this will have to be fixed for RAID1 and RAID10 over
5136 data_stripes = (num_stripes - nparity) / ncopies;
5139 * Use the number of data stripes to figure out how big this chunk
5140 * is really going to be in terms of logical address space,
5141 * and compare that answer with the max chunk size. If it's higher,
5142 * we try to reduce stripe_size.
5144 if (stripe_size * data_stripes > max_chunk_size) {
5146 * Reduce stripe_size, round it up to a 16MB boundary again and
5147 * then use it, unless it ends up being even bigger than the
5148 * previous value we had already.
5150 stripe_size = min(round_up(div_u64(max_chunk_size,
5151 data_stripes), SZ_16M),
5155 /* align to BTRFS_STRIPE_LEN */
5156 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
5158 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5163 map->num_stripes = num_stripes;
5165 for (i = 0; i < ndevs; ++i) {
5166 for (j = 0; j < dev_stripes; ++j) {
5167 int s = i * dev_stripes + j;
5168 map->stripes[s].dev = devices_info[i].dev;
5169 map->stripes[s].physical = devices_info[i].dev_offset +
5173 map->stripe_len = BTRFS_STRIPE_LEN;
5174 map->io_align = BTRFS_STRIPE_LEN;
5175 map->io_width = BTRFS_STRIPE_LEN;
5177 map->sub_stripes = sub_stripes;
5179 chunk_size = stripe_size * data_stripes;
5181 trace_btrfs_chunk_alloc(info, map, start, chunk_size);
5183 em = alloc_extent_map();
5189 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5190 em->map_lookup = map;
5192 em->len = chunk_size;
5193 em->block_start = 0;
5194 em->block_len = em->len;
5195 em->orig_block_len = stripe_size;
5197 em_tree = &info->mapping_tree.map_tree;
5198 write_lock(&em_tree->lock);
5199 ret = add_extent_mapping(em_tree, em, 0);
5201 write_unlock(&em_tree->lock);
5202 free_extent_map(em);
5206 list_add_tail(&em->list, &trans->transaction->pending_chunks);
5207 refcount_inc(&em->refs);
5208 write_unlock(&em_tree->lock);
5210 ret = btrfs_make_block_group(trans, 0, type, start, chunk_size);
5212 goto error_del_extent;
5214 for (i = 0; i < map->num_stripes; i++) {
5215 struct btrfs_device *dev = map->stripes[i].dev;
5217 btrfs_device_set_bytes_used(dev, dev->bytes_used + stripe_size);
5218 if (list_empty(&dev->post_commit_list))
5219 list_add_tail(&dev->post_commit_list,
5220 &trans->transaction->dev_update_list);
5223 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
5225 free_extent_map(em);
5226 check_raid56_incompat_flag(info, type);
5228 kfree(devices_info);
5232 write_lock(&em_tree->lock);
5233 remove_extent_mapping(em_tree, em);
5234 write_unlock(&em_tree->lock);
5236 /* One for our allocation */
5237 free_extent_map(em);
5238 /* One for the tree reference */
5239 free_extent_map(em);
5240 /* One for the pending_chunks list reference */
5241 free_extent_map(em);
5243 kfree(devices_info);
5247 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5248 u64 chunk_offset, u64 chunk_size)
5250 struct btrfs_fs_info *fs_info = trans->fs_info;
5251 struct btrfs_root *extent_root = fs_info->extent_root;
5252 struct btrfs_root *chunk_root = fs_info->chunk_root;
5253 struct btrfs_key key;
5254 struct btrfs_device *device;
5255 struct btrfs_chunk *chunk;
5256 struct btrfs_stripe *stripe;
5257 struct extent_map *em;
5258 struct map_lookup *map;
5265 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5269 map = em->map_lookup;
5270 item_size = btrfs_chunk_item_size(map->num_stripes);
5271 stripe_size = em->orig_block_len;
5273 chunk = kzalloc(item_size, GFP_NOFS);
5280 * Take the device list mutex to prevent races with the final phase of
5281 * a device replace operation that replaces the device object associated
5282 * with the map's stripes, because the device object's id can change
5283 * at any time during that final phase of the device replace operation
5284 * (dev-replace.c:btrfs_dev_replace_finishing()).
5286 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5287 for (i = 0; i < map->num_stripes; i++) {
5288 device = map->stripes[i].dev;
5289 dev_offset = map->stripes[i].physical;
5291 ret = btrfs_update_device(trans, device);
5294 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5295 dev_offset, stripe_size);
5300 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5304 stripe = &chunk->stripe;
5305 for (i = 0; i < map->num_stripes; i++) {
5306 device = map->stripes[i].dev;
5307 dev_offset = map->stripes[i].physical;
5309 btrfs_set_stack_stripe_devid(stripe, device->devid);
5310 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5311 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5314 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5316 btrfs_set_stack_chunk_length(chunk, chunk_size);
5317 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5318 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5319 btrfs_set_stack_chunk_type(chunk, map->type);
5320 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5321 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5322 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5323 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5324 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5326 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5327 key.type = BTRFS_CHUNK_ITEM_KEY;
5328 key.offset = chunk_offset;
5330 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5331 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5333 * TODO: Cleanup of inserted chunk root in case of
5336 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5341 free_extent_map(em);
5346 * Chunk allocation falls into two parts. The first part does work
5347 * that makes the new allocated chunk usable, but does not do any operation
5348 * that modifies the chunk tree. The second part does the work that
5349 * requires modifying the chunk tree. This division is important for the
5350 * bootstrap process of adding storage to a seed btrfs.
5352 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5356 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5357 chunk_offset = find_next_chunk(trans->fs_info);
5358 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5361 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5362 struct btrfs_fs_info *fs_info)
5365 u64 sys_chunk_offset;
5369 chunk_offset = find_next_chunk(fs_info);
5370 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5371 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5375 sys_chunk_offset = find_next_chunk(fs_info);
5376 alloc_profile = btrfs_system_alloc_profile(fs_info);
5377 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5381 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5385 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5386 BTRFS_BLOCK_GROUP_RAID10 |
5387 BTRFS_BLOCK_GROUP_RAID5 |
5388 BTRFS_BLOCK_GROUP_DUP)) {
5390 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5399 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5401 struct extent_map *em;
5402 struct map_lookup *map;
5407 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5411 map = em->map_lookup;
5412 for (i = 0; i < map->num_stripes; i++) {
5413 if (test_bit(BTRFS_DEV_STATE_MISSING,
5414 &map->stripes[i].dev->dev_state)) {
5418 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5419 &map->stripes[i].dev->dev_state)) {
5426 * If the number of missing devices is larger than max errors,
5427 * we can not write the data into that chunk successfully, so
5430 if (miss_ndevs > btrfs_chunk_max_errors(map))
5433 free_extent_map(em);
5437 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5439 extent_map_tree_init(&tree->map_tree);
5442 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5444 struct extent_map *em;
5447 write_lock(&tree->map_tree.lock);
5448 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5450 remove_extent_mapping(&tree->map_tree, em);
5451 write_unlock(&tree->map_tree.lock);
5455 free_extent_map(em);
5456 /* once for the tree */
5457 free_extent_map(em);
5461 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5463 struct extent_map *em;
5464 struct map_lookup *map;
5467 em = btrfs_get_chunk_map(fs_info, logical, len);
5470 * We could return errors for these cases, but that could get
5471 * ugly and we'd probably do the same thing which is just not do
5472 * anything else and exit, so return 1 so the callers don't try
5473 * to use other copies.
5477 map = em->map_lookup;
5478 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5479 ret = map->num_stripes;
5480 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5481 ret = map->sub_stripes;
5482 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5484 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5486 * There could be two corrupted data stripes, we need
5487 * to loop retry in order to rebuild the correct data.
5489 * Fail a stripe at a time on every retry except the
5490 * stripe under reconstruction.
5492 ret = map->num_stripes;
5495 free_extent_map(em);
5497 down_read(&fs_info->dev_replace.rwsem);
5498 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5499 fs_info->dev_replace.tgtdev)
5501 up_read(&fs_info->dev_replace.rwsem);
5506 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5509 struct extent_map *em;
5510 struct map_lookup *map;
5511 unsigned long len = fs_info->sectorsize;
5513 em = btrfs_get_chunk_map(fs_info, logical, len);
5515 if (!WARN_ON(IS_ERR(em))) {
5516 map = em->map_lookup;
5517 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5518 len = map->stripe_len * nr_data_stripes(map);
5519 free_extent_map(em);
5524 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5526 struct extent_map *em;
5527 struct map_lookup *map;
5530 em = btrfs_get_chunk_map(fs_info, logical, len);
5532 if(!WARN_ON(IS_ERR(em))) {
5533 map = em->map_lookup;
5534 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5536 free_extent_map(em);
5541 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5542 struct map_lookup *map, int first,
5543 int dev_replace_is_ongoing)
5547 int preferred_mirror;
5549 struct btrfs_device *srcdev;
5552 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5554 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5555 num_stripes = map->sub_stripes;
5557 num_stripes = map->num_stripes;
5559 preferred_mirror = first + current->pid % num_stripes;
5561 if (dev_replace_is_ongoing &&
5562 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5563 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5564 srcdev = fs_info->dev_replace.srcdev;
5569 * try to avoid the drive that is the source drive for a
5570 * dev-replace procedure, only choose it if no other non-missing
5571 * mirror is available
5573 for (tolerance = 0; tolerance < 2; tolerance++) {
5574 if (map->stripes[preferred_mirror].dev->bdev &&
5575 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5576 return preferred_mirror;
5577 for (i = first; i < first + num_stripes; i++) {
5578 if (map->stripes[i].dev->bdev &&
5579 (tolerance || map->stripes[i].dev != srcdev))
5584 /* we couldn't find one that doesn't fail. Just return something
5585 * and the io error handling code will clean up eventually
5587 return preferred_mirror;
5590 static inline int parity_smaller(u64 a, u64 b)
5595 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5596 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5598 struct btrfs_bio_stripe s;
5605 for (i = 0; i < num_stripes - 1; i++) {
5606 if (parity_smaller(bbio->raid_map[i],
5607 bbio->raid_map[i+1])) {
5608 s = bbio->stripes[i];
5609 l = bbio->raid_map[i];
5610 bbio->stripes[i] = bbio->stripes[i+1];
5611 bbio->raid_map[i] = bbio->raid_map[i+1];
5612 bbio->stripes[i+1] = s;
5613 bbio->raid_map[i+1] = l;
5621 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5623 struct btrfs_bio *bbio = kzalloc(
5624 /* the size of the btrfs_bio */
5625 sizeof(struct btrfs_bio) +
5626 /* plus the variable array for the stripes */
5627 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5628 /* plus the variable array for the tgt dev */
5629 sizeof(int) * (real_stripes) +
5631 * plus the raid_map, which includes both the tgt dev
5634 sizeof(u64) * (total_stripes),
5635 GFP_NOFS|__GFP_NOFAIL);
5637 atomic_set(&bbio->error, 0);
5638 refcount_set(&bbio->refs, 1);
5643 void btrfs_get_bbio(struct btrfs_bio *bbio)
5645 WARN_ON(!refcount_read(&bbio->refs));
5646 refcount_inc(&bbio->refs);
5649 void btrfs_put_bbio(struct btrfs_bio *bbio)
5653 if (refcount_dec_and_test(&bbio->refs))
5657 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5659 * Please note that, discard won't be sent to target device of device
5662 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5663 u64 logical, u64 length,
5664 struct btrfs_bio **bbio_ret)
5666 struct extent_map *em;
5667 struct map_lookup *map;
5668 struct btrfs_bio *bbio;
5672 u64 stripe_end_offset;
5679 u32 sub_stripes = 0;
5680 u64 stripes_per_dev = 0;
5681 u32 remaining_stripes = 0;
5682 u32 last_stripe = 0;
5686 /* discard always return a bbio */
5689 em = btrfs_get_chunk_map(fs_info, logical, length);
5693 map = em->map_lookup;
5694 /* we don't discard raid56 yet */
5695 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5700 offset = logical - em->start;
5701 length = min_t(u64, em->len - offset, length);
5703 stripe_len = map->stripe_len;
5705 * stripe_nr counts the total number of stripes we have to stride
5706 * to get to this block
5708 stripe_nr = div64_u64(offset, stripe_len);
5710 /* stripe_offset is the offset of this block in its stripe */
5711 stripe_offset = offset - stripe_nr * stripe_len;
5713 stripe_nr_end = round_up(offset + length, map->stripe_len);
5714 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5715 stripe_cnt = stripe_nr_end - stripe_nr;
5716 stripe_end_offset = stripe_nr_end * map->stripe_len -
5719 * after this, stripe_nr is the number of stripes on this
5720 * device we have to walk to find the data, and stripe_index is
5721 * the number of our device in the stripe array
5725 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5726 BTRFS_BLOCK_GROUP_RAID10)) {
5727 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5730 sub_stripes = map->sub_stripes;
5732 factor = map->num_stripes / sub_stripes;
5733 num_stripes = min_t(u64, map->num_stripes,
5734 sub_stripes * stripe_cnt);
5735 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5736 stripe_index *= sub_stripes;
5737 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5738 &remaining_stripes);
5739 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5740 last_stripe *= sub_stripes;
5741 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5742 BTRFS_BLOCK_GROUP_DUP)) {
5743 num_stripes = map->num_stripes;
5745 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5749 bbio = alloc_btrfs_bio(num_stripes, 0);
5755 for (i = 0; i < num_stripes; i++) {
5756 bbio->stripes[i].physical =
5757 map->stripes[stripe_index].physical +
5758 stripe_offset + stripe_nr * map->stripe_len;
5759 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5761 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5762 BTRFS_BLOCK_GROUP_RAID10)) {
5763 bbio->stripes[i].length = stripes_per_dev *
5766 if (i / sub_stripes < remaining_stripes)
5767 bbio->stripes[i].length +=
5771 * Special for the first stripe and
5774 * |-------|...|-------|
5778 if (i < sub_stripes)
5779 bbio->stripes[i].length -=
5782 if (stripe_index >= last_stripe &&
5783 stripe_index <= (last_stripe +
5785 bbio->stripes[i].length -=
5788 if (i == sub_stripes - 1)
5791 bbio->stripes[i].length = length;
5795 if (stripe_index == map->num_stripes) {
5802 bbio->map_type = map->type;
5803 bbio->num_stripes = num_stripes;
5805 free_extent_map(em);
5810 * In dev-replace case, for repair case (that's the only case where the mirror
5811 * is selected explicitly when calling btrfs_map_block), blocks left of the
5812 * left cursor can also be read from the target drive.
5814 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5816 * For READ, it also needs to be supported using the same mirror number.
5818 * If the requested block is not left of the left cursor, EIO is returned. This
5819 * can happen because btrfs_num_copies() returns one more in the dev-replace
5822 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5823 u64 logical, u64 length,
5824 u64 srcdev_devid, int *mirror_num,
5827 struct btrfs_bio *bbio = NULL;
5829 int index_srcdev = 0;
5831 u64 physical_of_found = 0;
5835 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5836 logical, &length, &bbio, 0, 0);
5838 ASSERT(bbio == NULL);
5842 num_stripes = bbio->num_stripes;
5843 if (*mirror_num > num_stripes) {
5845 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5846 * that means that the requested area is not left of the left
5849 btrfs_put_bbio(bbio);
5854 * process the rest of the function using the mirror_num of the source
5855 * drive. Therefore look it up first. At the end, patch the device
5856 * pointer to the one of the target drive.
5858 for (i = 0; i < num_stripes; i++) {
5859 if (bbio->stripes[i].dev->devid != srcdev_devid)
5863 * In case of DUP, in order to keep it simple, only add the
5864 * mirror with the lowest physical address
5867 physical_of_found <= bbio->stripes[i].physical)
5872 physical_of_found = bbio->stripes[i].physical;
5875 btrfs_put_bbio(bbio);
5881 *mirror_num = index_srcdev + 1;
5882 *physical = physical_of_found;
5886 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5887 struct btrfs_bio **bbio_ret,
5888 struct btrfs_dev_replace *dev_replace,
5889 int *num_stripes_ret, int *max_errors_ret)
5891 struct btrfs_bio *bbio = *bbio_ret;
5892 u64 srcdev_devid = dev_replace->srcdev->devid;
5893 int tgtdev_indexes = 0;
5894 int num_stripes = *num_stripes_ret;
5895 int max_errors = *max_errors_ret;
5898 if (op == BTRFS_MAP_WRITE) {
5899 int index_where_to_add;
5902 * duplicate the write operations while the dev replace
5903 * procedure is running. Since the copying of the old disk to
5904 * the new disk takes place at run time while the filesystem is
5905 * mounted writable, the regular write operations to the old
5906 * disk have to be duplicated to go to the new disk as well.
5908 * Note that device->missing is handled by the caller, and that
5909 * the write to the old disk is already set up in the stripes
5912 index_where_to_add = num_stripes;
5913 for (i = 0; i < num_stripes; i++) {
5914 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5915 /* write to new disk, too */
5916 struct btrfs_bio_stripe *new =
5917 bbio->stripes + index_where_to_add;
5918 struct btrfs_bio_stripe *old =
5921 new->physical = old->physical;
5922 new->length = old->length;
5923 new->dev = dev_replace->tgtdev;
5924 bbio->tgtdev_map[i] = index_where_to_add;
5925 index_where_to_add++;
5930 num_stripes = index_where_to_add;
5931 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5932 int index_srcdev = 0;
5934 u64 physical_of_found = 0;
5937 * During the dev-replace procedure, the target drive can also
5938 * be used to read data in case it is needed to repair a corrupt
5939 * block elsewhere. This is possible if the requested area is
5940 * left of the left cursor. In this area, the target drive is a
5941 * full copy of the source drive.
5943 for (i = 0; i < num_stripes; i++) {
5944 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5946 * In case of DUP, in order to keep it simple,
5947 * only add the mirror with the lowest physical
5951 physical_of_found <=
5952 bbio->stripes[i].physical)
5956 physical_of_found = bbio->stripes[i].physical;
5960 struct btrfs_bio_stripe *tgtdev_stripe =
5961 bbio->stripes + num_stripes;
5963 tgtdev_stripe->physical = physical_of_found;
5964 tgtdev_stripe->length =
5965 bbio->stripes[index_srcdev].length;
5966 tgtdev_stripe->dev = dev_replace->tgtdev;
5967 bbio->tgtdev_map[index_srcdev] = num_stripes;
5974 *num_stripes_ret = num_stripes;
5975 *max_errors_ret = max_errors;
5976 bbio->num_tgtdevs = tgtdev_indexes;
5980 static bool need_full_stripe(enum btrfs_map_op op)
5982 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5985 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5986 enum btrfs_map_op op,
5987 u64 logical, u64 *length,
5988 struct btrfs_bio **bbio_ret,
5989 int mirror_num, int need_raid_map)
5991 struct extent_map *em;
5992 struct map_lookup *map;
6002 int tgtdev_indexes = 0;
6003 struct btrfs_bio *bbio = NULL;
6004 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6005 int dev_replace_is_ongoing = 0;
6006 int num_alloc_stripes;
6007 int patch_the_first_stripe_for_dev_replace = 0;
6008 u64 physical_to_patch_in_first_stripe = 0;
6009 u64 raid56_full_stripe_start = (u64)-1;
6011 if (op == BTRFS_MAP_DISCARD)
6012 return __btrfs_map_block_for_discard(fs_info, logical,
6015 em = btrfs_get_chunk_map(fs_info, logical, *length);
6019 map = em->map_lookup;
6020 offset = logical - em->start;
6022 stripe_len = map->stripe_len;
6025 * stripe_nr counts the total number of stripes we have to stride
6026 * to get to this block
6028 stripe_nr = div64_u64(stripe_nr, stripe_len);
6030 stripe_offset = stripe_nr * stripe_len;
6031 if (offset < stripe_offset) {
6033 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
6034 stripe_offset, offset, em->start, logical,
6036 free_extent_map(em);
6040 /* stripe_offset is the offset of this block in its stripe*/
6041 stripe_offset = offset - stripe_offset;
6043 /* if we're here for raid56, we need to know the stripe aligned start */
6044 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6045 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
6046 raid56_full_stripe_start = offset;
6048 /* allow a write of a full stripe, but make sure we don't
6049 * allow straddling of stripes
6051 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6053 raid56_full_stripe_start *= full_stripe_len;
6056 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6058 /* For writes to RAID[56], allow a full stripeset across all disks.
6059 For other RAID types and for RAID[56] reads, just allow a single
6060 stripe (on a single disk). */
6061 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6062 (op == BTRFS_MAP_WRITE)) {
6063 max_len = stripe_len * nr_data_stripes(map) -
6064 (offset - raid56_full_stripe_start);
6066 /* we limit the length of each bio to what fits in a stripe */
6067 max_len = stripe_len - stripe_offset;
6069 *length = min_t(u64, em->len - offset, max_len);
6071 *length = em->len - offset;
6075 * This is for when we're called from btrfs_bio_fits_in_stripe and all
6076 * it cares about is the length
6081 down_read(&dev_replace->rwsem);
6082 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6084 * Hold the semaphore for read during the whole operation, write is
6085 * requested at commit time but must wait.
6087 if (!dev_replace_is_ongoing)
6088 up_read(&dev_replace->rwsem);
6090 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6091 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6092 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6093 dev_replace->srcdev->devid,
6095 &physical_to_patch_in_first_stripe);
6099 patch_the_first_stripe_for_dev_replace = 1;
6100 } else if (mirror_num > map->num_stripes) {
6106 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6107 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6109 if (!need_full_stripe(op))
6111 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
6112 if (need_full_stripe(op))
6113 num_stripes = map->num_stripes;
6114 else if (mirror_num)
6115 stripe_index = mirror_num - 1;
6117 stripe_index = find_live_mirror(fs_info, map, 0,
6118 dev_replace_is_ongoing);
6119 mirror_num = stripe_index + 1;
6122 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6123 if (need_full_stripe(op)) {
6124 num_stripes = map->num_stripes;
6125 } else if (mirror_num) {
6126 stripe_index = mirror_num - 1;
6131 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6132 u32 factor = map->num_stripes / map->sub_stripes;
6134 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6135 stripe_index *= map->sub_stripes;
6137 if (need_full_stripe(op))
6138 num_stripes = map->sub_stripes;
6139 else if (mirror_num)
6140 stripe_index += mirror_num - 1;
6142 int old_stripe_index = stripe_index;
6143 stripe_index = find_live_mirror(fs_info, map,
6145 dev_replace_is_ongoing);
6146 mirror_num = stripe_index - old_stripe_index + 1;
6149 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6150 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6151 /* push stripe_nr back to the start of the full stripe */
6152 stripe_nr = div64_u64(raid56_full_stripe_start,
6153 stripe_len * nr_data_stripes(map));
6155 /* RAID[56] write or recovery. Return all stripes */
6156 num_stripes = map->num_stripes;
6157 max_errors = nr_parity_stripes(map);
6159 *length = map->stripe_len;
6164 * Mirror #0 or #1 means the original data block.
6165 * Mirror #2 is RAID5 parity block.
6166 * Mirror #3 is RAID6 Q block.
6168 stripe_nr = div_u64_rem(stripe_nr,
6169 nr_data_stripes(map), &stripe_index);
6171 stripe_index = nr_data_stripes(map) +
6174 /* We distribute the parity blocks across stripes */
6175 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6177 if (!need_full_stripe(op) && mirror_num <= 1)
6182 * after this, stripe_nr is the number of stripes on this
6183 * device we have to walk to find the data, and stripe_index is
6184 * the number of our device in the stripe array
6186 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6188 mirror_num = stripe_index + 1;
6190 if (stripe_index >= map->num_stripes) {
6192 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6193 stripe_index, map->num_stripes);
6198 num_alloc_stripes = num_stripes;
6199 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6200 if (op == BTRFS_MAP_WRITE)
6201 num_alloc_stripes <<= 1;
6202 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6203 num_alloc_stripes++;
6204 tgtdev_indexes = num_stripes;
6207 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6212 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
6213 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
6215 /* build raid_map */
6216 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6217 (need_full_stripe(op) || mirror_num > 1)) {
6221 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6222 sizeof(struct btrfs_bio_stripe) *
6224 sizeof(int) * tgtdev_indexes);
6226 /* Work out the disk rotation on this stripe-set */
6227 div_u64_rem(stripe_nr, num_stripes, &rot);
6229 /* Fill in the logical address of each stripe */
6230 tmp = stripe_nr * nr_data_stripes(map);
6231 for (i = 0; i < nr_data_stripes(map); i++)
6232 bbio->raid_map[(i+rot) % num_stripes] =
6233 em->start + (tmp + i) * map->stripe_len;
6235 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6236 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6237 bbio->raid_map[(i+rot+1) % num_stripes] =
6242 for (i = 0; i < num_stripes; i++) {
6243 bbio->stripes[i].physical =
6244 map->stripes[stripe_index].physical +
6246 stripe_nr * map->stripe_len;
6247 bbio->stripes[i].dev =
6248 map->stripes[stripe_index].dev;
6252 if (need_full_stripe(op))
6253 max_errors = btrfs_chunk_max_errors(map);
6256 sort_parity_stripes(bbio, num_stripes);
6258 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6259 need_full_stripe(op)) {
6260 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6265 bbio->map_type = map->type;
6266 bbio->num_stripes = num_stripes;
6267 bbio->max_errors = max_errors;
6268 bbio->mirror_num = mirror_num;
6271 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6272 * mirror_num == num_stripes + 1 && dev_replace target drive is
6273 * available as a mirror
6275 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6276 WARN_ON(num_stripes > 1);
6277 bbio->stripes[0].dev = dev_replace->tgtdev;
6278 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6279 bbio->mirror_num = map->num_stripes + 1;
6282 if (dev_replace_is_ongoing) {
6283 lockdep_assert_held(&dev_replace->rwsem);
6284 /* Unlock and let waiting writers proceed */
6285 up_read(&dev_replace->rwsem);
6287 free_extent_map(em);
6291 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6292 u64 logical, u64 *length,
6293 struct btrfs_bio **bbio_ret, int mirror_num)
6295 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6299 /* For Scrub/replace */
6300 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6301 u64 logical, u64 *length,
6302 struct btrfs_bio **bbio_ret)
6304 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6307 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
6308 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
6310 struct extent_map *em;
6311 struct map_lookup *map;
6319 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
6323 map = em->map_lookup;
6325 rmap_len = map->stripe_len;
6327 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6328 length = div_u64(length, map->num_stripes / map->sub_stripes);
6329 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6330 length = div_u64(length, map->num_stripes);
6331 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6332 length = div_u64(length, nr_data_stripes(map));
6333 rmap_len = map->stripe_len * nr_data_stripes(map);
6336 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6337 BUG_ON(!buf); /* -ENOMEM */
6339 for (i = 0; i < map->num_stripes; i++) {
6340 if (map->stripes[i].physical > physical ||
6341 map->stripes[i].physical + length <= physical)
6344 stripe_nr = physical - map->stripes[i].physical;
6345 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6347 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6348 stripe_nr = stripe_nr * map->num_stripes + i;
6349 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6350 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6351 stripe_nr = stripe_nr * map->num_stripes + i;
6352 } /* else if RAID[56], multiply by nr_data_stripes().
6353 * Alternatively, just use rmap_len below instead of
6354 * map->stripe_len */
6356 bytenr = chunk_start + stripe_nr * rmap_len;
6357 WARN_ON(nr >= map->num_stripes);
6358 for (j = 0; j < nr; j++) {
6359 if (buf[j] == bytenr)
6363 WARN_ON(nr >= map->num_stripes);
6370 *stripe_len = rmap_len;
6372 free_extent_map(em);
6376 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6378 bio->bi_private = bbio->private;
6379 bio->bi_end_io = bbio->end_io;
6382 btrfs_put_bbio(bbio);
6385 static void btrfs_end_bio(struct bio *bio)
6387 struct btrfs_bio *bbio = bio->bi_private;
6388 int is_orig_bio = 0;
6390 if (bio->bi_status) {
6391 atomic_inc(&bbio->error);
6392 if (bio->bi_status == BLK_STS_IOERR ||
6393 bio->bi_status == BLK_STS_TARGET) {
6394 unsigned int stripe_index =
6395 btrfs_io_bio(bio)->stripe_index;
6396 struct btrfs_device *dev;
6398 BUG_ON(stripe_index >= bbio->num_stripes);
6399 dev = bbio->stripes[stripe_index].dev;
6401 if (bio_op(bio) == REQ_OP_WRITE)
6402 btrfs_dev_stat_inc_and_print(dev,
6403 BTRFS_DEV_STAT_WRITE_ERRS);
6404 else if (!(bio->bi_opf & REQ_RAHEAD))
6405 btrfs_dev_stat_inc_and_print(dev,
6406 BTRFS_DEV_STAT_READ_ERRS);
6407 if (bio->bi_opf & REQ_PREFLUSH)
6408 btrfs_dev_stat_inc_and_print(dev,
6409 BTRFS_DEV_STAT_FLUSH_ERRS);
6414 if (bio == bbio->orig_bio)
6417 btrfs_bio_counter_dec(bbio->fs_info);
6419 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6422 bio = bbio->orig_bio;
6425 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6426 /* only send an error to the higher layers if it is
6427 * beyond the tolerance of the btrfs bio
6429 if (atomic_read(&bbio->error) > bbio->max_errors) {
6430 bio->bi_status = BLK_STS_IOERR;
6433 * this bio is actually up to date, we didn't
6434 * go over the max number of errors
6436 bio->bi_status = BLK_STS_OK;
6439 btrfs_end_bbio(bbio, bio);
6440 } else if (!is_orig_bio) {
6446 * see run_scheduled_bios for a description of why bios are collected for
6449 * This will add one bio to the pending list for a device and make sure
6450 * the work struct is scheduled.
6452 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6455 struct btrfs_fs_info *fs_info = device->fs_info;
6456 int should_queue = 1;
6457 struct btrfs_pending_bios *pending_bios;
6459 /* don't bother with additional async steps for reads, right now */
6460 if (bio_op(bio) == REQ_OP_READ) {
6461 btrfsic_submit_bio(bio);
6465 WARN_ON(bio->bi_next);
6466 bio->bi_next = NULL;
6468 spin_lock(&device->io_lock);
6469 if (op_is_sync(bio->bi_opf))
6470 pending_bios = &device->pending_sync_bios;
6472 pending_bios = &device->pending_bios;
6474 if (pending_bios->tail)
6475 pending_bios->tail->bi_next = bio;
6477 pending_bios->tail = bio;
6478 if (!pending_bios->head)
6479 pending_bios->head = bio;
6480 if (device->running_pending)
6483 spin_unlock(&device->io_lock);
6486 btrfs_queue_work(fs_info->submit_workers, &device->work);
6489 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6490 u64 physical, int dev_nr, int async)
6492 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6493 struct btrfs_fs_info *fs_info = bbio->fs_info;
6495 bio->bi_private = bbio;
6496 btrfs_io_bio(bio)->stripe_index = dev_nr;
6497 bio->bi_end_io = btrfs_end_bio;
6498 bio->bi_iter.bi_sector = physical >> 9;
6499 btrfs_debug_in_rcu(fs_info,
6500 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6501 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6502 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6503 bio->bi_iter.bi_size);
6504 bio_set_dev(bio, dev->bdev);
6506 btrfs_bio_counter_inc_noblocked(fs_info);
6509 btrfs_schedule_bio(dev, bio);
6511 btrfsic_submit_bio(bio);
6514 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6516 atomic_inc(&bbio->error);
6517 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6518 /* Should be the original bio. */
6519 WARN_ON(bio != bbio->orig_bio);
6521 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6522 bio->bi_iter.bi_sector = logical >> 9;
6523 if (atomic_read(&bbio->error) > bbio->max_errors)
6524 bio->bi_status = BLK_STS_IOERR;
6526 bio->bi_status = BLK_STS_OK;
6527 btrfs_end_bbio(bbio, bio);
6531 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6532 int mirror_num, int async_submit)
6534 struct btrfs_device *dev;
6535 struct bio *first_bio = bio;
6536 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6542 struct btrfs_bio *bbio = NULL;
6544 length = bio->bi_iter.bi_size;
6545 map_length = length;
6547 btrfs_bio_counter_inc_blocked(fs_info);
6548 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6549 &map_length, &bbio, mirror_num, 1);
6551 btrfs_bio_counter_dec(fs_info);
6552 return errno_to_blk_status(ret);
6555 total_devs = bbio->num_stripes;
6556 bbio->orig_bio = first_bio;
6557 bbio->private = first_bio->bi_private;
6558 bbio->end_io = first_bio->bi_end_io;
6559 bbio->fs_info = fs_info;
6560 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6562 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6563 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6564 /* In this case, map_length has been set to the length of
6565 a single stripe; not the whole write */
6566 if (bio_op(bio) == REQ_OP_WRITE) {
6567 ret = raid56_parity_write(fs_info, bio, bbio,
6570 ret = raid56_parity_recover(fs_info, bio, bbio,
6571 map_length, mirror_num, 1);
6574 btrfs_bio_counter_dec(fs_info);
6575 return errno_to_blk_status(ret);
6578 if (map_length < length) {
6580 "mapping failed logical %llu bio len %llu len %llu",
6581 logical, length, map_length);
6585 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6586 dev = bbio->stripes[dev_nr].dev;
6587 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6589 (bio_op(first_bio) == REQ_OP_WRITE &&
6590 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6591 bbio_error(bbio, first_bio, logical);
6595 if (dev_nr < total_devs - 1)
6596 bio = btrfs_bio_clone(first_bio);
6600 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6601 dev_nr, async_submit);
6603 btrfs_bio_counter_dec(fs_info);
6608 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6611 * If devid and uuid are both specified, the match must be exact, otherwise
6612 * only devid is used.
6614 * If @seed is true, traverse through the seed devices.
6616 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6617 u64 devid, u8 *uuid, u8 *fsid,
6620 struct btrfs_device *device;
6622 while (fs_devices) {
6624 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6625 list_for_each_entry(device, &fs_devices->devices,
6627 if (device->devid == devid &&
6628 (!uuid || memcmp(device->uuid, uuid,
6629 BTRFS_UUID_SIZE) == 0))
6634 fs_devices = fs_devices->seed;
6641 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6642 u64 devid, u8 *dev_uuid)
6644 struct btrfs_device *device;
6646 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6650 list_add(&device->dev_list, &fs_devices->devices);
6651 device->fs_devices = fs_devices;
6652 fs_devices->num_devices++;
6654 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6655 fs_devices->missing_devices++;
6661 * btrfs_alloc_device - allocate struct btrfs_device
6662 * @fs_info: used only for generating a new devid, can be NULL if
6663 * devid is provided (i.e. @devid != NULL).
6664 * @devid: a pointer to devid for this device. If NULL a new devid
6666 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6669 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6670 * on error. Returned struct is not linked onto any lists and must be
6671 * destroyed with btrfs_free_device.
6673 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6677 struct btrfs_device *dev;
6680 if (WARN_ON(!devid && !fs_info))
6681 return ERR_PTR(-EINVAL);
6683 dev = __alloc_device();
6692 ret = find_next_devid(fs_info, &tmp);
6694 btrfs_free_device(dev);
6695 return ERR_PTR(ret);
6701 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6703 generate_random_uuid(dev->uuid);
6705 btrfs_init_work(&dev->work, btrfs_submit_helper,
6706 pending_bios_fn, NULL, NULL);
6711 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6712 u64 devid, u8 *uuid, bool error)
6715 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6718 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6722 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6723 struct extent_buffer *leaf,
6724 struct btrfs_chunk *chunk)
6726 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6727 struct map_lookup *map;
6728 struct extent_map *em;
6732 u8 uuid[BTRFS_UUID_SIZE];
6737 logical = key->offset;
6738 length = btrfs_chunk_length(leaf, chunk);
6739 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6742 * Only need to verify chunk item if we're reading from sys chunk array,
6743 * as chunk item in tree block is already verified by tree-checker.
6745 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6746 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6751 read_lock(&map_tree->map_tree.lock);
6752 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6753 read_unlock(&map_tree->map_tree.lock);
6755 /* already mapped? */
6756 if (em && em->start <= logical && em->start + em->len > logical) {
6757 free_extent_map(em);
6760 free_extent_map(em);
6763 em = alloc_extent_map();
6766 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6768 free_extent_map(em);
6772 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6773 em->map_lookup = map;
6774 em->start = logical;
6777 em->block_start = 0;
6778 em->block_len = em->len;
6780 map->num_stripes = num_stripes;
6781 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6782 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6783 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6784 map->type = btrfs_chunk_type(leaf, chunk);
6785 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6786 map->verified_stripes = 0;
6787 for (i = 0; i < num_stripes; i++) {
6788 map->stripes[i].physical =
6789 btrfs_stripe_offset_nr(leaf, chunk, i);
6790 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6791 read_extent_buffer(leaf, uuid, (unsigned long)
6792 btrfs_stripe_dev_uuid_nr(chunk, i),
6794 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6795 devid, uuid, NULL, true);
6796 if (!map->stripes[i].dev &&
6797 !btrfs_test_opt(fs_info, DEGRADED)) {
6798 free_extent_map(em);
6799 btrfs_report_missing_device(fs_info, devid, uuid, true);
6802 if (!map->stripes[i].dev) {
6803 map->stripes[i].dev =
6804 add_missing_dev(fs_info->fs_devices, devid,
6806 if (IS_ERR(map->stripes[i].dev)) {
6807 free_extent_map(em);
6809 "failed to init missing dev %llu: %ld",
6810 devid, PTR_ERR(map->stripes[i].dev));
6811 return PTR_ERR(map->stripes[i].dev);
6813 btrfs_report_missing_device(fs_info, devid, uuid, false);
6815 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6816 &(map->stripes[i].dev->dev_state));
6820 write_lock(&map_tree->map_tree.lock);
6821 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6822 write_unlock(&map_tree->map_tree.lock);
6825 "failed to add chunk map, start=%llu len=%llu: %d",
6826 em->start, em->len, ret);
6828 free_extent_map(em);
6833 static void fill_device_from_item(struct extent_buffer *leaf,
6834 struct btrfs_dev_item *dev_item,
6835 struct btrfs_device *device)
6839 device->devid = btrfs_device_id(leaf, dev_item);
6840 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6841 device->total_bytes = device->disk_total_bytes;
6842 device->commit_total_bytes = device->disk_total_bytes;
6843 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6844 device->commit_bytes_used = device->bytes_used;
6845 device->type = btrfs_device_type(leaf, dev_item);
6846 device->io_align = btrfs_device_io_align(leaf, dev_item);
6847 device->io_width = btrfs_device_io_width(leaf, dev_item);
6848 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6849 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6850 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6852 ptr = btrfs_device_uuid(dev_item);
6853 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6856 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6859 struct btrfs_fs_devices *fs_devices;
6862 lockdep_assert_held(&uuid_mutex);
6865 fs_devices = fs_info->fs_devices->seed;
6866 while (fs_devices) {
6867 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6870 fs_devices = fs_devices->seed;
6873 fs_devices = find_fsid(fsid, NULL);
6875 if (!btrfs_test_opt(fs_info, DEGRADED))
6876 return ERR_PTR(-ENOENT);
6878 fs_devices = alloc_fs_devices(fsid, NULL);
6879 if (IS_ERR(fs_devices))
6882 fs_devices->seeding = 1;
6883 fs_devices->opened = 1;
6887 fs_devices = clone_fs_devices(fs_devices);
6888 if (IS_ERR(fs_devices))
6891 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6893 free_fs_devices(fs_devices);
6894 fs_devices = ERR_PTR(ret);
6898 if (!fs_devices->seeding) {
6899 close_fs_devices(fs_devices);
6900 free_fs_devices(fs_devices);
6901 fs_devices = ERR_PTR(-EINVAL);
6905 fs_devices->seed = fs_info->fs_devices->seed;
6906 fs_info->fs_devices->seed = fs_devices;
6911 static int read_one_dev(struct btrfs_fs_info *fs_info,
6912 struct extent_buffer *leaf,
6913 struct btrfs_dev_item *dev_item)
6915 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6916 struct btrfs_device *device;
6919 u8 fs_uuid[BTRFS_FSID_SIZE];
6920 u8 dev_uuid[BTRFS_UUID_SIZE];
6922 devid = btrfs_device_id(leaf, dev_item);
6923 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6925 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6928 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6929 fs_devices = open_seed_devices(fs_info, fs_uuid);
6930 if (IS_ERR(fs_devices))
6931 return PTR_ERR(fs_devices);
6934 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6937 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6938 btrfs_report_missing_device(fs_info, devid,
6943 device = add_missing_dev(fs_devices, devid, dev_uuid);
6944 if (IS_ERR(device)) {
6946 "failed to add missing dev %llu: %ld",
6947 devid, PTR_ERR(device));
6948 return PTR_ERR(device);
6950 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6952 if (!device->bdev) {
6953 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6954 btrfs_report_missing_device(fs_info,
6955 devid, dev_uuid, true);
6958 btrfs_report_missing_device(fs_info, devid,
6962 if (!device->bdev &&
6963 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6965 * this happens when a device that was properly setup
6966 * in the device info lists suddenly goes bad.
6967 * device->bdev is NULL, and so we have to set
6968 * device->missing to one here
6970 device->fs_devices->missing_devices++;
6971 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6974 /* Move the device to its own fs_devices */
6975 if (device->fs_devices != fs_devices) {
6976 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6977 &device->dev_state));
6979 list_move(&device->dev_list, &fs_devices->devices);
6980 device->fs_devices->num_devices--;
6981 fs_devices->num_devices++;
6983 device->fs_devices->missing_devices--;
6984 fs_devices->missing_devices++;
6986 device->fs_devices = fs_devices;
6990 if (device->fs_devices != fs_info->fs_devices) {
6991 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6992 if (device->generation !=
6993 btrfs_device_generation(leaf, dev_item))
6997 fill_device_from_item(leaf, dev_item, device);
6998 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6999 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7000 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7001 device->fs_devices->total_rw_bytes += device->total_bytes;
7002 atomic64_add(device->total_bytes - device->bytes_used,
7003 &fs_info->free_chunk_space);
7009 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7011 struct btrfs_root *root = fs_info->tree_root;
7012 struct btrfs_super_block *super_copy = fs_info->super_copy;
7013 struct extent_buffer *sb;
7014 struct btrfs_disk_key *disk_key;
7015 struct btrfs_chunk *chunk;
7017 unsigned long sb_array_offset;
7024 struct btrfs_key key;
7026 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7028 * This will create extent buffer of nodesize, superblock size is
7029 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7030 * overallocate but we can keep it as-is, only the first page is used.
7032 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
7035 set_extent_buffer_uptodate(sb);
7036 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
7038 * The sb extent buffer is artificial and just used to read the system array.
7039 * set_extent_buffer_uptodate() call does not properly mark all it's
7040 * pages up-to-date when the page is larger: extent does not cover the
7041 * whole page and consequently check_page_uptodate does not find all
7042 * the page's extents up-to-date (the hole beyond sb),
7043 * write_extent_buffer then triggers a WARN_ON.
7045 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7046 * but sb spans only this function. Add an explicit SetPageUptodate call
7047 * to silence the warning eg. on PowerPC 64.
7049 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
7050 SetPageUptodate(sb->pages[0]);
7052 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7053 array_size = btrfs_super_sys_array_size(super_copy);
7055 array_ptr = super_copy->sys_chunk_array;
7056 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7059 while (cur_offset < array_size) {
7060 disk_key = (struct btrfs_disk_key *)array_ptr;
7061 len = sizeof(*disk_key);
7062 if (cur_offset + len > array_size)
7063 goto out_short_read;
7065 btrfs_disk_key_to_cpu(&key, disk_key);
7068 sb_array_offset += len;
7071 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
7072 chunk = (struct btrfs_chunk *)sb_array_offset;
7074 * At least one btrfs_chunk with one stripe must be
7075 * present, exact stripe count check comes afterwards
7077 len = btrfs_chunk_item_size(1);
7078 if (cur_offset + len > array_size)
7079 goto out_short_read;
7081 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7084 "invalid number of stripes %u in sys_array at offset %u",
7085 num_stripes, cur_offset);
7090 type = btrfs_chunk_type(sb, chunk);
7091 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7093 "invalid chunk type %llu in sys_array at offset %u",
7099 len = btrfs_chunk_item_size(num_stripes);
7100 if (cur_offset + len > array_size)
7101 goto out_short_read;
7103 ret = read_one_chunk(fs_info, &key, sb, chunk);
7108 "unexpected item type %u in sys_array at offset %u",
7109 (u32)key.type, cur_offset);
7114 sb_array_offset += len;
7117 clear_extent_buffer_uptodate(sb);
7118 free_extent_buffer_stale(sb);
7122 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7124 clear_extent_buffer_uptodate(sb);
7125 free_extent_buffer_stale(sb);
7130 * Check if all chunks in the fs are OK for read-write degraded mount
7132 * If the @failing_dev is specified, it's accounted as missing.
7134 * Return true if all chunks meet the minimal RW mount requirements.
7135 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7137 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7138 struct btrfs_device *failing_dev)
7140 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
7141 struct extent_map *em;
7145 read_lock(&map_tree->map_tree.lock);
7146 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
7147 read_unlock(&map_tree->map_tree.lock);
7148 /* No chunk at all? Return false anyway */
7154 struct map_lookup *map;
7159 map = em->map_lookup;
7161 btrfs_get_num_tolerated_disk_barrier_failures(
7163 for (i = 0; i < map->num_stripes; i++) {
7164 struct btrfs_device *dev = map->stripes[i].dev;
7166 if (!dev || !dev->bdev ||
7167 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7168 dev->last_flush_error)
7170 else if (failing_dev && failing_dev == dev)
7173 if (missing > max_tolerated) {
7176 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7177 em->start, missing, max_tolerated);
7178 free_extent_map(em);
7182 next_start = extent_map_end(em);
7183 free_extent_map(em);
7185 read_lock(&map_tree->map_tree.lock);
7186 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
7187 (u64)(-1) - next_start);
7188 read_unlock(&map_tree->map_tree.lock);
7194 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7196 struct btrfs_root *root = fs_info->chunk_root;
7197 struct btrfs_path *path;
7198 struct extent_buffer *leaf;
7199 struct btrfs_key key;
7200 struct btrfs_key found_key;
7205 path = btrfs_alloc_path();
7210 * uuid_mutex is needed only if we are mounting a sprout FS
7211 * otherwise we don't need it.
7213 mutex_lock(&uuid_mutex);
7214 mutex_lock(&fs_info->chunk_mutex);
7217 * Read all device items, and then all the chunk items. All
7218 * device items are found before any chunk item (their object id
7219 * is smaller than the lowest possible object id for a chunk
7220 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7222 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7225 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7229 leaf = path->nodes[0];
7230 slot = path->slots[0];
7231 if (slot >= btrfs_header_nritems(leaf)) {
7232 ret = btrfs_next_leaf(root, path);
7239 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7240 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7241 struct btrfs_dev_item *dev_item;
7242 dev_item = btrfs_item_ptr(leaf, slot,
7243 struct btrfs_dev_item);
7244 ret = read_one_dev(fs_info, leaf, dev_item);
7248 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7249 struct btrfs_chunk *chunk;
7250 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7251 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
7259 * After loading chunk tree, we've got all device information,
7260 * do another round of validation checks.
7262 if (total_dev != fs_info->fs_devices->total_devices) {
7264 "super_num_devices %llu mismatch with num_devices %llu found here",
7265 btrfs_super_num_devices(fs_info->super_copy),
7270 if (btrfs_super_total_bytes(fs_info->super_copy) <
7271 fs_info->fs_devices->total_rw_bytes) {
7273 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7274 btrfs_super_total_bytes(fs_info->super_copy),
7275 fs_info->fs_devices->total_rw_bytes);
7281 mutex_unlock(&fs_info->chunk_mutex);
7282 mutex_unlock(&uuid_mutex);
7284 btrfs_free_path(path);
7288 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7290 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7291 struct btrfs_device *device;
7293 while (fs_devices) {
7294 mutex_lock(&fs_devices->device_list_mutex);
7295 list_for_each_entry(device, &fs_devices->devices, dev_list)
7296 device->fs_info = fs_info;
7297 mutex_unlock(&fs_devices->device_list_mutex);
7299 fs_devices = fs_devices->seed;
7303 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7307 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7308 btrfs_dev_stat_reset(dev, i);
7311 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7313 struct btrfs_key key;
7314 struct btrfs_key found_key;
7315 struct btrfs_root *dev_root = fs_info->dev_root;
7316 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7317 struct extent_buffer *eb;
7320 struct btrfs_device *device;
7321 struct btrfs_path *path = NULL;
7324 path = btrfs_alloc_path();
7330 mutex_lock(&fs_devices->device_list_mutex);
7331 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7333 struct btrfs_dev_stats_item *ptr;
7335 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7336 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7337 key.offset = device->devid;
7338 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7340 __btrfs_reset_dev_stats(device);
7341 device->dev_stats_valid = 1;
7342 btrfs_release_path(path);
7345 slot = path->slots[0];
7346 eb = path->nodes[0];
7347 btrfs_item_key_to_cpu(eb, &found_key, slot);
7348 item_size = btrfs_item_size_nr(eb, slot);
7350 ptr = btrfs_item_ptr(eb, slot,
7351 struct btrfs_dev_stats_item);
7353 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7354 if (item_size >= (1 + i) * sizeof(__le64))
7355 btrfs_dev_stat_set(device, i,
7356 btrfs_dev_stats_value(eb, ptr, i));
7358 btrfs_dev_stat_reset(device, i);
7361 device->dev_stats_valid = 1;
7362 btrfs_dev_stat_print_on_load(device);
7363 btrfs_release_path(path);
7365 mutex_unlock(&fs_devices->device_list_mutex);
7368 btrfs_free_path(path);
7369 return ret < 0 ? ret : 0;
7372 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7373 struct btrfs_device *device)
7375 struct btrfs_fs_info *fs_info = trans->fs_info;
7376 struct btrfs_root *dev_root = fs_info->dev_root;
7377 struct btrfs_path *path;
7378 struct btrfs_key key;
7379 struct extent_buffer *eb;
7380 struct btrfs_dev_stats_item *ptr;
7384 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7385 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7386 key.offset = device->devid;
7388 path = btrfs_alloc_path();
7391 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7393 btrfs_warn_in_rcu(fs_info,
7394 "error %d while searching for dev_stats item for device %s",
7395 ret, rcu_str_deref(device->name));
7400 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7401 /* need to delete old one and insert a new one */
7402 ret = btrfs_del_item(trans, dev_root, path);
7404 btrfs_warn_in_rcu(fs_info,
7405 "delete too small dev_stats item for device %s failed %d",
7406 rcu_str_deref(device->name), ret);
7413 /* need to insert a new item */
7414 btrfs_release_path(path);
7415 ret = btrfs_insert_empty_item(trans, dev_root, path,
7416 &key, sizeof(*ptr));
7418 btrfs_warn_in_rcu(fs_info,
7419 "insert dev_stats item for device %s failed %d",
7420 rcu_str_deref(device->name), ret);
7425 eb = path->nodes[0];
7426 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7427 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7428 btrfs_set_dev_stats_value(eb, ptr, i,
7429 btrfs_dev_stat_read(device, i));
7430 btrfs_mark_buffer_dirty(eb);
7433 btrfs_free_path(path);
7438 * called from commit_transaction. Writes all changed device stats to disk.
7440 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7441 struct btrfs_fs_info *fs_info)
7443 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7444 struct btrfs_device *device;
7448 mutex_lock(&fs_devices->device_list_mutex);
7449 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7450 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7451 if (!device->dev_stats_valid || stats_cnt == 0)
7456 * There is a LOAD-LOAD control dependency between the value of
7457 * dev_stats_ccnt and updating the on-disk values which requires
7458 * reading the in-memory counters. Such control dependencies
7459 * require explicit read memory barriers.
7461 * This memory barriers pairs with smp_mb__before_atomic in
7462 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7463 * barrier implied by atomic_xchg in
7464 * btrfs_dev_stats_read_and_reset
7468 ret = update_dev_stat_item(trans, device);
7470 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7472 mutex_unlock(&fs_devices->device_list_mutex);
7477 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7479 btrfs_dev_stat_inc(dev, index);
7480 btrfs_dev_stat_print_on_error(dev);
7483 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7485 if (!dev->dev_stats_valid)
7487 btrfs_err_rl_in_rcu(dev->fs_info,
7488 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7489 rcu_str_deref(dev->name),
7490 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7491 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7492 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7493 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7494 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7497 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7501 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7502 if (btrfs_dev_stat_read(dev, i) != 0)
7504 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7505 return; /* all values == 0, suppress message */
7507 btrfs_info_in_rcu(dev->fs_info,
7508 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7509 rcu_str_deref(dev->name),
7510 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7511 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7512 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7513 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7514 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7517 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7518 struct btrfs_ioctl_get_dev_stats *stats)
7520 struct btrfs_device *dev;
7521 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7524 mutex_lock(&fs_devices->device_list_mutex);
7525 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7527 mutex_unlock(&fs_devices->device_list_mutex);
7530 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7532 } else if (!dev->dev_stats_valid) {
7533 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7535 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7536 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7537 if (stats->nr_items > i)
7539 btrfs_dev_stat_read_and_reset(dev, i);
7541 btrfs_dev_stat_reset(dev, i);
7544 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7545 if (stats->nr_items > i)
7546 stats->values[i] = btrfs_dev_stat_read(dev, i);
7548 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7549 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7553 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7555 struct buffer_head *bh;
7556 struct btrfs_super_block *disk_super;
7562 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7565 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7568 disk_super = (struct btrfs_super_block *)bh->b_data;
7570 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7571 set_buffer_dirty(bh);
7572 sync_dirty_buffer(bh);
7576 /* Notify udev that device has changed */
7577 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7579 /* Update ctime/mtime for device path for libblkid */
7580 update_dev_time(device_path);
7584 * Update the size and bytes used for each device where it changed. This is
7585 * delayed since we would otherwise get errors while writing out the
7588 * Must be invoked during transaction commit.
7590 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7592 struct btrfs_device *curr, *next;
7594 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7596 if (list_empty(&trans->dev_update_list))
7600 * We don't need the device_list_mutex here. This list is owned by the
7601 * transaction and the transaction must complete before the device is
7604 mutex_lock(&trans->fs_info->chunk_mutex);
7605 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7607 list_del_init(&curr->post_commit_list);
7608 curr->commit_total_bytes = curr->disk_total_bytes;
7609 curr->commit_bytes_used = curr->bytes_used;
7611 mutex_unlock(&trans->fs_info->chunk_mutex);
7614 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7616 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7617 while (fs_devices) {
7618 fs_devices->fs_info = fs_info;
7619 fs_devices = fs_devices->seed;
7623 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7625 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7626 while (fs_devices) {
7627 fs_devices->fs_info = NULL;
7628 fs_devices = fs_devices->seed;
7633 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7635 int btrfs_bg_type_to_factor(u64 flags)
7637 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
7638 BTRFS_BLOCK_GROUP_RAID10))
7644 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
7646 int index = btrfs_bg_flags_to_raid_index(type);
7647 int ncopies = btrfs_raid_array[index].ncopies;
7650 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
7651 case BTRFS_BLOCK_GROUP_RAID5:
7652 data_stripes = num_stripes - 1;
7654 case BTRFS_BLOCK_GROUP_RAID6:
7655 data_stripes = num_stripes - 2;
7658 data_stripes = num_stripes / ncopies;
7661 return div_u64(chunk_len, data_stripes);
7664 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7665 u64 chunk_offset, u64 devid,
7666 u64 physical_offset, u64 physical_len)
7668 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7669 struct extent_map *em;
7670 struct map_lookup *map;
7671 struct btrfs_device *dev;
7677 read_lock(&em_tree->lock);
7678 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7679 read_unlock(&em_tree->lock);
7683 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7684 physical_offset, devid);
7689 map = em->map_lookup;
7690 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7691 if (physical_len != stripe_len) {
7693 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7694 physical_offset, devid, em->start, physical_len,
7700 for (i = 0; i < map->num_stripes; i++) {
7701 if (map->stripes[i].dev->devid == devid &&
7702 map->stripes[i].physical == physical_offset) {
7704 if (map->verified_stripes >= map->num_stripes) {
7706 "too many dev extents for chunk %llu found",
7711 map->verified_stripes++;
7717 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7718 physical_offset, devid);
7722 /* Make sure no dev extent is beyond device bondary */
7723 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7725 btrfs_err(fs_info, "failed to find devid %llu", devid);
7730 /* It's possible this device is a dummy for seed device */
7731 if (dev->disk_total_bytes == 0) {
7732 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7735 btrfs_err(fs_info, "failed to find seed devid %llu",
7742 if (physical_offset + physical_len > dev->disk_total_bytes) {
7744 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7745 devid, physical_offset, physical_len,
7746 dev->disk_total_bytes);
7751 free_extent_map(em);
7755 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7757 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7758 struct extent_map *em;
7759 struct rb_node *node;
7762 read_lock(&em_tree->lock);
7763 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7764 em = rb_entry(node, struct extent_map, rb_node);
7765 if (em->map_lookup->num_stripes !=
7766 em->map_lookup->verified_stripes) {
7768 "chunk %llu has missing dev extent, have %d expect %d",
7769 em->start, em->map_lookup->verified_stripes,
7770 em->map_lookup->num_stripes);
7776 read_unlock(&em_tree->lock);
7781 * Ensure that all dev extents are mapped to correct chunk, otherwise
7782 * later chunk allocation/free would cause unexpected behavior.
7784 * NOTE: This will iterate through the whole device tree, which should be of
7785 * the same size level as the chunk tree. This slightly increases mount time.
7787 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7789 struct btrfs_path *path;
7790 struct btrfs_root *root = fs_info->dev_root;
7791 struct btrfs_key key;
7793 u64 prev_dev_ext_end = 0;
7797 key.type = BTRFS_DEV_EXTENT_KEY;
7800 path = btrfs_alloc_path();
7804 path->reada = READA_FORWARD;
7805 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7809 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7810 ret = btrfs_next_item(root, path);
7813 /* No dev extents at all? Not good */
7820 struct extent_buffer *leaf = path->nodes[0];
7821 struct btrfs_dev_extent *dext;
7822 int slot = path->slots[0];
7824 u64 physical_offset;
7828 btrfs_item_key_to_cpu(leaf, &key, slot);
7829 if (key.type != BTRFS_DEV_EXTENT_KEY)
7831 devid = key.objectid;
7832 physical_offset = key.offset;
7834 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7835 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7836 physical_len = btrfs_dev_extent_length(leaf, dext);
7838 /* Check if this dev extent overlaps with the previous one */
7839 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7841 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7842 devid, physical_offset, prev_dev_ext_end);
7847 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7848 physical_offset, physical_len);
7852 prev_dev_ext_end = physical_offset + physical_len;
7854 ret = btrfs_next_item(root, path);
7863 /* Ensure all chunks have corresponding dev extents */
7864 ret = verify_chunk_dev_extent_mapping(fs_info);
7866 btrfs_free_path(path);
7871 * Check whether the given block group or device is pinned by any inode being
7872 * used as a swapfile.
7874 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7876 struct btrfs_swapfile_pin *sp;
7877 struct rb_node *node;
7879 spin_lock(&fs_info->swapfile_pins_lock);
7880 node = fs_info->swapfile_pins.rb_node;
7882 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7884 node = node->rb_left;
7885 else if (ptr > sp->ptr)
7886 node = node->rb_right;
7890 spin_unlock(&fs_info->swapfile_pins_lock);
7891 return node != NULL;