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 struct extent_buffer *l;
4724 struct btrfs_key key;
4725 struct btrfs_super_block *super_copy = fs_info->super_copy;
4726 u64 old_total = btrfs_super_total_bytes(super_copy);
4727 u64 old_size = btrfs_device_get_total_bytes(device);
4731 new_size = round_down(new_size, fs_info->sectorsize);
4733 diff = round_down(old_size - new_size, fs_info->sectorsize);
4735 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4738 path = btrfs_alloc_path();
4742 path->reada = READA_BACK;
4744 trans = btrfs_start_transaction(root, 0);
4745 if (IS_ERR(trans)) {
4746 btrfs_free_path(path);
4747 return PTR_ERR(trans);
4750 mutex_lock(&fs_info->chunk_mutex);
4752 btrfs_device_set_total_bytes(device, new_size);
4753 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4754 device->fs_devices->total_rw_bytes -= diff;
4755 atomic64_sub(diff, &fs_info->free_chunk_space);
4759 * Once the device's size has been set to the new size, ensure all
4760 * in-memory chunks are synced to disk so that the loop below sees them
4761 * and relocates them accordingly.
4763 if (contains_pending_extent(trans->transaction, device, &start, diff)) {
4764 mutex_unlock(&fs_info->chunk_mutex);
4765 ret = btrfs_commit_transaction(trans);
4769 mutex_unlock(&fs_info->chunk_mutex);
4770 btrfs_end_transaction(trans);
4774 key.objectid = device->devid;
4775 key.offset = (u64)-1;
4776 key.type = BTRFS_DEV_EXTENT_KEY;
4779 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4780 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4782 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4786 ret = btrfs_previous_item(root, path, 0, key.type);
4788 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4793 btrfs_release_path(path);
4798 slot = path->slots[0];
4799 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4801 if (key.objectid != device->devid) {
4802 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4803 btrfs_release_path(path);
4807 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4808 length = btrfs_dev_extent_length(l, dev_extent);
4810 if (key.offset + length <= new_size) {
4811 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4812 btrfs_release_path(path);
4816 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4817 btrfs_release_path(path);
4820 * We may be relocating the only data chunk we have,
4821 * which could potentially end up with losing data's
4822 * raid profile, so lets allocate an empty one in
4825 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4827 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4831 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4832 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4833 if (ret == -ENOSPC) {
4836 if (ret == -ETXTBSY) {
4838 "could not shrink block group %llu due to active swapfile",
4843 } while (key.offset-- > 0);
4845 if (failed && !retried) {
4849 } else if (failed && retried) {
4854 /* Shrinking succeeded, else we would be at "done". */
4855 trans = btrfs_start_transaction(root, 0);
4856 if (IS_ERR(trans)) {
4857 ret = PTR_ERR(trans);
4861 mutex_lock(&fs_info->chunk_mutex);
4862 btrfs_device_set_disk_total_bytes(device, new_size);
4863 if (list_empty(&device->post_commit_list))
4864 list_add_tail(&device->post_commit_list,
4865 &trans->transaction->dev_update_list);
4867 WARN_ON(diff > old_total);
4868 btrfs_set_super_total_bytes(super_copy,
4869 round_down(old_total - diff, fs_info->sectorsize));
4870 mutex_unlock(&fs_info->chunk_mutex);
4872 /* Now btrfs_update_device() will change the on-disk size. */
4873 ret = btrfs_update_device(trans, device);
4875 btrfs_abort_transaction(trans, ret);
4876 btrfs_end_transaction(trans);
4878 ret = btrfs_commit_transaction(trans);
4881 btrfs_free_path(path);
4883 mutex_lock(&fs_info->chunk_mutex);
4884 btrfs_device_set_total_bytes(device, old_size);
4885 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4886 device->fs_devices->total_rw_bytes += diff;
4887 atomic64_add(diff, &fs_info->free_chunk_space);
4888 mutex_unlock(&fs_info->chunk_mutex);
4893 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4894 struct btrfs_key *key,
4895 struct btrfs_chunk *chunk, int item_size)
4897 struct btrfs_super_block *super_copy = fs_info->super_copy;
4898 struct btrfs_disk_key disk_key;
4902 mutex_lock(&fs_info->chunk_mutex);
4903 array_size = btrfs_super_sys_array_size(super_copy);
4904 if (array_size + item_size + sizeof(disk_key)
4905 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4906 mutex_unlock(&fs_info->chunk_mutex);
4910 ptr = super_copy->sys_chunk_array + array_size;
4911 btrfs_cpu_key_to_disk(&disk_key, key);
4912 memcpy(ptr, &disk_key, sizeof(disk_key));
4913 ptr += sizeof(disk_key);
4914 memcpy(ptr, chunk, item_size);
4915 item_size += sizeof(disk_key);
4916 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4917 mutex_unlock(&fs_info->chunk_mutex);
4923 * sort the devices in descending order by max_avail, total_avail
4925 static int btrfs_cmp_device_info(const void *a, const void *b)
4927 const struct btrfs_device_info *di_a = a;
4928 const struct btrfs_device_info *di_b = b;
4930 if (di_a->max_avail > di_b->max_avail)
4932 if (di_a->max_avail < di_b->max_avail)
4934 if (di_a->total_avail > di_b->total_avail)
4936 if (di_a->total_avail < di_b->total_avail)
4941 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4943 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4946 btrfs_set_fs_incompat(info, RAID56);
4949 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4950 u64 start, u64 type)
4952 struct btrfs_fs_info *info = trans->fs_info;
4953 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4954 struct btrfs_device *device;
4955 struct map_lookup *map = NULL;
4956 struct extent_map_tree *em_tree;
4957 struct extent_map *em;
4958 struct btrfs_device_info *devices_info = NULL;
4960 int num_stripes; /* total number of stripes to allocate */
4961 int data_stripes; /* number of stripes that count for
4963 int sub_stripes; /* sub_stripes info for map */
4964 int dev_stripes; /* stripes per dev */
4965 int devs_max; /* max devs to use */
4966 int devs_min; /* min devs needed */
4967 int devs_increment; /* ndevs has to be a multiple of this */
4968 int ncopies; /* how many copies to data has */
4969 int nparity; /* number of stripes worth of bytes to
4970 store parity information */
4972 u64 max_stripe_size;
4981 BUG_ON(!alloc_profile_is_valid(type, 0));
4983 if (list_empty(&fs_devices->alloc_list)) {
4984 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4985 btrfs_debug(info, "%s: no writable device", __func__);
4989 index = btrfs_bg_flags_to_raid_index(type);
4991 sub_stripes = btrfs_raid_array[index].sub_stripes;
4992 dev_stripes = btrfs_raid_array[index].dev_stripes;
4993 devs_max = btrfs_raid_array[index].devs_max;
4994 devs_min = btrfs_raid_array[index].devs_min;
4995 devs_increment = btrfs_raid_array[index].devs_increment;
4996 ncopies = btrfs_raid_array[index].ncopies;
4997 nparity = btrfs_raid_array[index].nparity;
4999 if (type & BTRFS_BLOCK_GROUP_DATA) {
5000 max_stripe_size = SZ_1G;
5001 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
5003 devs_max = BTRFS_MAX_DEVS(info);
5004 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5005 /* for larger filesystems, use larger metadata chunks */
5006 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
5007 max_stripe_size = SZ_1G;
5009 max_stripe_size = SZ_256M;
5010 max_chunk_size = max_stripe_size;
5012 devs_max = BTRFS_MAX_DEVS(info);
5013 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5014 max_stripe_size = SZ_32M;
5015 max_chunk_size = 2 * max_stripe_size;
5017 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
5019 btrfs_err(info, "invalid chunk type 0x%llx requested",
5024 /* We don't want a chunk larger than 10% of writable space */
5025 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
5028 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5034 * in the first pass through the devices list, we gather information
5035 * about the available holes on each device.
5038 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5042 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5044 "BTRFS: read-only device in alloc_list\n");
5048 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5049 &device->dev_state) ||
5050 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5053 if (device->total_bytes > device->bytes_used)
5054 total_avail = device->total_bytes - device->bytes_used;
5058 /* If there is no space on this device, skip it. */
5059 if (total_avail == 0)
5062 ret = find_free_dev_extent(trans, device,
5063 max_stripe_size * dev_stripes,
5064 &dev_offset, &max_avail);
5065 if (ret && ret != -ENOSPC)
5069 max_avail = max_stripe_size * dev_stripes;
5071 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
5072 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5074 "%s: devid %llu has no free space, have=%llu want=%u",
5075 __func__, device->devid, max_avail,
5076 BTRFS_STRIPE_LEN * dev_stripes);
5080 if (ndevs == fs_devices->rw_devices) {
5081 WARN(1, "%s: found more than %llu devices\n",
5082 __func__, fs_devices->rw_devices);
5085 devices_info[ndevs].dev_offset = dev_offset;
5086 devices_info[ndevs].max_avail = max_avail;
5087 devices_info[ndevs].total_avail = total_avail;
5088 devices_info[ndevs].dev = device;
5093 * now sort the devices by hole size / available space
5095 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5096 btrfs_cmp_device_info, NULL);
5098 /* round down to number of usable stripes */
5099 ndevs = round_down(ndevs, devs_increment);
5101 if (ndevs < devs_min) {
5103 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5105 "%s: not enough devices with free space: have=%d minimum required=%d",
5106 __func__, ndevs, devs_min);
5111 ndevs = min(ndevs, devs_max);
5114 * The primary goal is to maximize the number of stripes, so use as
5115 * many devices as possible, even if the stripes are not maximum sized.
5117 * The DUP profile stores more than one stripe per device, the
5118 * max_avail is the total size so we have to adjust.
5120 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
5121 num_stripes = ndevs * dev_stripes;
5124 * this will have to be fixed for RAID1 and RAID10 over
5127 data_stripes = (num_stripes - nparity) / ncopies;
5130 * Use the number of data stripes to figure out how big this chunk
5131 * is really going to be in terms of logical address space,
5132 * and compare that answer with the max chunk size. If it's higher,
5133 * we try to reduce stripe_size.
5135 if (stripe_size * data_stripes > max_chunk_size) {
5137 * Reduce stripe_size, round it up to a 16MB boundary again and
5138 * then use it, unless it ends up being even bigger than the
5139 * previous value we had already.
5141 stripe_size = min(round_up(div_u64(max_chunk_size,
5142 data_stripes), SZ_16M),
5146 /* align to BTRFS_STRIPE_LEN */
5147 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
5149 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5154 map->num_stripes = num_stripes;
5156 for (i = 0; i < ndevs; ++i) {
5157 for (j = 0; j < dev_stripes; ++j) {
5158 int s = i * dev_stripes + j;
5159 map->stripes[s].dev = devices_info[i].dev;
5160 map->stripes[s].physical = devices_info[i].dev_offset +
5164 map->stripe_len = BTRFS_STRIPE_LEN;
5165 map->io_align = BTRFS_STRIPE_LEN;
5166 map->io_width = BTRFS_STRIPE_LEN;
5168 map->sub_stripes = sub_stripes;
5170 chunk_size = stripe_size * data_stripes;
5172 trace_btrfs_chunk_alloc(info, map, start, chunk_size);
5174 em = alloc_extent_map();
5180 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5181 em->map_lookup = map;
5183 em->len = chunk_size;
5184 em->block_start = 0;
5185 em->block_len = em->len;
5186 em->orig_block_len = stripe_size;
5188 em_tree = &info->mapping_tree.map_tree;
5189 write_lock(&em_tree->lock);
5190 ret = add_extent_mapping(em_tree, em, 0);
5192 write_unlock(&em_tree->lock);
5193 free_extent_map(em);
5197 list_add_tail(&em->list, &trans->transaction->pending_chunks);
5198 refcount_inc(&em->refs);
5199 write_unlock(&em_tree->lock);
5201 ret = btrfs_make_block_group(trans, 0, type, start, chunk_size);
5203 goto error_del_extent;
5205 for (i = 0; i < map->num_stripes; i++) {
5206 struct btrfs_device *dev = map->stripes[i].dev;
5208 btrfs_device_set_bytes_used(dev, dev->bytes_used + stripe_size);
5209 if (list_empty(&dev->post_commit_list))
5210 list_add_tail(&dev->post_commit_list,
5211 &trans->transaction->dev_update_list);
5214 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
5216 free_extent_map(em);
5217 check_raid56_incompat_flag(info, type);
5219 kfree(devices_info);
5223 write_lock(&em_tree->lock);
5224 remove_extent_mapping(em_tree, em);
5225 write_unlock(&em_tree->lock);
5227 /* One for our allocation */
5228 free_extent_map(em);
5229 /* One for the tree reference */
5230 free_extent_map(em);
5231 /* One for the pending_chunks list reference */
5232 free_extent_map(em);
5234 kfree(devices_info);
5238 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5239 u64 chunk_offset, u64 chunk_size)
5241 struct btrfs_fs_info *fs_info = trans->fs_info;
5242 struct btrfs_root *extent_root = fs_info->extent_root;
5243 struct btrfs_root *chunk_root = fs_info->chunk_root;
5244 struct btrfs_key key;
5245 struct btrfs_device *device;
5246 struct btrfs_chunk *chunk;
5247 struct btrfs_stripe *stripe;
5248 struct extent_map *em;
5249 struct map_lookup *map;
5256 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5260 map = em->map_lookup;
5261 item_size = btrfs_chunk_item_size(map->num_stripes);
5262 stripe_size = em->orig_block_len;
5264 chunk = kzalloc(item_size, GFP_NOFS);
5271 * Take the device list mutex to prevent races with the final phase of
5272 * a device replace operation that replaces the device object associated
5273 * with the map's stripes, because the device object's id can change
5274 * at any time during that final phase of the device replace operation
5275 * (dev-replace.c:btrfs_dev_replace_finishing()).
5277 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5278 for (i = 0; i < map->num_stripes; i++) {
5279 device = map->stripes[i].dev;
5280 dev_offset = map->stripes[i].physical;
5282 ret = btrfs_update_device(trans, device);
5285 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5286 dev_offset, stripe_size);
5291 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5295 stripe = &chunk->stripe;
5296 for (i = 0; i < map->num_stripes; i++) {
5297 device = map->stripes[i].dev;
5298 dev_offset = map->stripes[i].physical;
5300 btrfs_set_stack_stripe_devid(stripe, device->devid);
5301 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5302 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5305 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5307 btrfs_set_stack_chunk_length(chunk, chunk_size);
5308 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5309 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5310 btrfs_set_stack_chunk_type(chunk, map->type);
5311 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5312 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5313 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5314 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5315 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5317 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5318 key.type = BTRFS_CHUNK_ITEM_KEY;
5319 key.offset = chunk_offset;
5321 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5322 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5324 * TODO: Cleanup of inserted chunk root in case of
5327 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5332 free_extent_map(em);
5337 * Chunk allocation falls into two parts. The first part does work
5338 * that makes the new allocated chunk usable, but does not do any operation
5339 * that modifies the chunk tree. The second part does the work that
5340 * requires modifying the chunk tree. This division is important for the
5341 * bootstrap process of adding storage to a seed btrfs.
5343 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5347 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5348 chunk_offset = find_next_chunk(trans->fs_info);
5349 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5352 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5353 struct btrfs_fs_info *fs_info)
5356 u64 sys_chunk_offset;
5360 chunk_offset = find_next_chunk(fs_info);
5361 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5362 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5366 sys_chunk_offset = find_next_chunk(fs_info);
5367 alloc_profile = btrfs_system_alloc_profile(fs_info);
5368 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5372 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5376 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5377 BTRFS_BLOCK_GROUP_RAID10 |
5378 BTRFS_BLOCK_GROUP_RAID5 |
5379 BTRFS_BLOCK_GROUP_DUP)) {
5381 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5390 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5392 struct extent_map *em;
5393 struct map_lookup *map;
5398 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5402 map = em->map_lookup;
5403 for (i = 0; i < map->num_stripes; i++) {
5404 if (test_bit(BTRFS_DEV_STATE_MISSING,
5405 &map->stripes[i].dev->dev_state)) {
5409 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5410 &map->stripes[i].dev->dev_state)) {
5417 * If the number of missing devices is larger than max errors,
5418 * we can not write the data into that chunk successfully, so
5421 if (miss_ndevs > btrfs_chunk_max_errors(map))
5424 free_extent_map(em);
5428 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5430 extent_map_tree_init(&tree->map_tree);
5433 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5435 struct extent_map *em;
5438 write_lock(&tree->map_tree.lock);
5439 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5441 remove_extent_mapping(&tree->map_tree, em);
5442 write_unlock(&tree->map_tree.lock);
5446 free_extent_map(em);
5447 /* once for the tree */
5448 free_extent_map(em);
5452 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5454 struct extent_map *em;
5455 struct map_lookup *map;
5458 em = btrfs_get_chunk_map(fs_info, logical, len);
5461 * We could return errors for these cases, but that could get
5462 * ugly and we'd probably do the same thing which is just not do
5463 * anything else and exit, so return 1 so the callers don't try
5464 * to use other copies.
5468 map = em->map_lookup;
5469 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5470 ret = map->num_stripes;
5471 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5472 ret = map->sub_stripes;
5473 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5475 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5477 * There could be two corrupted data stripes, we need
5478 * to loop retry in order to rebuild the correct data.
5480 * Fail a stripe at a time on every retry except the
5481 * stripe under reconstruction.
5483 ret = map->num_stripes;
5486 free_extent_map(em);
5488 down_read(&fs_info->dev_replace.rwsem);
5489 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5490 fs_info->dev_replace.tgtdev)
5492 up_read(&fs_info->dev_replace.rwsem);
5497 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5500 struct extent_map *em;
5501 struct map_lookup *map;
5502 unsigned long len = fs_info->sectorsize;
5504 em = btrfs_get_chunk_map(fs_info, logical, len);
5506 if (!WARN_ON(IS_ERR(em))) {
5507 map = em->map_lookup;
5508 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5509 len = map->stripe_len * nr_data_stripes(map);
5510 free_extent_map(em);
5515 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5517 struct extent_map *em;
5518 struct map_lookup *map;
5521 em = btrfs_get_chunk_map(fs_info, logical, len);
5523 if(!WARN_ON(IS_ERR(em))) {
5524 map = em->map_lookup;
5525 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5527 free_extent_map(em);
5532 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5533 struct map_lookup *map, int first,
5534 int dev_replace_is_ongoing)
5538 int preferred_mirror;
5540 struct btrfs_device *srcdev;
5543 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5545 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5546 num_stripes = map->sub_stripes;
5548 num_stripes = map->num_stripes;
5550 preferred_mirror = first + current->pid % num_stripes;
5552 if (dev_replace_is_ongoing &&
5553 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5554 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5555 srcdev = fs_info->dev_replace.srcdev;
5560 * try to avoid the drive that is the source drive for a
5561 * dev-replace procedure, only choose it if no other non-missing
5562 * mirror is available
5564 for (tolerance = 0; tolerance < 2; tolerance++) {
5565 if (map->stripes[preferred_mirror].dev->bdev &&
5566 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5567 return preferred_mirror;
5568 for (i = first; i < first + num_stripes; i++) {
5569 if (map->stripes[i].dev->bdev &&
5570 (tolerance || map->stripes[i].dev != srcdev))
5575 /* we couldn't find one that doesn't fail. Just return something
5576 * and the io error handling code will clean up eventually
5578 return preferred_mirror;
5581 static inline int parity_smaller(u64 a, u64 b)
5586 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5587 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5589 struct btrfs_bio_stripe s;
5596 for (i = 0; i < num_stripes - 1; i++) {
5597 if (parity_smaller(bbio->raid_map[i],
5598 bbio->raid_map[i+1])) {
5599 s = bbio->stripes[i];
5600 l = bbio->raid_map[i];
5601 bbio->stripes[i] = bbio->stripes[i+1];
5602 bbio->raid_map[i] = bbio->raid_map[i+1];
5603 bbio->stripes[i+1] = s;
5604 bbio->raid_map[i+1] = l;
5612 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5614 struct btrfs_bio *bbio = kzalloc(
5615 /* the size of the btrfs_bio */
5616 sizeof(struct btrfs_bio) +
5617 /* plus the variable array for the stripes */
5618 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5619 /* plus the variable array for the tgt dev */
5620 sizeof(int) * (real_stripes) +
5622 * plus the raid_map, which includes both the tgt dev
5625 sizeof(u64) * (total_stripes),
5626 GFP_NOFS|__GFP_NOFAIL);
5628 atomic_set(&bbio->error, 0);
5629 refcount_set(&bbio->refs, 1);
5634 void btrfs_get_bbio(struct btrfs_bio *bbio)
5636 WARN_ON(!refcount_read(&bbio->refs));
5637 refcount_inc(&bbio->refs);
5640 void btrfs_put_bbio(struct btrfs_bio *bbio)
5644 if (refcount_dec_and_test(&bbio->refs))
5648 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5650 * Please note that, discard won't be sent to target device of device
5653 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5654 u64 logical, u64 length,
5655 struct btrfs_bio **bbio_ret)
5657 struct extent_map *em;
5658 struct map_lookup *map;
5659 struct btrfs_bio *bbio;
5663 u64 stripe_end_offset;
5670 u32 sub_stripes = 0;
5671 u64 stripes_per_dev = 0;
5672 u32 remaining_stripes = 0;
5673 u32 last_stripe = 0;
5677 /* discard always return a bbio */
5680 em = btrfs_get_chunk_map(fs_info, logical, length);
5684 map = em->map_lookup;
5685 /* we don't discard raid56 yet */
5686 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5691 offset = logical - em->start;
5692 length = min_t(u64, em->len - offset, length);
5694 stripe_len = map->stripe_len;
5696 * stripe_nr counts the total number of stripes we have to stride
5697 * to get to this block
5699 stripe_nr = div64_u64(offset, stripe_len);
5701 /* stripe_offset is the offset of this block in its stripe */
5702 stripe_offset = offset - stripe_nr * stripe_len;
5704 stripe_nr_end = round_up(offset + length, map->stripe_len);
5705 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5706 stripe_cnt = stripe_nr_end - stripe_nr;
5707 stripe_end_offset = stripe_nr_end * map->stripe_len -
5710 * after this, stripe_nr is the number of stripes on this
5711 * device we have to walk to find the data, and stripe_index is
5712 * the number of our device in the stripe array
5716 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5717 BTRFS_BLOCK_GROUP_RAID10)) {
5718 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5721 sub_stripes = map->sub_stripes;
5723 factor = map->num_stripes / sub_stripes;
5724 num_stripes = min_t(u64, map->num_stripes,
5725 sub_stripes * stripe_cnt);
5726 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5727 stripe_index *= sub_stripes;
5728 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5729 &remaining_stripes);
5730 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5731 last_stripe *= sub_stripes;
5732 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5733 BTRFS_BLOCK_GROUP_DUP)) {
5734 num_stripes = map->num_stripes;
5736 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5740 bbio = alloc_btrfs_bio(num_stripes, 0);
5746 for (i = 0; i < num_stripes; i++) {
5747 bbio->stripes[i].physical =
5748 map->stripes[stripe_index].physical +
5749 stripe_offset + stripe_nr * map->stripe_len;
5750 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5752 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5753 BTRFS_BLOCK_GROUP_RAID10)) {
5754 bbio->stripes[i].length = stripes_per_dev *
5757 if (i / sub_stripes < remaining_stripes)
5758 bbio->stripes[i].length +=
5762 * Special for the first stripe and
5765 * |-------|...|-------|
5769 if (i < sub_stripes)
5770 bbio->stripes[i].length -=
5773 if (stripe_index >= last_stripe &&
5774 stripe_index <= (last_stripe +
5776 bbio->stripes[i].length -=
5779 if (i == sub_stripes - 1)
5782 bbio->stripes[i].length = length;
5786 if (stripe_index == map->num_stripes) {
5793 bbio->map_type = map->type;
5794 bbio->num_stripes = num_stripes;
5796 free_extent_map(em);
5801 * In dev-replace case, for repair case (that's the only case where the mirror
5802 * is selected explicitly when calling btrfs_map_block), blocks left of the
5803 * left cursor can also be read from the target drive.
5805 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5807 * For READ, it also needs to be supported using the same mirror number.
5809 * If the requested block is not left of the left cursor, EIO is returned. This
5810 * can happen because btrfs_num_copies() returns one more in the dev-replace
5813 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5814 u64 logical, u64 length,
5815 u64 srcdev_devid, int *mirror_num,
5818 struct btrfs_bio *bbio = NULL;
5820 int index_srcdev = 0;
5822 u64 physical_of_found = 0;
5826 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5827 logical, &length, &bbio, 0, 0);
5829 ASSERT(bbio == NULL);
5833 num_stripes = bbio->num_stripes;
5834 if (*mirror_num > num_stripes) {
5836 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5837 * that means that the requested area is not left of the left
5840 btrfs_put_bbio(bbio);
5845 * process the rest of the function using the mirror_num of the source
5846 * drive. Therefore look it up first. At the end, patch the device
5847 * pointer to the one of the target drive.
5849 for (i = 0; i < num_stripes; i++) {
5850 if (bbio->stripes[i].dev->devid != srcdev_devid)
5854 * In case of DUP, in order to keep it simple, only add the
5855 * mirror with the lowest physical address
5858 physical_of_found <= bbio->stripes[i].physical)
5863 physical_of_found = bbio->stripes[i].physical;
5866 btrfs_put_bbio(bbio);
5872 *mirror_num = index_srcdev + 1;
5873 *physical = physical_of_found;
5877 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5878 struct btrfs_bio **bbio_ret,
5879 struct btrfs_dev_replace *dev_replace,
5880 int *num_stripes_ret, int *max_errors_ret)
5882 struct btrfs_bio *bbio = *bbio_ret;
5883 u64 srcdev_devid = dev_replace->srcdev->devid;
5884 int tgtdev_indexes = 0;
5885 int num_stripes = *num_stripes_ret;
5886 int max_errors = *max_errors_ret;
5889 if (op == BTRFS_MAP_WRITE) {
5890 int index_where_to_add;
5893 * duplicate the write operations while the dev replace
5894 * procedure is running. Since the copying of the old disk to
5895 * the new disk takes place at run time while the filesystem is
5896 * mounted writable, the regular write operations to the old
5897 * disk have to be duplicated to go to the new disk as well.
5899 * Note that device->missing is handled by the caller, and that
5900 * the write to the old disk is already set up in the stripes
5903 index_where_to_add = num_stripes;
5904 for (i = 0; i < num_stripes; i++) {
5905 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5906 /* write to new disk, too */
5907 struct btrfs_bio_stripe *new =
5908 bbio->stripes + index_where_to_add;
5909 struct btrfs_bio_stripe *old =
5912 new->physical = old->physical;
5913 new->length = old->length;
5914 new->dev = dev_replace->tgtdev;
5915 bbio->tgtdev_map[i] = index_where_to_add;
5916 index_where_to_add++;
5921 num_stripes = index_where_to_add;
5922 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5923 int index_srcdev = 0;
5925 u64 physical_of_found = 0;
5928 * During the dev-replace procedure, the target drive can also
5929 * be used to read data in case it is needed to repair a corrupt
5930 * block elsewhere. This is possible if the requested area is
5931 * left of the left cursor. In this area, the target drive is a
5932 * full copy of the source drive.
5934 for (i = 0; i < num_stripes; i++) {
5935 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5937 * In case of DUP, in order to keep it simple,
5938 * only add the mirror with the lowest physical
5942 physical_of_found <=
5943 bbio->stripes[i].physical)
5947 physical_of_found = bbio->stripes[i].physical;
5951 struct btrfs_bio_stripe *tgtdev_stripe =
5952 bbio->stripes + num_stripes;
5954 tgtdev_stripe->physical = physical_of_found;
5955 tgtdev_stripe->length =
5956 bbio->stripes[index_srcdev].length;
5957 tgtdev_stripe->dev = dev_replace->tgtdev;
5958 bbio->tgtdev_map[index_srcdev] = num_stripes;
5965 *num_stripes_ret = num_stripes;
5966 *max_errors_ret = max_errors;
5967 bbio->num_tgtdevs = tgtdev_indexes;
5971 static bool need_full_stripe(enum btrfs_map_op op)
5973 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5976 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5977 enum btrfs_map_op op,
5978 u64 logical, u64 *length,
5979 struct btrfs_bio **bbio_ret,
5980 int mirror_num, int need_raid_map)
5982 struct extent_map *em;
5983 struct map_lookup *map;
5993 int tgtdev_indexes = 0;
5994 struct btrfs_bio *bbio = NULL;
5995 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5996 int dev_replace_is_ongoing = 0;
5997 int num_alloc_stripes;
5998 int patch_the_first_stripe_for_dev_replace = 0;
5999 u64 physical_to_patch_in_first_stripe = 0;
6000 u64 raid56_full_stripe_start = (u64)-1;
6002 if (op == BTRFS_MAP_DISCARD)
6003 return __btrfs_map_block_for_discard(fs_info, logical,
6006 em = btrfs_get_chunk_map(fs_info, logical, *length);
6010 map = em->map_lookup;
6011 offset = logical - em->start;
6013 stripe_len = map->stripe_len;
6016 * stripe_nr counts the total number of stripes we have to stride
6017 * to get to this block
6019 stripe_nr = div64_u64(stripe_nr, stripe_len);
6021 stripe_offset = stripe_nr * stripe_len;
6022 if (offset < stripe_offset) {
6024 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
6025 stripe_offset, offset, em->start, logical,
6027 free_extent_map(em);
6031 /* stripe_offset is the offset of this block in its stripe*/
6032 stripe_offset = offset - stripe_offset;
6034 /* if we're here for raid56, we need to know the stripe aligned start */
6035 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6036 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
6037 raid56_full_stripe_start = offset;
6039 /* allow a write of a full stripe, but make sure we don't
6040 * allow straddling of stripes
6042 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6044 raid56_full_stripe_start *= full_stripe_len;
6047 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6049 /* For writes to RAID[56], allow a full stripeset across all disks.
6050 For other RAID types and for RAID[56] reads, just allow a single
6051 stripe (on a single disk). */
6052 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6053 (op == BTRFS_MAP_WRITE)) {
6054 max_len = stripe_len * nr_data_stripes(map) -
6055 (offset - raid56_full_stripe_start);
6057 /* we limit the length of each bio to what fits in a stripe */
6058 max_len = stripe_len - stripe_offset;
6060 *length = min_t(u64, em->len - offset, max_len);
6062 *length = em->len - offset;
6066 * This is for when we're called from btrfs_bio_fits_in_stripe and all
6067 * it cares about is the length
6072 down_read(&dev_replace->rwsem);
6073 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6075 * Hold the semaphore for read during the whole operation, write is
6076 * requested at commit time but must wait.
6078 if (!dev_replace_is_ongoing)
6079 up_read(&dev_replace->rwsem);
6081 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6082 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6083 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6084 dev_replace->srcdev->devid,
6086 &physical_to_patch_in_first_stripe);
6090 patch_the_first_stripe_for_dev_replace = 1;
6091 } else if (mirror_num > map->num_stripes) {
6097 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6098 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6100 if (!need_full_stripe(op))
6102 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
6103 if (need_full_stripe(op))
6104 num_stripes = map->num_stripes;
6105 else if (mirror_num)
6106 stripe_index = mirror_num - 1;
6108 stripe_index = find_live_mirror(fs_info, map, 0,
6109 dev_replace_is_ongoing);
6110 mirror_num = stripe_index + 1;
6113 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6114 if (need_full_stripe(op)) {
6115 num_stripes = map->num_stripes;
6116 } else if (mirror_num) {
6117 stripe_index = mirror_num - 1;
6122 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6123 u32 factor = map->num_stripes / map->sub_stripes;
6125 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6126 stripe_index *= map->sub_stripes;
6128 if (need_full_stripe(op))
6129 num_stripes = map->sub_stripes;
6130 else if (mirror_num)
6131 stripe_index += mirror_num - 1;
6133 int old_stripe_index = stripe_index;
6134 stripe_index = find_live_mirror(fs_info, map,
6136 dev_replace_is_ongoing);
6137 mirror_num = stripe_index - old_stripe_index + 1;
6140 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6141 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6142 /* push stripe_nr back to the start of the full stripe */
6143 stripe_nr = div64_u64(raid56_full_stripe_start,
6144 stripe_len * nr_data_stripes(map));
6146 /* RAID[56] write or recovery. Return all stripes */
6147 num_stripes = map->num_stripes;
6148 max_errors = nr_parity_stripes(map);
6150 *length = map->stripe_len;
6155 * Mirror #0 or #1 means the original data block.
6156 * Mirror #2 is RAID5 parity block.
6157 * Mirror #3 is RAID6 Q block.
6159 stripe_nr = div_u64_rem(stripe_nr,
6160 nr_data_stripes(map), &stripe_index);
6162 stripe_index = nr_data_stripes(map) +
6165 /* We distribute the parity blocks across stripes */
6166 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6168 if (!need_full_stripe(op) && mirror_num <= 1)
6173 * after this, stripe_nr is the number of stripes on this
6174 * device we have to walk to find the data, and stripe_index is
6175 * the number of our device in the stripe array
6177 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6179 mirror_num = stripe_index + 1;
6181 if (stripe_index >= map->num_stripes) {
6183 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6184 stripe_index, map->num_stripes);
6189 num_alloc_stripes = num_stripes;
6190 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6191 if (op == BTRFS_MAP_WRITE)
6192 num_alloc_stripes <<= 1;
6193 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6194 num_alloc_stripes++;
6195 tgtdev_indexes = num_stripes;
6198 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6203 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
6204 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
6206 /* build raid_map */
6207 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6208 (need_full_stripe(op) || mirror_num > 1)) {
6212 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6213 sizeof(struct btrfs_bio_stripe) *
6215 sizeof(int) * tgtdev_indexes);
6217 /* Work out the disk rotation on this stripe-set */
6218 div_u64_rem(stripe_nr, num_stripes, &rot);
6220 /* Fill in the logical address of each stripe */
6221 tmp = stripe_nr * nr_data_stripes(map);
6222 for (i = 0; i < nr_data_stripes(map); i++)
6223 bbio->raid_map[(i+rot) % num_stripes] =
6224 em->start + (tmp + i) * map->stripe_len;
6226 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6227 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6228 bbio->raid_map[(i+rot+1) % num_stripes] =
6233 for (i = 0; i < num_stripes; i++) {
6234 bbio->stripes[i].physical =
6235 map->stripes[stripe_index].physical +
6237 stripe_nr * map->stripe_len;
6238 bbio->stripes[i].dev =
6239 map->stripes[stripe_index].dev;
6243 if (need_full_stripe(op))
6244 max_errors = btrfs_chunk_max_errors(map);
6247 sort_parity_stripes(bbio, num_stripes);
6249 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6250 need_full_stripe(op)) {
6251 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6256 bbio->map_type = map->type;
6257 bbio->num_stripes = num_stripes;
6258 bbio->max_errors = max_errors;
6259 bbio->mirror_num = mirror_num;
6262 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6263 * mirror_num == num_stripes + 1 && dev_replace target drive is
6264 * available as a mirror
6266 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6267 WARN_ON(num_stripes > 1);
6268 bbio->stripes[0].dev = dev_replace->tgtdev;
6269 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6270 bbio->mirror_num = map->num_stripes + 1;
6273 if (dev_replace_is_ongoing) {
6274 lockdep_assert_held(&dev_replace->rwsem);
6275 /* Unlock and let waiting writers proceed */
6276 up_read(&dev_replace->rwsem);
6278 free_extent_map(em);
6282 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6283 u64 logical, u64 *length,
6284 struct btrfs_bio **bbio_ret, int mirror_num)
6286 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6290 /* For Scrub/replace */
6291 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6292 u64 logical, u64 *length,
6293 struct btrfs_bio **bbio_ret)
6295 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6298 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
6299 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
6301 struct extent_map *em;
6302 struct map_lookup *map;
6310 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
6314 map = em->map_lookup;
6316 rmap_len = map->stripe_len;
6318 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6319 length = div_u64(length, map->num_stripes / map->sub_stripes);
6320 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6321 length = div_u64(length, map->num_stripes);
6322 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6323 length = div_u64(length, nr_data_stripes(map));
6324 rmap_len = map->stripe_len * nr_data_stripes(map);
6327 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6328 BUG_ON(!buf); /* -ENOMEM */
6330 for (i = 0; i < map->num_stripes; i++) {
6331 if (map->stripes[i].physical > physical ||
6332 map->stripes[i].physical + length <= physical)
6335 stripe_nr = physical - map->stripes[i].physical;
6336 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6338 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6339 stripe_nr = stripe_nr * map->num_stripes + i;
6340 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6341 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6342 stripe_nr = stripe_nr * map->num_stripes + i;
6343 } /* else if RAID[56], multiply by nr_data_stripes().
6344 * Alternatively, just use rmap_len below instead of
6345 * map->stripe_len */
6347 bytenr = chunk_start + stripe_nr * rmap_len;
6348 WARN_ON(nr >= map->num_stripes);
6349 for (j = 0; j < nr; j++) {
6350 if (buf[j] == bytenr)
6354 WARN_ON(nr >= map->num_stripes);
6361 *stripe_len = rmap_len;
6363 free_extent_map(em);
6367 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6369 bio->bi_private = bbio->private;
6370 bio->bi_end_io = bbio->end_io;
6373 btrfs_put_bbio(bbio);
6376 static void btrfs_end_bio(struct bio *bio)
6378 struct btrfs_bio *bbio = bio->bi_private;
6379 int is_orig_bio = 0;
6381 if (bio->bi_status) {
6382 atomic_inc(&bbio->error);
6383 if (bio->bi_status == BLK_STS_IOERR ||
6384 bio->bi_status == BLK_STS_TARGET) {
6385 unsigned int stripe_index =
6386 btrfs_io_bio(bio)->stripe_index;
6387 struct btrfs_device *dev;
6389 BUG_ON(stripe_index >= bbio->num_stripes);
6390 dev = bbio->stripes[stripe_index].dev;
6392 if (bio_op(bio) == REQ_OP_WRITE)
6393 btrfs_dev_stat_inc_and_print(dev,
6394 BTRFS_DEV_STAT_WRITE_ERRS);
6395 else if (!(bio->bi_opf & REQ_RAHEAD))
6396 btrfs_dev_stat_inc_and_print(dev,
6397 BTRFS_DEV_STAT_READ_ERRS);
6398 if (bio->bi_opf & REQ_PREFLUSH)
6399 btrfs_dev_stat_inc_and_print(dev,
6400 BTRFS_DEV_STAT_FLUSH_ERRS);
6405 if (bio == bbio->orig_bio)
6408 btrfs_bio_counter_dec(bbio->fs_info);
6410 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6413 bio = bbio->orig_bio;
6416 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6417 /* only send an error to the higher layers if it is
6418 * beyond the tolerance of the btrfs bio
6420 if (atomic_read(&bbio->error) > bbio->max_errors) {
6421 bio->bi_status = BLK_STS_IOERR;
6424 * this bio is actually up to date, we didn't
6425 * go over the max number of errors
6427 bio->bi_status = BLK_STS_OK;
6430 btrfs_end_bbio(bbio, bio);
6431 } else if (!is_orig_bio) {
6437 * see run_scheduled_bios for a description of why bios are collected for
6440 * This will add one bio to the pending list for a device and make sure
6441 * the work struct is scheduled.
6443 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6446 struct btrfs_fs_info *fs_info = device->fs_info;
6447 int should_queue = 1;
6448 struct btrfs_pending_bios *pending_bios;
6450 /* don't bother with additional async steps for reads, right now */
6451 if (bio_op(bio) == REQ_OP_READ) {
6452 btrfsic_submit_bio(bio);
6456 WARN_ON(bio->bi_next);
6457 bio->bi_next = NULL;
6459 spin_lock(&device->io_lock);
6460 if (op_is_sync(bio->bi_opf))
6461 pending_bios = &device->pending_sync_bios;
6463 pending_bios = &device->pending_bios;
6465 if (pending_bios->tail)
6466 pending_bios->tail->bi_next = bio;
6468 pending_bios->tail = bio;
6469 if (!pending_bios->head)
6470 pending_bios->head = bio;
6471 if (device->running_pending)
6474 spin_unlock(&device->io_lock);
6477 btrfs_queue_work(fs_info->submit_workers, &device->work);
6480 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6481 u64 physical, int dev_nr, int async)
6483 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6484 struct btrfs_fs_info *fs_info = bbio->fs_info;
6486 bio->bi_private = bbio;
6487 btrfs_io_bio(bio)->stripe_index = dev_nr;
6488 bio->bi_end_io = btrfs_end_bio;
6489 bio->bi_iter.bi_sector = physical >> 9;
6490 btrfs_debug_in_rcu(fs_info,
6491 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6492 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6493 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6494 bio->bi_iter.bi_size);
6495 bio_set_dev(bio, dev->bdev);
6497 btrfs_bio_counter_inc_noblocked(fs_info);
6500 btrfs_schedule_bio(dev, bio);
6502 btrfsic_submit_bio(bio);
6505 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6507 atomic_inc(&bbio->error);
6508 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6509 /* Should be the original bio. */
6510 WARN_ON(bio != bbio->orig_bio);
6512 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6513 bio->bi_iter.bi_sector = logical >> 9;
6514 if (atomic_read(&bbio->error) > bbio->max_errors)
6515 bio->bi_status = BLK_STS_IOERR;
6517 bio->bi_status = BLK_STS_OK;
6518 btrfs_end_bbio(bbio, bio);
6522 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6523 int mirror_num, int async_submit)
6525 struct btrfs_device *dev;
6526 struct bio *first_bio = bio;
6527 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6533 struct btrfs_bio *bbio = NULL;
6535 length = bio->bi_iter.bi_size;
6536 map_length = length;
6538 btrfs_bio_counter_inc_blocked(fs_info);
6539 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6540 &map_length, &bbio, mirror_num, 1);
6542 btrfs_bio_counter_dec(fs_info);
6543 return errno_to_blk_status(ret);
6546 total_devs = bbio->num_stripes;
6547 bbio->orig_bio = first_bio;
6548 bbio->private = first_bio->bi_private;
6549 bbio->end_io = first_bio->bi_end_io;
6550 bbio->fs_info = fs_info;
6551 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6553 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6554 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6555 /* In this case, map_length has been set to the length of
6556 a single stripe; not the whole write */
6557 if (bio_op(bio) == REQ_OP_WRITE) {
6558 ret = raid56_parity_write(fs_info, bio, bbio,
6561 ret = raid56_parity_recover(fs_info, bio, bbio,
6562 map_length, mirror_num, 1);
6565 btrfs_bio_counter_dec(fs_info);
6566 return errno_to_blk_status(ret);
6569 if (map_length < length) {
6571 "mapping failed logical %llu bio len %llu len %llu",
6572 logical, length, map_length);
6576 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6577 dev = bbio->stripes[dev_nr].dev;
6578 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6580 (bio_op(first_bio) == REQ_OP_WRITE &&
6581 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6582 bbio_error(bbio, first_bio, logical);
6586 if (dev_nr < total_devs - 1)
6587 bio = btrfs_bio_clone(first_bio);
6591 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6592 dev_nr, async_submit);
6594 btrfs_bio_counter_dec(fs_info);
6599 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6602 * If devid and uuid are both specified, the match must be exact, otherwise
6603 * only devid is used.
6605 * If @seed is true, traverse through the seed devices.
6607 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6608 u64 devid, u8 *uuid, u8 *fsid,
6611 struct btrfs_device *device;
6613 while (fs_devices) {
6615 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6616 list_for_each_entry(device, &fs_devices->devices,
6618 if (device->devid == devid &&
6619 (!uuid || memcmp(device->uuid, uuid,
6620 BTRFS_UUID_SIZE) == 0))
6625 fs_devices = fs_devices->seed;
6632 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6633 u64 devid, u8 *dev_uuid)
6635 struct btrfs_device *device;
6637 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6641 list_add(&device->dev_list, &fs_devices->devices);
6642 device->fs_devices = fs_devices;
6643 fs_devices->num_devices++;
6645 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6646 fs_devices->missing_devices++;
6652 * btrfs_alloc_device - allocate struct btrfs_device
6653 * @fs_info: used only for generating a new devid, can be NULL if
6654 * devid is provided (i.e. @devid != NULL).
6655 * @devid: a pointer to devid for this device. If NULL a new devid
6657 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6660 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6661 * on error. Returned struct is not linked onto any lists and must be
6662 * destroyed with btrfs_free_device.
6664 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6668 struct btrfs_device *dev;
6671 if (WARN_ON(!devid && !fs_info))
6672 return ERR_PTR(-EINVAL);
6674 dev = __alloc_device();
6683 ret = find_next_devid(fs_info, &tmp);
6685 btrfs_free_device(dev);
6686 return ERR_PTR(ret);
6692 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6694 generate_random_uuid(dev->uuid);
6696 btrfs_init_work(&dev->work, btrfs_submit_helper,
6697 pending_bios_fn, NULL, NULL);
6702 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6703 u64 devid, u8 *uuid, bool error)
6706 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6709 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6713 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6715 int index = btrfs_bg_flags_to_raid_index(type);
6716 int ncopies = btrfs_raid_array[index].ncopies;
6719 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6720 case BTRFS_BLOCK_GROUP_RAID5:
6721 data_stripes = num_stripes - 1;
6723 case BTRFS_BLOCK_GROUP_RAID6:
6724 data_stripes = num_stripes - 2;
6727 data_stripes = num_stripes / ncopies;
6730 return div_u64(chunk_len, data_stripes);
6733 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6734 struct extent_buffer *leaf,
6735 struct btrfs_chunk *chunk)
6737 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6738 struct map_lookup *map;
6739 struct extent_map *em;
6743 u8 uuid[BTRFS_UUID_SIZE];
6748 logical = key->offset;
6749 length = btrfs_chunk_length(leaf, chunk);
6750 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6753 * Only need to verify chunk item if we're reading from sys chunk array,
6754 * as chunk item in tree block is already verified by tree-checker.
6756 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6757 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6762 read_lock(&map_tree->map_tree.lock);
6763 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6764 read_unlock(&map_tree->map_tree.lock);
6766 /* already mapped? */
6767 if (em && em->start <= logical && em->start + em->len > logical) {
6768 free_extent_map(em);
6771 free_extent_map(em);
6774 em = alloc_extent_map();
6777 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6779 free_extent_map(em);
6783 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6784 em->map_lookup = map;
6785 em->start = logical;
6788 em->block_start = 0;
6789 em->block_len = em->len;
6791 map->num_stripes = num_stripes;
6792 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6793 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6794 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6795 map->type = btrfs_chunk_type(leaf, chunk);
6796 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6797 map->verified_stripes = 0;
6798 em->orig_block_len = calc_stripe_length(map->type, em->len,
6800 for (i = 0; i < num_stripes; i++) {
6801 map->stripes[i].physical =
6802 btrfs_stripe_offset_nr(leaf, chunk, i);
6803 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6804 read_extent_buffer(leaf, uuid, (unsigned long)
6805 btrfs_stripe_dev_uuid_nr(chunk, i),
6807 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6808 devid, uuid, NULL, true);
6809 if (!map->stripes[i].dev &&
6810 !btrfs_test_opt(fs_info, DEGRADED)) {
6811 free_extent_map(em);
6812 btrfs_report_missing_device(fs_info, devid, uuid, true);
6815 if (!map->stripes[i].dev) {
6816 map->stripes[i].dev =
6817 add_missing_dev(fs_info->fs_devices, devid,
6819 if (IS_ERR(map->stripes[i].dev)) {
6820 free_extent_map(em);
6822 "failed to init missing dev %llu: %ld",
6823 devid, PTR_ERR(map->stripes[i].dev));
6824 return PTR_ERR(map->stripes[i].dev);
6826 btrfs_report_missing_device(fs_info, devid, uuid, false);
6828 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6829 &(map->stripes[i].dev->dev_state));
6833 write_lock(&map_tree->map_tree.lock);
6834 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6835 write_unlock(&map_tree->map_tree.lock);
6838 "failed to add chunk map, start=%llu len=%llu: %d",
6839 em->start, em->len, ret);
6841 free_extent_map(em);
6846 static void fill_device_from_item(struct extent_buffer *leaf,
6847 struct btrfs_dev_item *dev_item,
6848 struct btrfs_device *device)
6852 device->devid = btrfs_device_id(leaf, dev_item);
6853 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6854 device->total_bytes = device->disk_total_bytes;
6855 device->commit_total_bytes = device->disk_total_bytes;
6856 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6857 device->commit_bytes_used = device->bytes_used;
6858 device->type = btrfs_device_type(leaf, dev_item);
6859 device->io_align = btrfs_device_io_align(leaf, dev_item);
6860 device->io_width = btrfs_device_io_width(leaf, dev_item);
6861 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6862 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6863 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6865 ptr = btrfs_device_uuid(dev_item);
6866 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6869 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6872 struct btrfs_fs_devices *fs_devices;
6875 lockdep_assert_held(&uuid_mutex);
6878 fs_devices = fs_info->fs_devices->seed;
6879 while (fs_devices) {
6880 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6883 fs_devices = fs_devices->seed;
6886 fs_devices = find_fsid(fsid, NULL);
6888 if (!btrfs_test_opt(fs_info, DEGRADED))
6889 return ERR_PTR(-ENOENT);
6891 fs_devices = alloc_fs_devices(fsid, NULL);
6892 if (IS_ERR(fs_devices))
6895 fs_devices->seeding = 1;
6896 fs_devices->opened = 1;
6900 fs_devices = clone_fs_devices(fs_devices);
6901 if (IS_ERR(fs_devices))
6904 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6906 free_fs_devices(fs_devices);
6907 fs_devices = ERR_PTR(ret);
6911 if (!fs_devices->seeding) {
6912 close_fs_devices(fs_devices);
6913 free_fs_devices(fs_devices);
6914 fs_devices = ERR_PTR(-EINVAL);
6918 fs_devices->seed = fs_info->fs_devices->seed;
6919 fs_info->fs_devices->seed = fs_devices;
6924 static int read_one_dev(struct btrfs_fs_info *fs_info,
6925 struct extent_buffer *leaf,
6926 struct btrfs_dev_item *dev_item)
6928 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6929 struct btrfs_device *device;
6932 u8 fs_uuid[BTRFS_FSID_SIZE];
6933 u8 dev_uuid[BTRFS_UUID_SIZE];
6935 devid = btrfs_device_id(leaf, dev_item);
6936 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6938 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6941 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6942 fs_devices = open_seed_devices(fs_info, fs_uuid);
6943 if (IS_ERR(fs_devices))
6944 return PTR_ERR(fs_devices);
6947 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6950 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6951 btrfs_report_missing_device(fs_info, devid,
6956 device = add_missing_dev(fs_devices, devid, dev_uuid);
6957 if (IS_ERR(device)) {
6959 "failed to add missing dev %llu: %ld",
6960 devid, PTR_ERR(device));
6961 return PTR_ERR(device);
6963 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6965 if (!device->bdev) {
6966 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6967 btrfs_report_missing_device(fs_info,
6968 devid, dev_uuid, true);
6971 btrfs_report_missing_device(fs_info, devid,
6975 if (!device->bdev &&
6976 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6978 * this happens when a device that was properly setup
6979 * in the device info lists suddenly goes bad.
6980 * device->bdev is NULL, and so we have to set
6981 * device->missing to one here
6983 device->fs_devices->missing_devices++;
6984 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6987 /* Move the device to its own fs_devices */
6988 if (device->fs_devices != fs_devices) {
6989 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6990 &device->dev_state));
6992 list_move(&device->dev_list, &fs_devices->devices);
6993 device->fs_devices->num_devices--;
6994 fs_devices->num_devices++;
6996 device->fs_devices->missing_devices--;
6997 fs_devices->missing_devices++;
6999 device->fs_devices = fs_devices;
7003 if (device->fs_devices != fs_info->fs_devices) {
7004 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7005 if (device->generation !=
7006 btrfs_device_generation(leaf, dev_item))
7010 fill_device_from_item(leaf, dev_item, device);
7011 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7012 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7013 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7014 device->fs_devices->total_rw_bytes += device->total_bytes;
7015 atomic64_add(device->total_bytes - device->bytes_used,
7016 &fs_info->free_chunk_space);
7022 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7024 struct btrfs_root *root = fs_info->tree_root;
7025 struct btrfs_super_block *super_copy = fs_info->super_copy;
7026 struct extent_buffer *sb;
7027 struct btrfs_disk_key *disk_key;
7028 struct btrfs_chunk *chunk;
7030 unsigned long sb_array_offset;
7037 struct btrfs_key key;
7039 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7041 * This will create extent buffer of nodesize, superblock size is
7042 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7043 * overallocate but we can keep it as-is, only the first page is used.
7045 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
7048 set_extent_buffer_uptodate(sb);
7049 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
7051 * The sb extent buffer is artificial and just used to read the system array.
7052 * set_extent_buffer_uptodate() call does not properly mark all it's
7053 * pages up-to-date when the page is larger: extent does not cover the
7054 * whole page and consequently check_page_uptodate does not find all
7055 * the page's extents up-to-date (the hole beyond sb),
7056 * write_extent_buffer then triggers a WARN_ON.
7058 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7059 * but sb spans only this function. Add an explicit SetPageUptodate call
7060 * to silence the warning eg. on PowerPC 64.
7062 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
7063 SetPageUptodate(sb->pages[0]);
7065 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7066 array_size = btrfs_super_sys_array_size(super_copy);
7068 array_ptr = super_copy->sys_chunk_array;
7069 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7072 while (cur_offset < array_size) {
7073 disk_key = (struct btrfs_disk_key *)array_ptr;
7074 len = sizeof(*disk_key);
7075 if (cur_offset + len > array_size)
7076 goto out_short_read;
7078 btrfs_disk_key_to_cpu(&key, disk_key);
7081 sb_array_offset += len;
7084 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
7085 chunk = (struct btrfs_chunk *)sb_array_offset;
7087 * At least one btrfs_chunk with one stripe must be
7088 * present, exact stripe count check comes afterwards
7090 len = btrfs_chunk_item_size(1);
7091 if (cur_offset + len > array_size)
7092 goto out_short_read;
7094 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7097 "invalid number of stripes %u in sys_array at offset %u",
7098 num_stripes, cur_offset);
7103 type = btrfs_chunk_type(sb, chunk);
7104 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7106 "invalid chunk type %llu in sys_array at offset %u",
7112 len = btrfs_chunk_item_size(num_stripes);
7113 if (cur_offset + len > array_size)
7114 goto out_short_read;
7116 ret = read_one_chunk(fs_info, &key, sb, chunk);
7121 "unexpected item type %u in sys_array at offset %u",
7122 (u32)key.type, cur_offset);
7127 sb_array_offset += len;
7130 clear_extent_buffer_uptodate(sb);
7131 free_extent_buffer_stale(sb);
7135 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7137 clear_extent_buffer_uptodate(sb);
7138 free_extent_buffer_stale(sb);
7143 * Check if all chunks in the fs are OK for read-write degraded mount
7145 * If the @failing_dev is specified, it's accounted as missing.
7147 * Return true if all chunks meet the minimal RW mount requirements.
7148 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7150 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7151 struct btrfs_device *failing_dev)
7153 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
7154 struct extent_map *em;
7158 read_lock(&map_tree->map_tree.lock);
7159 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
7160 read_unlock(&map_tree->map_tree.lock);
7161 /* No chunk at all? Return false anyway */
7167 struct map_lookup *map;
7172 map = em->map_lookup;
7174 btrfs_get_num_tolerated_disk_barrier_failures(
7176 for (i = 0; i < map->num_stripes; i++) {
7177 struct btrfs_device *dev = map->stripes[i].dev;
7179 if (!dev || !dev->bdev ||
7180 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7181 dev->last_flush_error)
7183 else if (failing_dev && failing_dev == dev)
7186 if (missing > max_tolerated) {
7189 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7190 em->start, missing, max_tolerated);
7191 free_extent_map(em);
7195 next_start = extent_map_end(em);
7196 free_extent_map(em);
7198 read_lock(&map_tree->map_tree.lock);
7199 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
7200 (u64)(-1) - next_start);
7201 read_unlock(&map_tree->map_tree.lock);
7207 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7209 struct btrfs_root *root = fs_info->chunk_root;
7210 struct btrfs_path *path;
7211 struct extent_buffer *leaf;
7212 struct btrfs_key key;
7213 struct btrfs_key found_key;
7218 path = btrfs_alloc_path();
7223 * uuid_mutex is needed only if we are mounting a sprout FS
7224 * otherwise we don't need it.
7226 mutex_lock(&uuid_mutex);
7227 mutex_lock(&fs_info->chunk_mutex);
7230 * Read all device items, and then all the chunk items. All
7231 * device items are found before any chunk item (their object id
7232 * is smaller than the lowest possible object id for a chunk
7233 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7235 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7238 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7242 leaf = path->nodes[0];
7243 slot = path->slots[0];
7244 if (slot >= btrfs_header_nritems(leaf)) {
7245 ret = btrfs_next_leaf(root, path);
7252 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7253 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7254 struct btrfs_dev_item *dev_item;
7255 dev_item = btrfs_item_ptr(leaf, slot,
7256 struct btrfs_dev_item);
7257 ret = read_one_dev(fs_info, leaf, dev_item);
7261 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7262 struct btrfs_chunk *chunk;
7263 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7264 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
7272 * After loading chunk tree, we've got all device information,
7273 * do another round of validation checks.
7275 if (total_dev != fs_info->fs_devices->total_devices) {
7277 "super_num_devices %llu mismatch with num_devices %llu found here",
7278 btrfs_super_num_devices(fs_info->super_copy),
7283 if (btrfs_super_total_bytes(fs_info->super_copy) <
7284 fs_info->fs_devices->total_rw_bytes) {
7286 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7287 btrfs_super_total_bytes(fs_info->super_copy),
7288 fs_info->fs_devices->total_rw_bytes);
7294 mutex_unlock(&fs_info->chunk_mutex);
7295 mutex_unlock(&uuid_mutex);
7297 btrfs_free_path(path);
7301 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7303 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7304 struct btrfs_device *device;
7306 while (fs_devices) {
7307 mutex_lock(&fs_devices->device_list_mutex);
7308 list_for_each_entry(device, &fs_devices->devices, dev_list)
7309 device->fs_info = fs_info;
7310 mutex_unlock(&fs_devices->device_list_mutex);
7312 fs_devices = fs_devices->seed;
7316 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7320 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7321 btrfs_dev_stat_reset(dev, i);
7324 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7326 struct btrfs_key key;
7327 struct btrfs_key found_key;
7328 struct btrfs_root *dev_root = fs_info->dev_root;
7329 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7330 struct extent_buffer *eb;
7333 struct btrfs_device *device;
7334 struct btrfs_path *path = NULL;
7337 path = btrfs_alloc_path();
7343 mutex_lock(&fs_devices->device_list_mutex);
7344 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7346 struct btrfs_dev_stats_item *ptr;
7348 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7349 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7350 key.offset = device->devid;
7351 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7353 __btrfs_reset_dev_stats(device);
7354 device->dev_stats_valid = 1;
7355 btrfs_release_path(path);
7358 slot = path->slots[0];
7359 eb = path->nodes[0];
7360 btrfs_item_key_to_cpu(eb, &found_key, slot);
7361 item_size = btrfs_item_size_nr(eb, slot);
7363 ptr = btrfs_item_ptr(eb, slot,
7364 struct btrfs_dev_stats_item);
7366 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7367 if (item_size >= (1 + i) * sizeof(__le64))
7368 btrfs_dev_stat_set(device, i,
7369 btrfs_dev_stats_value(eb, ptr, i));
7371 btrfs_dev_stat_reset(device, i);
7374 device->dev_stats_valid = 1;
7375 btrfs_dev_stat_print_on_load(device);
7376 btrfs_release_path(path);
7378 mutex_unlock(&fs_devices->device_list_mutex);
7381 btrfs_free_path(path);
7382 return ret < 0 ? ret : 0;
7385 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7386 struct btrfs_device *device)
7388 struct btrfs_fs_info *fs_info = trans->fs_info;
7389 struct btrfs_root *dev_root = fs_info->dev_root;
7390 struct btrfs_path *path;
7391 struct btrfs_key key;
7392 struct extent_buffer *eb;
7393 struct btrfs_dev_stats_item *ptr;
7397 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7398 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7399 key.offset = device->devid;
7401 path = btrfs_alloc_path();
7404 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7406 btrfs_warn_in_rcu(fs_info,
7407 "error %d while searching for dev_stats item for device %s",
7408 ret, rcu_str_deref(device->name));
7413 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7414 /* need to delete old one and insert a new one */
7415 ret = btrfs_del_item(trans, dev_root, path);
7417 btrfs_warn_in_rcu(fs_info,
7418 "delete too small dev_stats item for device %s failed %d",
7419 rcu_str_deref(device->name), ret);
7426 /* need to insert a new item */
7427 btrfs_release_path(path);
7428 ret = btrfs_insert_empty_item(trans, dev_root, path,
7429 &key, sizeof(*ptr));
7431 btrfs_warn_in_rcu(fs_info,
7432 "insert dev_stats item for device %s failed %d",
7433 rcu_str_deref(device->name), ret);
7438 eb = path->nodes[0];
7439 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7440 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7441 btrfs_set_dev_stats_value(eb, ptr, i,
7442 btrfs_dev_stat_read(device, i));
7443 btrfs_mark_buffer_dirty(eb);
7446 btrfs_free_path(path);
7451 * called from commit_transaction. Writes all changed device stats to disk.
7453 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7454 struct btrfs_fs_info *fs_info)
7456 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7457 struct btrfs_device *device;
7461 mutex_lock(&fs_devices->device_list_mutex);
7462 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7463 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7464 if (!device->dev_stats_valid || stats_cnt == 0)
7469 * There is a LOAD-LOAD control dependency between the value of
7470 * dev_stats_ccnt and updating the on-disk values which requires
7471 * reading the in-memory counters. Such control dependencies
7472 * require explicit read memory barriers.
7474 * This memory barriers pairs with smp_mb__before_atomic in
7475 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7476 * barrier implied by atomic_xchg in
7477 * btrfs_dev_stats_read_and_reset
7481 ret = update_dev_stat_item(trans, device);
7483 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7485 mutex_unlock(&fs_devices->device_list_mutex);
7490 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7492 btrfs_dev_stat_inc(dev, index);
7493 btrfs_dev_stat_print_on_error(dev);
7496 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7498 if (!dev->dev_stats_valid)
7500 btrfs_err_rl_in_rcu(dev->fs_info,
7501 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7502 rcu_str_deref(dev->name),
7503 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7504 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7505 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7506 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7507 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7510 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7514 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7515 if (btrfs_dev_stat_read(dev, i) != 0)
7517 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7518 return; /* all values == 0, suppress message */
7520 btrfs_info_in_rcu(dev->fs_info,
7521 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7522 rcu_str_deref(dev->name),
7523 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7524 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7525 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7526 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7527 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7530 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7531 struct btrfs_ioctl_get_dev_stats *stats)
7533 struct btrfs_device *dev;
7534 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7537 mutex_lock(&fs_devices->device_list_mutex);
7538 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7540 mutex_unlock(&fs_devices->device_list_mutex);
7543 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7545 } else if (!dev->dev_stats_valid) {
7546 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7548 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7549 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7550 if (stats->nr_items > i)
7552 btrfs_dev_stat_read_and_reset(dev, i);
7554 btrfs_dev_stat_reset(dev, i);
7557 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7558 if (stats->nr_items > i)
7559 stats->values[i] = btrfs_dev_stat_read(dev, i);
7561 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7562 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7566 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7568 struct buffer_head *bh;
7569 struct btrfs_super_block *disk_super;
7575 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7578 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7581 disk_super = (struct btrfs_super_block *)bh->b_data;
7583 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7584 set_buffer_dirty(bh);
7585 sync_dirty_buffer(bh);
7589 /* Notify udev that device has changed */
7590 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7592 /* Update ctime/mtime for device path for libblkid */
7593 update_dev_time(device_path);
7597 * Update the size and bytes used for each device where it changed. This is
7598 * delayed since we would otherwise get errors while writing out the
7601 * Must be invoked during transaction commit.
7603 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7605 struct btrfs_device *curr, *next;
7607 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7609 if (list_empty(&trans->dev_update_list))
7613 * We don't need the device_list_mutex here. This list is owned by the
7614 * transaction and the transaction must complete before the device is
7617 mutex_lock(&trans->fs_info->chunk_mutex);
7618 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7620 list_del_init(&curr->post_commit_list);
7621 curr->commit_total_bytes = curr->disk_total_bytes;
7622 curr->commit_bytes_used = curr->bytes_used;
7624 mutex_unlock(&trans->fs_info->chunk_mutex);
7627 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7629 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7630 while (fs_devices) {
7631 fs_devices->fs_info = fs_info;
7632 fs_devices = fs_devices->seed;
7636 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7638 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7639 while (fs_devices) {
7640 fs_devices->fs_info = NULL;
7641 fs_devices = fs_devices->seed;
7646 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7648 int btrfs_bg_type_to_factor(u64 flags)
7650 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
7651 BTRFS_BLOCK_GROUP_RAID10))
7658 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7659 u64 chunk_offset, u64 devid,
7660 u64 physical_offset, u64 physical_len)
7662 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7663 struct extent_map *em;
7664 struct map_lookup *map;
7665 struct btrfs_device *dev;
7671 read_lock(&em_tree->lock);
7672 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7673 read_unlock(&em_tree->lock);
7677 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7678 physical_offset, devid);
7683 map = em->map_lookup;
7684 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7685 if (physical_len != stripe_len) {
7687 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7688 physical_offset, devid, em->start, physical_len,
7694 for (i = 0; i < map->num_stripes; i++) {
7695 if (map->stripes[i].dev->devid == devid &&
7696 map->stripes[i].physical == physical_offset) {
7698 if (map->verified_stripes >= map->num_stripes) {
7700 "too many dev extents for chunk %llu found",
7705 map->verified_stripes++;
7711 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7712 physical_offset, devid);
7716 /* Make sure no dev extent is beyond device bondary */
7717 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7719 btrfs_err(fs_info, "failed to find devid %llu", devid);
7724 /* It's possible this device is a dummy for seed device */
7725 if (dev->disk_total_bytes == 0) {
7726 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7729 btrfs_err(fs_info, "failed to find seed devid %llu",
7736 if (physical_offset + physical_len > dev->disk_total_bytes) {
7738 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7739 devid, physical_offset, physical_len,
7740 dev->disk_total_bytes);
7745 free_extent_map(em);
7749 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7751 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7752 struct extent_map *em;
7753 struct rb_node *node;
7756 read_lock(&em_tree->lock);
7757 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7758 em = rb_entry(node, struct extent_map, rb_node);
7759 if (em->map_lookup->num_stripes !=
7760 em->map_lookup->verified_stripes) {
7762 "chunk %llu has missing dev extent, have %d expect %d",
7763 em->start, em->map_lookup->verified_stripes,
7764 em->map_lookup->num_stripes);
7770 read_unlock(&em_tree->lock);
7775 * Ensure that all dev extents are mapped to correct chunk, otherwise
7776 * later chunk allocation/free would cause unexpected behavior.
7778 * NOTE: This will iterate through the whole device tree, which should be of
7779 * the same size level as the chunk tree. This slightly increases mount time.
7781 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7783 struct btrfs_path *path;
7784 struct btrfs_root *root = fs_info->dev_root;
7785 struct btrfs_key key;
7787 u64 prev_dev_ext_end = 0;
7791 key.type = BTRFS_DEV_EXTENT_KEY;
7794 path = btrfs_alloc_path();
7798 path->reada = READA_FORWARD;
7799 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7803 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7804 ret = btrfs_next_item(root, path);
7807 /* No dev extents at all? Not good */
7814 struct extent_buffer *leaf = path->nodes[0];
7815 struct btrfs_dev_extent *dext;
7816 int slot = path->slots[0];
7818 u64 physical_offset;
7822 btrfs_item_key_to_cpu(leaf, &key, slot);
7823 if (key.type != BTRFS_DEV_EXTENT_KEY)
7825 devid = key.objectid;
7826 physical_offset = key.offset;
7828 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7829 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7830 physical_len = btrfs_dev_extent_length(leaf, dext);
7832 /* Check if this dev extent overlaps with the previous one */
7833 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7835 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7836 devid, physical_offset, prev_dev_ext_end);
7841 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7842 physical_offset, physical_len);
7846 prev_dev_ext_end = physical_offset + physical_len;
7848 ret = btrfs_next_item(root, path);
7857 /* Ensure all chunks have corresponding dev extents */
7858 ret = verify_chunk_dev_extent_mapping(fs_info);
7860 btrfs_free_path(path);
7865 * Check whether the given block group or device is pinned by any inode being
7866 * used as a swapfile.
7868 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7870 struct btrfs_swapfile_pin *sp;
7871 struct rb_node *node;
7873 spin_lock(&fs_info->swapfile_pins_lock);
7874 node = fs_info->swapfile_pins.rb_node;
7876 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7878 node = node->rb_left;
7879 else if (ptr > sp->ptr)
7880 node = node->rb_right;
7884 spin_unlock(&fs_info->swapfile_pins_lock);
7885 return node != NULL;