1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
8 #include <linux/slab.h>
9 #include <linux/buffer_head.h>
10 #include <linux/blkdev.h>
11 #include <linux/ratelimit.h>
12 #include <linux/kthread.h>
13 #include <linux/raid/pq.h>
14 #include <linux/semaphore.h>
15 #include <linux/uuid.h>
16 #include <linux/list_sort.h>
19 #include "extent_map.h"
21 #include "transaction.h"
22 #include "print-tree.h"
25 #include "async-thread.h"
26 #include "check-integrity.h"
27 #include "rcu-string.h"
28 #include "dev-replace.h"
30 #include "tree-checker.h"
31 #include "space-info.h"
32 #include "block-group.h"
34 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
35 [BTRFS_RAID_RAID10] = {
38 .devs_max = 0, /* 0 == as many as possible */
40 .tolerated_failures = 1,
44 .raid_name = "raid10",
45 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
46 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
48 [BTRFS_RAID_RAID1] = {
53 .tolerated_failures = 1,
58 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
59 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
66 .tolerated_failures = 0,
71 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
74 [BTRFS_RAID_RAID0] = {
79 .tolerated_failures = 0,
84 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
87 [BTRFS_RAID_SINGLE] = {
92 .tolerated_failures = 0,
96 .raid_name = "single",
100 [BTRFS_RAID_RAID5] = {
105 .tolerated_failures = 1,
109 .raid_name = "raid5",
110 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
111 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
113 [BTRFS_RAID_RAID6] = {
118 .tolerated_failures = 2,
122 .raid_name = "raid6",
123 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
124 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
128 const char *btrfs_bg_type_to_raid_name(u64 flags)
130 const int index = btrfs_bg_flags_to_raid_index(flags);
132 if (index >= BTRFS_NR_RAID_TYPES)
135 return btrfs_raid_array[index].raid_name;
139 * Fill @buf with textual description of @bg_flags, no more than @size_buf
140 * bytes including terminating null byte.
142 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
147 u64 flags = bg_flags;
148 u32 size_bp = size_buf;
155 #define DESCRIBE_FLAG(flag, desc) \
157 if (flags & (flag)) { \
158 ret = snprintf(bp, size_bp, "%s|", (desc)); \
159 if (ret < 0 || ret >= size_bp) \
167 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
168 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
169 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
171 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
172 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
173 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
174 btrfs_raid_array[i].raid_name);
178 ret = snprintf(bp, size_bp, "0x%llx|", flags);
182 if (size_bp < size_buf)
183 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
186 * The text is trimmed, it's up to the caller to provide sufficiently
192 static int init_first_rw_device(struct btrfs_trans_handle *trans);
193 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
194 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
195 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
196 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
197 enum btrfs_map_op op,
198 u64 logical, u64 *length,
199 struct btrfs_bio **bbio_ret,
200 int mirror_num, int need_raid_map);
206 * There are several mutexes that protect manipulation of devices and low-level
207 * structures like chunks but not block groups, extents or files
209 * uuid_mutex (global lock)
210 * ------------------------
211 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
212 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
213 * device) or requested by the device= mount option
215 * the mutex can be very coarse and can cover long-running operations
217 * protects: updates to fs_devices counters like missing devices, rw devices,
218 * seeding, structure cloning, opening/closing devices at mount/umount time
220 * global::fs_devs - add, remove, updates to the global list
222 * does not protect: manipulation of the fs_devices::devices list!
224 * btrfs_device::name - renames (write side), read is RCU
226 * fs_devices::device_list_mutex (per-fs, with RCU)
227 * ------------------------------------------------
228 * protects updates to fs_devices::devices, ie. adding and deleting
230 * simple list traversal with read-only actions can be done with RCU protection
232 * may be used to exclude some operations from running concurrently without any
233 * modifications to the list (see write_all_supers)
237 * protects balance structures (status, state) and context accessed from
238 * several places (internally, ioctl)
242 * protects chunks, adding or removing during allocation, trim or when a new
243 * device is added/removed. Additionally it also protects post_commit_list of
244 * individual devices, since they can be added to the transaction's
245 * post_commit_list only with chunk_mutex held.
249 * a big lock that is held by the cleaner thread and prevents running subvolume
250 * cleaning together with relocation or delayed iputs
263 * Exclusive operations, BTRFS_FS_EXCL_OP
264 * ======================================
266 * Maintains the exclusivity of the following operations that apply to the
267 * whole filesystem and cannot run in parallel.
272 * - Device replace (*)
275 * The device operations (as above) can be in one of the following states:
281 * Only device operations marked with (*) can go into the Paused state for the
284 * - ioctl (only Balance can be Paused through ioctl)
285 * - filesystem remounted as read-only
286 * - filesystem unmounted and mounted as read-only
287 * - system power-cycle and filesystem mounted as read-only
288 * - filesystem or device errors leading to forced read-only
290 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
291 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
292 * A device operation in Paused or Running state can be canceled or resumed
293 * either by ioctl (Balance only) or when remounted as read-write.
294 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
298 DEFINE_MUTEX(uuid_mutex);
299 static LIST_HEAD(fs_uuids);
300 struct list_head *btrfs_get_fs_uuids(void)
306 * alloc_fs_devices - allocate struct btrfs_fs_devices
307 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
308 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
310 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
311 * The returned struct is not linked onto any lists and can be destroyed with
312 * kfree() right away.
314 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
315 const u8 *metadata_fsid)
317 struct btrfs_fs_devices *fs_devs;
319 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
321 return ERR_PTR(-ENOMEM);
323 mutex_init(&fs_devs->device_list_mutex);
325 INIT_LIST_HEAD(&fs_devs->devices);
326 INIT_LIST_HEAD(&fs_devs->alloc_list);
327 INIT_LIST_HEAD(&fs_devs->fs_list);
329 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
332 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
334 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
339 void btrfs_free_device(struct btrfs_device *device)
341 WARN_ON(!list_empty(&device->post_commit_list));
342 rcu_string_free(device->name);
343 extent_io_tree_release(&device->alloc_state);
344 bio_put(device->flush_bio);
348 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
350 struct btrfs_device *device;
351 WARN_ON(fs_devices->opened);
352 while (!list_empty(&fs_devices->devices)) {
353 device = list_entry(fs_devices->devices.next,
354 struct btrfs_device, dev_list);
355 list_del(&device->dev_list);
356 btrfs_free_device(device);
361 void __exit btrfs_cleanup_fs_uuids(void)
363 struct btrfs_fs_devices *fs_devices;
365 while (!list_empty(&fs_uuids)) {
366 fs_devices = list_entry(fs_uuids.next,
367 struct btrfs_fs_devices, fs_list);
368 list_del(&fs_devices->fs_list);
369 free_fs_devices(fs_devices);
374 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
375 * Returned struct is not linked onto any lists and must be destroyed using
378 static struct btrfs_device *__alloc_device(void)
380 struct btrfs_device *dev;
382 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
384 return ERR_PTR(-ENOMEM);
387 * Preallocate a bio that's always going to be used for flushing device
388 * barriers and matches the device lifespan
390 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
391 if (!dev->flush_bio) {
393 return ERR_PTR(-ENOMEM);
396 INIT_LIST_HEAD(&dev->dev_list);
397 INIT_LIST_HEAD(&dev->dev_alloc_list);
398 INIT_LIST_HEAD(&dev->post_commit_list);
400 spin_lock_init(&dev->io_lock);
402 atomic_set(&dev->reada_in_flight, 0);
403 atomic_set(&dev->dev_stats_ccnt, 0);
404 btrfs_device_data_ordered_init(dev);
405 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
406 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
407 extent_io_tree_init(NULL, &dev->alloc_state, 0, NULL);
412 static noinline struct btrfs_fs_devices *find_fsid(
413 const u8 *fsid, const u8 *metadata_fsid)
415 struct btrfs_fs_devices *fs_devices;
421 * Handle scanned device having completed its fsid change but
422 * belonging to a fs_devices that was created by first scanning
423 * a device which didn't have its fsid/metadata_uuid changed
424 * at all and the CHANGING_FSID_V2 flag set.
426 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
427 if (fs_devices->fsid_change &&
428 memcmp(metadata_fsid, fs_devices->fsid,
429 BTRFS_FSID_SIZE) == 0 &&
430 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
431 BTRFS_FSID_SIZE) == 0) {
436 * Handle scanned device having completed its fsid change but
437 * belonging to a fs_devices that was created by a device that
438 * has an outdated pair of fsid/metadata_uuid and
439 * CHANGING_FSID_V2 flag set.
441 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
442 if (fs_devices->fsid_change &&
443 memcmp(fs_devices->metadata_uuid,
444 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
445 memcmp(metadata_fsid, fs_devices->metadata_uuid,
446 BTRFS_FSID_SIZE) == 0) {
452 /* Handle non-split brain cases */
453 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
455 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
456 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
457 BTRFS_FSID_SIZE) == 0)
460 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
468 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
469 int flush, struct block_device **bdev,
470 struct buffer_head **bh)
474 *bdev = blkdev_get_by_path(device_path, flags, holder);
477 ret = PTR_ERR(*bdev);
482 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
483 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
485 blkdev_put(*bdev, flags);
488 invalidate_bdev(*bdev);
489 *bh = btrfs_read_dev_super(*bdev);
492 blkdev_put(*bdev, flags);
504 static void requeue_list(struct btrfs_pending_bios *pending_bios,
505 struct bio *head, struct bio *tail)
508 struct bio *old_head;
510 old_head = pending_bios->head;
511 pending_bios->head = head;
512 if (pending_bios->tail)
513 tail->bi_next = old_head;
515 pending_bios->tail = tail;
519 * we try to collect pending bios for a device so we don't get a large
520 * number of procs sending bios down to the same device. This greatly
521 * improves the schedulers ability to collect and merge the bios.
523 * But, it also turns into a long list of bios to process and that is sure
524 * to eventually make the worker thread block. The solution here is to
525 * make some progress and then put this work struct back at the end of
526 * the list if the block device is congested. This way, multiple devices
527 * can make progress from a single worker thread.
529 static noinline void run_scheduled_bios(struct btrfs_device *device)
531 struct btrfs_fs_info *fs_info = device->fs_info;
533 struct backing_dev_info *bdi;
534 struct btrfs_pending_bios *pending_bios;
538 unsigned long num_run;
539 unsigned long batch_run = 0;
540 unsigned long last_waited = 0;
542 int sync_pending = 0;
543 struct blk_plug plug;
546 * this function runs all the bios we've collected for
547 * a particular device. We don't want to wander off to
548 * another device without first sending all of these down.
549 * So, setup a plug here and finish it off before we return
551 blk_start_plug(&plug);
553 bdi = device->bdev->bd_bdi;
556 spin_lock(&device->io_lock);
561 /* take all the bios off the list at once and process them
562 * later on (without the lock held). But, remember the
563 * tail and other pointers so the bios can be properly reinserted
564 * into the list if we hit congestion
566 if (!force_reg && device->pending_sync_bios.head) {
567 pending_bios = &device->pending_sync_bios;
570 pending_bios = &device->pending_bios;
574 pending = pending_bios->head;
575 tail = pending_bios->tail;
576 WARN_ON(pending && !tail);
579 * if pending was null this time around, no bios need processing
580 * at all and we can stop. Otherwise it'll loop back up again
581 * and do an additional check so no bios are missed.
583 * device->running_pending is used to synchronize with the
586 if (device->pending_sync_bios.head == NULL &&
587 device->pending_bios.head == NULL) {
589 device->running_pending = 0;
592 device->running_pending = 1;
595 pending_bios->head = NULL;
596 pending_bios->tail = NULL;
598 spin_unlock(&device->io_lock);
603 /* we want to work on both lists, but do more bios on the
604 * sync list than the regular list
607 pending_bios != &device->pending_sync_bios &&
608 device->pending_sync_bios.head) ||
609 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
610 device->pending_bios.head)) {
611 spin_lock(&device->io_lock);
612 requeue_list(pending_bios, pending, tail);
617 pending = pending->bi_next;
620 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
623 * if we're doing the sync list, record that our
624 * plug has some sync requests on it
626 * If we're doing the regular list and there are
627 * sync requests sitting around, unplug before
630 if (pending_bios == &device->pending_sync_bios) {
632 } else if (sync_pending) {
633 blk_finish_plug(&plug);
634 blk_start_plug(&plug);
638 btrfsic_submit_bio(cur);
645 * we made progress, there is more work to do and the bdi
646 * is now congested. Back off and let other work structs
649 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
650 fs_info->fs_devices->open_devices > 1) {
651 struct io_context *ioc;
653 ioc = current->io_context;
656 * the main goal here is that we don't want to
657 * block if we're going to be able to submit
658 * more requests without blocking.
660 * This code does two great things, it pokes into
661 * the elevator code from a filesystem _and_
662 * it makes assumptions about how batching works.
664 if (ioc && ioc->nr_batch_requests > 0 &&
665 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
667 ioc->last_waited == last_waited)) {
669 * we want to go through our batch of
670 * requests and stop. So, we copy out
671 * the ioc->last_waited time and test
672 * against it before looping
674 last_waited = ioc->last_waited;
678 spin_lock(&device->io_lock);
679 requeue_list(pending_bios, pending, tail);
680 device->running_pending = 1;
682 spin_unlock(&device->io_lock);
683 btrfs_queue_work(fs_info->submit_workers,
693 spin_lock(&device->io_lock);
694 if (device->pending_bios.head || device->pending_sync_bios.head)
696 spin_unlock(&device->io_lock);
699 blk_finish_plug(&plug);
702 static void pending_bios_fn(struct btrfs_work *work)
704 struct btrfs_device *device;
706 device = container_of(work, struct btrfs_device, work);
707 run_scheduled_bios(device);
710 static bool device_path_matched(const char *path, struct btrfs_device *device)
715 found = strcmp(rcu_str_deref(device->name), path);
722 * Search and remove all stale (devices which are not mounted) devices.
723 * When both inputs are NULL, it will search and release all stale devices.
724 * path: Optional. When provided will it release all unmounted devices
725 * matching this path only.
726 * skip_dev: Optional. Will skip this device when searching for the stale
728 * Return: 0 for success or if @path is NULL.
729 * -EBUSY if @path is a mounted device.
730 * -ENOENT if @path does not match any device in the list.
732 static int btrfs_free_stale_devices(const char *path,
733 struct btrfs_device *skip_device)
735 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
736 struct btrfs_device *device, *tmp_device;
742 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
744 mutex_lock(&fs_devices->device_list_mutex);
745 list_for_each_entry_safe(device, tmp_device,
746 &fs_devices->devices, dev_list) {
747 if (skip_device && skip_device == device)
749 if (path && !device->name)
751 if (path && !device_path_matched(path, device))
753 if (fs_devices->opened) {
754 /* for an already deleted device return 0 */
755 if (path && ret != 0)
760 /* delete the stale device */
761 fs_devices->num_devices--;
762 list_del(&device->dev_list);
763 btrfs_free_device(device);
766 if (fs_devices->num_devices == 0)
769 mutex_unlock(&fs_devices->device_list_mutex);
771 if (fs_devices->num_devices == 0) {
772 btrfs_sysfs_remove_fsid(fs_devices);
773 list_del(&fs_devices->fs_list);
774 free_fs_devices(fs_devices);
781 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
782 struct btrfs_device *device, fmode_t flags,
785 struct request_queue *q;
786 struct block_device *bdev;
787 struct buffer_head *bh;
788 struct btrfs_super_block *disk_super;
797 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
802 disk_super = (struct btrfs_super_block *)bh->b_data;
803 devid = btrfs_stack_device_id(&disk_super->dev_item);
804 if (devid != device->devid)
807 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
810 device->generation = btrfs_super_generation(disk_super);
812 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
813 if (btrfs_super_incompat_flags(disk_super) &
814 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
816 "BTRFS: Invalid seeding and uuid-changed device detected\n");
820 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
821 fs_devices->seeding = 1;
823 if (bdev_read_only(bdev))
824 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
826 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
829 q = bdev_get_queue(bdev);
830 if (!blk_queue_nonrot(q))
831 fs_devices->rotating = 1;
834 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
835 device->mode = flags;
837 fs_devices->open_devices++;
838 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
839 device->devid != BTRFS_DEV_REPLACE_DEVID) {
840 fs_devices->rw_devices++;
841 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
849 blkdev_put(bdev, flags);
855 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
856 * being created with a disk that has already completed its fsid change.
858 static struct btrfs_fs_devices *find_fsid_inprogress(
859 struct btrfs_super_block *disk_super)
861 struct btrfs_fs_devices *fs_devices;
863 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
864 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
865 BTRFS_FSID_SIZE) != 0 &&
866 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
867 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
876 static struct btrfs_fs_devices *find_fsid_changed(
877 struct btrfs_super_block *disk_super)
879 struct btrfs_fs_devices *fs_devices;
882 * Handles the case where scanned device is part of an fs that had
883 * multiple successful changes of FSID but curently device didn't
884 * observe it. Meaning our fsid will be different than theirs. We need
885 * to handle two subcases :
886 * 1 - The fs still continues to have different METADATA/FSID uuids.
887 * 2 - The fs is switched back to its original FSID (METADATA/FSID
890 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
892 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
893 BTRFS_FSID_SIZE) != 0 &&
894 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
895 BTRFS_FSID_SIZE) == 0 &&
896 memcmp(fs_devices->fsid, disk_super->fsid,
897 BTRFS_FSID_SIZE) != 0)
900 /* Unchanged UUIDs */
901 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
902 BTRFS_FSID_SIZE) == 0 &&
903 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
904 BTRFS_FSID_SIZE) == 0)
911 static struct btrfs_fs_devices *find_fsid_reverted_metadata(
912 struct btrfs_super_block *disk_super)
914 struct btrfs_fs_devices *fs_devices;
917 * Handle the case where the scanned device is part of an fs whose last
918 * metadata UUID change reverted it to the original FSID. At the same
919 * time * fs_devices was first created by another constitutent device
920 * which didn't fully observe the operation. This results in an
921 * btrfs_fs_devices created with metadata/fsid different AND
922 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
923 * fs_devices equal to the FSID of the disk.
925 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
926 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
927 BTRFS_FSID_SIZE) != 0 &&
928 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
929 BTRFS_FSID_SIZE) == 0 &&
930 fs_devices->fsid_change)
937 * Add new device to list of registered devices
940 * device pointer which was just added or updated when successful
941 * error pointer when failed
943 static noinline struct btrfs_device *device_list_add(const char *path,
944 struct btrfs_super_block *disk_super,
945 bool *new_device_added)
947 struct btrfs_device *device;
948 struct btrfs_fs_devices *fs_devices = NULL;
949 struct rcu_string *name;
950 u64 found_transid = btrfs_super_generation(disk_super);
951 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
952 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
953 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
954 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
955 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
957 if (fsid_change_in_progress) {
958 if (!has_metadata_uuid) {
960 * When we have an image which has CHANGING_FSID_V2 set
961 * it might belong to either a filesystem which has
962 * disks with completed fsid change or it might belong
963 * to fs with no UUID changes in effect, handle both.
965 fs_devices = find_fsid_inprogress(disk_super);
967 fs_devices = find_fsid(disk_super->fsid, NULL);
969 fs_devices = find_fsid_changed(disk_super);
971 } else if (has_metadata_uuid) {
972 fs_devices = find_fsid(disk_super->fsid,
973 disk_super->metadata_uuid);
975 fs_devices = find_fsid_reverted_metadata(disk_super);
977 fs_devices = find_fsid(disk_super->fsid, NULL);
982 if (has_metadata_uuid)
983 fs_devices = alloc_fs_devices(disk_super->fsid,
984 disk_super->metadata_uuid);
986 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
988 if (IS_ERR(fs_devices))
989 return ERR_CAST(fs_devices);
991 fs_devices->fsid_change = fsid_change_in_progress;
993 mutex_lock(&fs_devices->device_list_mutex);
994 list_add(&fs_devices->fs_list, &fs_uuids);
998 mutex_lock(&fs_devices->device_list_mutex);
999 device = btrfs_find_device(fs_devices, devid,
1000 disk_super->dev_item.uuid, NULL, false);
1003 * If this disk has been pulled into an fs devices created by
1004 * a device which had the CHANGING_FSID_V2 flag then replace the
1005 * metadata_uuid/fsid values of the fs_devices.
1007 if (fs_devices->fsid_change &&
1008 found_transid > fs_devices->latest_generation) {
1009 memcpy(fs_devices->fsid, disk_super->fsid,
1012 if (has_metadata_uuid)
1013 memcpy(fs_devices->metadata_uuid,
1014 disk_super->metadata_uuid,
1017 memcpy(fs_devices->metadata_uuid,
1018 disk_super->fsid, BTRFS_FSID_SIZE);
1020 fs_devices->fsid_change = false;
1025 if (fs_devices->opened) {
1026 mutex_unlock(&fs_devices->device_list_mutex);
1027 return ERR_PTR(-EBUSY);
1030 device = btrfs_alloc_device(NULL, &devid,
1031 disk_super->dev_item.uuid);
1032 if (IS_ERR(device)) {
1033 mutex_unlock(&fs_devices->device_list_mutex);
1034 /* we can safely leave the fs_devices entry around */
1038 name = rcu_string_strdup(path, GFP_NOFS);
1040 btrfs_free_device(device);
1041 mutex_unlock(&fs_devices->device_list_mutex);
1042 return ERR_PTR(-ENOMEM);
1044 rcu_assign_pointer(device->name, name);
1046 list_add_rcu(&device->dev_list, &fs_devices->devices);
1047 fs_devices->num_devices++;
1049 device->fs_devices = fs_devices;
1050 *new_device_added = true;
1052 if (disk_super->label[0])
1053 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
1054 disk_super->label, devid, found_transid, path);
1056 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
1057 disk_super->fsid, devid, found_transid, path);
1059 } else if (!device->name || strcmp(device->name->str, path)) {
1061 * When FS is already mounted.
1062 * 1. If you are here and if the device->name is NULL that
1063 * means this device was missing at time of FS mount.
1064 * 2. If you are here and if the device->name is different
1065 * from 'path' that means either
1066 * a. The same device disappeared and reappeared with
1067 * different name. or
1068 * b. The missing-disk-which-was-replaced, has
1071 * We must allow 1 and 2a above. But 2b would be a spurious
1072 * and unintentional.
1074 * Further in case of 1 and 2a above, the disk at 'path'
1075 * would have missed some transaction when it was away and
1076 * in case of 2a the stale bdev has to be updated as well.
1077 * 2b must not be allowed at all time.
1081 * For now, we do allow update to btrfs_fs_device through the
1082 * btrfs dev scan cli after FS has been mounted. We're still
1083 * tracking a problem where systems fail mount by subvolume id
1084 * when we reject replacement on a mounted FS.
1086 if (!fs_devices->opened && found_transid < device->generation) {
1088 * That is if the FS is _not_ mounted and if you
1089 * are here, that means there is more than one
1090 * disk with same uuid and devid.We keep the one
1091 * with larger generation number or the last-in if
1092 * generation are equal.
1094 mutex_unlock(&fs_devices->device_list_mutex);
1095 return ERR_PTR(-EEXIST);
1099 * We are going to replace the device path for a given devid,
1100 * make sure it's the same device if the device is mounted
1103 struct block_device *path_bdev;
1105 path_bdev = lookup_bdev(path);
1106 if (IS_ERR(path_bdev)) {
1107 mutex_unlock(&fs_devices->device_list_mutex);
1108 return ERR_CAST(path_bdev);
1111 if (device->bdev != path_bdev) {
1113 mutex_unlock(&fs_devices->device_list_mutex);
1114 btrfs_warn_in_rcu(device->fs_info,
1115 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
1116 disk_super->fsid, devid,
1117 rcu_str_deref(device->name), path);
1118 return ERR_PTR(-EEXIST);
1121 btrfs_info_in_rcu(device->fs_info,
1122 "device fsid %pU devid %llu moved old:%s new:%s",
1123 disk_super->fsid, devid,
1124 rcu_str_deref(device->name), path);
1127 name = rcu_string_strdup(path, GFP_NOFS);
1129 mutex_unlock(&fs_devices->device_list_mutex);
1130 return ERR_PTR(-ENOMEM);
1132 rcu_string_free(device->name);
1133 rcu_assign_pointer(device->name, name);
1134 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1135 fs_devices->missing_devices--;
1136 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1141 * Unmount does not free the btrfs_device struct but would zero
1142 * generation along with most of the other members. So just update
1143 * it back. We need it to pick the disk with largest generation
1146 if (!fs_devices->opened) {
1147 device->generation = found_transid;
1148 fs_devices->latest_generation = max_t(u64, found_transid,
1149 fs_devices->latest_generation);
1152 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
1154 mutex_unlock(&fs_devices->device_list_mutex);
1158 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1160 struct btrfs_fs_devices *fs_devices;
1161 struct btrfs_device *device;
1162 struct btrfs_device *orig_dev;
1165 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1166 if (IS_ERR(fs_devices))
1169 mutex_lock(&orig->device_list_mutex);
1170 fs_devices->total_devices = orig->total_devices;
1172 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1173 struct rcu_string *name;
1175 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1177 if (IS_ERR(device)) {
1178 ret = PTR_ERR(device);
1183 * This is ok to do without rcu read locked because we hold the
1184 * uuid mutex so nothing we touch in here is going to disappear.
1186 if (orig_dev->name) {
1187 name = rcu_string_strdup(orig_dev->name->str,
1190 btrfs_free_device(device);
1194 rcu_assign_pointer(device->name, name);
1197 list_add(&device->dev_list, &fs_devices->devices);
1198 device->fs_devices = fs_devices;
1199 fs_devices->num_devices++;
1201 mutex_unlock(&orig->device_list_mutex);
1204 mutex_unlock(&orig->device_list_mutex);
1205 free_fs_devices(fs_devices);
1206 return ERR_PTR(ret);
1210 * After we have read the system tree and know devids belonging to
1211 * this filesystem, remove the device which does not belong there.
1213 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1215 struct btrfs_device *device, *next;
1216 struct btrfs_device *latest_dev = NULL;
1218 mutex_lock(&uuid_mutex);
1220 /* This is the initialized path, it is safe to release the devices. */
1221 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1222 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1223 &device->dev_state)) {
1224 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1225 &device->dev_state) &&
1227 device->generation > latest_dev->generation)) {
1228 latest_dev = device;
1233 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1235 * In the first step, keep the device which has
1236 * the correct fsid and the devid that is used
1237 * for the dev_replace procedure.
1238 * In the second step, the dev_replace state is
1239 * read from the device tree and it is known
1240 * whether the procedure is really active or
1241 * not, which means whether this device is
1242 * used or whether it should be removed.
1244 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1245 &device->dev_state)) {
1250 blkdev_put(device->bdev, device->mode);
1251 device->bdev = NULL;
1252 fs_devices->open_devices--;
1254 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1255 list_del_init(&device->dev_alloc_list);
1256 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1257 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1258 &device->dev_state))
1259 fs_devices->rw_devices--;
1261 list_del_init(&device->dev_list);
1262 fs_devices->num_devices--;
1263 btrfs_free_device(device);
1266 if (fs_devices->seed) {
1267 fs_devices = fs_devices->seed;
1271 fs_devices->latest_bdev = latest_dev->bdev;
1273 mutex_unlock(&uuid_mutex);
1276 static void btrfs_close_bdev(struct btrfs_device *device)
1281 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1282 sync_blockdev(device->bdev);
1283 invalidate_bdev(device->bdev);
1286 blkdev_put(device->bdev, device->mode);
1289 static void btrfs_close_one_device(struct btrfs_device *device)
1291 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1292 struct btrfs_device *new_device;
1293 struct rcu_string *name;
1296 fs_devices->open_devices--;
1298 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1299 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1300 list_del_init(&device->dev_alloc_list);
1301 fs_devices->rw_devices--;
1304 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1305 fs_devices->missing_devices--;
1307 btrfs_close_bdev(device);
1309 new_device = btrfs_alloc_device(NULL, &device->devid,
1311 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1313 /* Safe because we are under uuid_mutex */
1315 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1316 BUG_ON(!name); /* -ENOMEM */
1317 rcu_assign_pointer(new_device->name, name);
1320 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1321 new_device->fs_devices = device->fs_devices;
1324 btrfs_free_device(device);
1327 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1329 struct btrfs_device *device, *tmp;
1331 if (--fs_devices->opened > 0)
1334 mutex_lock(&fs_devices->device_list_mutex);
1335 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1336 btrfs_close_one_device(device);
1338 mutex_unlock(&fs_devices->device_list_mutex);
1340 WARN_ON(fs_devices->open_devices);
1341 WARN_ON(fs_devices->rw_devices);
1342 fs_devices->opened = 0;
1343 fs_devices->seeding = 0;
1348 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1350 struct btrfs_fs_devices *seed_devices = NULL;
1353 mutex_lock(&uuid_mutex);
1354 ret = close_fs_devices(fs_devices);
1355 if (!fs_devices->opened) {
1356 seed_devices = fs_devices->seed;
1357 fs_devices->seed = NULL;
1359 mutex_unlock(&uuid_mutex);
1361 while (seed_devices) {
1362 fs_devices = seed_devices;
1363 seed_devices = fs_devices->seed;
1364 close_fs_devices(fs_devices);
1365 free_fs_devices(fs_devices);
1370 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1371 fmode_t flags, void *holder)
1373 struct btrfs_device *device;
1374 struct btrfs_device *latest_dev = NULL;
1377 flags |= FMODE_EXCL;
1379 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1380 /* Just open everything we can; ignore failures here */
1381 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1385 device->generation > latest_dev->generation)
1386 latest_dev = device;
1388 if (fs_devices->open_devices == 0) {
1392 fs_devices->opened = 1;
1393 fs_devices->latest_bdev = latest_dev->bdev;
1394 fs_devices->total_rw_bytes = 0;
1399 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1401 struct btrfs_device *dev1, *dev2;
1403 dev1 = list_entry(a, struct btrfs_device, dev_list);
1404 dev2 = list_entry(b, struct btrfs_device, dev_list);
1406 if (dev1->devid < dev2->devid)
1408 else if (dev1->devid > dev2->devid)
1413 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1414 fmode_t flags, void *holder)
1418 lockdep_assert_held(&uuid_mutex);
1420 mutex_lock(&fs_devices->device_list_mutex);
1421 if (fs_devices->opened) {
1422 fs_devices->opened++;
1425 list_sort(NULL, &fs_devices->devices, devid_cmp);
1426 ret = open_fs_devices(fs_devices, flags, holder);
1428 mutex_unlock(&fs_devices->device_list_mutex);
1433 static void btrfs_release_disk_super(struct page *page)
1439 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1441 struct btrfs_super_block **disk_super)
1446 /* make sure our super fits in the device */
1447 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1450 /* make sure our super fits in the page */
1451 if (sizeof(**disk_super) > PAGE_SIZE)
1454 /* make sure our super doesn't straddle pages on disk */
1455 index = bytenr >> PAGE_SHIFT;
1456 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1459 /* pull in the page with our super */
1460 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1463 if (IS_ERR_OR_NULL(*page))
1468 /* align our pointer to the offset of the super block */
1469 *disk_super = p + offset_in_page(bytenr);
1471 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1472 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1473 btrfs_release_disk_super(*page);
1477 if ((*disk_super)->label[0] &&
1478 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1479 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1484 int btrfs_forget_devices(const char *path)
1488 mutex_lock(&uuid_mutex);
1489 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1490 mutex_unlock(&uuid_mutex);
1496 * Look for a btrfs signature on a device. This may be called out of the mount path
1497 * and we are not allowed to call set_blocksize during the scan. The superblock
1498 * is read via pagecache
1500 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1503 struct btrfs_super_block *disk_super;
1504 bool new_device_added = false;
1505 struct btrfs_device *device = NULL;
1506 struct block_device *bdev;
1510 lockdep_assert_held(&uuid_mutex);
1513 * we would like to check all the supers, but that would make
1514 * a btrfs mount succeed after a mkfs from a different FS.
1515 * So, we need to add a special mount option to scan for
1516 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1518 bytenr = btrfs_sb_offset(0);
1519 flags |= FMODE_EXCL;
1521 bdev = blkdev_get_by_path(path, flags, holder);
1523 return ERR_CAST(bdev);
1525 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1526 device = ERR_PTR(-EINVAL);
1527 goto error_bdev_put;
1530 device = device_list_add(path, disk_super, &new_device_added);
1531 if (!IS_ERR(device)) {
1532 if (new_device_added)
1533 btrfs_free_stale_devices(path, device);
1536 btrfs_release_disk_super(page);
1539 blkdev_put(bdev, flags);
1545 * Try to find a chunk that intersects [start, start + len] range and when one
1546 * such is found, record the end of it in *start
1548 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1551 u64 physical_start, physical_end;
1553 lockdep_assert_held(&device->fs_info->chunk_mutex);
1555 if (!find_first_extent_bit(&device->alloc_state, *start,
1556 &physical_start, &physical_end,
1557 CHUNK_ALLOCATED, NULL)) {
1559 if (in_range(physical_start, *start, len) ||
1560 in_range(*start, physical_start,
1561 physical_end - physical_start)) {
1562 *start = physical_end + 1;
1571 * find_free_dev_extent_start - find free space in the specified device
1572 * @device: the device which we search the free space in
1573 * @num_bytes: the size of the free space that we need
1574 * @search_start: the position from which to begin the search
1575 * @start: store the start of the free space.
1576 * @len: the size of the free space. that we find, or the size
1577 * of the max free space if we don't find suitable free space
1579 * this uses a pretty simple search, the expectation is that it is
1580 * called very infrequently and that a given device has a small number
1583 * @start is used to store the start of the free space if we find. But if we
1584 * don't find suitable free space, it will be used to store the start position
1585 * of the max free space.
1587 * @len is used to store the size of the free space that we find.
1588 * But if we don't find suitable free space, it is used to store the size of
1589 * the max free space.
1591 * NOTE: This function will search *commit* root of device tree, and does extra
1592 * check to ensure dev extents are not double allocated.
1593 * This makes the function safe to allocate dev extents but may not report
1594 * correct usable device space, as device extent freed in current transaction
1595 * is not reported as avaiable.
1597 static int find_free_dev_extent_start(struct btrfs_device *device,
1598 u64 num_bytes, u64 search_start, u64 *start,
1601 struct btrfs_fs_info *fs_info = device->fs_info;
1602 struct btrfs_root *root = fs_info->dev_root;
1603 struct btrfs_key key;
1604 struct btrfs_dev_extent *dev_extent;
1605 struct btrfs_path *path;
1610 u64 search_end = device->total_bytes;
1613 struct extent_buffer *l;
1616 * We don't want to overwrite the superblock on the drive nor any area
1617 * used by the boot loader (grub for example), so we make sure to start
1618 * at an offset of at least 1MB.
1620 search_start = max_t(u64, search_start, SZ_1M);
1622 path = btrfs_alloc_path();
1626 max_hole_start = search_start;
1630 if (search_start >= search_end ||
1631 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1636 path->reada = READA_FORWARD;
1637 path->search_commit_root = 1;
1638 path->skip_locking = 1;
1640 key.objectid = device->devid;
1641 key.offset = search_start;
1642 key.type = BTRFS_DEV_EXTENT_KEY;
1644 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1648 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1655 slot = path->slots[0];
1656 if (slot >= btrfs_header_nritems(l)) {
1657 ret = btrfs_next_leaf(root, path);
1665 btrfs_item_key_to_cpu(l, &key, slot);
1667 if (key.objectid < device->devid)
1670 if (key.objectid > device->devid)
1673 if (key.type != BTRFS_DEV_EXTENT_KEY)
1676 if (key.offset > search_start) {
1677 hole_size = key.offset - search_start;
1680 * Have to check before we set max_hole_start, otherwise
1681 * we could end up sending back this offset anyway.
1683 if (contains_pending_extent(device, &search_start,
1685 if (key.offset >= search_start)
1686 hole_size = key.offset - search_start;
1691 if (hole_size > max_hole_size) {
1692 max_hole_start = search_start;
1693 max_hole_size = hole_size;
1697 * If this free space is greater than which we need,
1698 * it must be the max free space that we have found
1699 * until now, so max_hole_start must point to the start
1700 * of this free space and the length of this free space
1701 * is stored in max_hole_size. Thus, we return
1702 * max_hole_start and max_hole_size and go back to the
1705 if (hole_size >= num_bytes) {
1711 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1712 extent_end = key.offset + btrfs_dev_extent_length(l,
1714 if (extent_end > search_start)
1715 search_start = extent_end;
1722 * At this point, search_start should be the end of
1723 * allocated dev extents, and when shrinking the device,
1724 * search_end may be smaller than search_start.
1726 if (search_end > search_start) {
1727 hole_size = search_end - search_start;
1729 if (contains_pending_extent(device, &search_start, hole_size)) {
1730 btrfs_release_path(path);
1734 if (hole_size > max_hole_size) {
1735 max_hole_start = search_start;
1736 max_hole_size = hole_size;
1741 if (max_hole_size < num_bytes)
1747 btrfs_free_path(path);
1748 *start = max_hole_start;
1750 *len = max_hole_size;
1754 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1755 u64 *start, u64 *len)
1757 /* FIXME use last free of some kind */
1758 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1761 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1762 struct btrfs_device *device,
1763 u64 start, u64 *dev_extent_len)
1765 struct btrfs_fs_info *fs_info = device->fs_info;
1766 struct btrfs_root *root = fs_info->dev_root;
1768 struct btrfs_path *path;
1769 struct btrfs_key key;
1770 struct btrfs_key found_key;
1771 struct extent_buffer *leaf = NULL;
1772 struct btrfs_dev_extent *extent = NULL;
1774 path = btrfs_alloc_path();
1778 key.objectid = device->devid;
1780 key.type = BTRFS_DEV_EXTENT_KEY;
1782 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1784 ret = btrfs_previous_item(root, path, key.objectid,
1785 BTRFS_DEV_EXTENT_KEY);
1788 leaf = path->nodes[0];
1789 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1790 extent = btrfs_item_ptr(leaf, path->slots[0],
1791 struct btrfs_dev_extent);
1792 BUG_ON(found_key.offset > start || found_key.offset +
1793 btrfs_dev_extent_length(leaf, extent) < start);
1795 btrfs_release_path(path);
1797 } else if (ret == 0) {
1798 leaf = path->nodes[0];
1799 extent = btrfs_item_ptr(leaf, path->slots[0],
1800 struct btrfs_dev_extent);
1802 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1806 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1808 ret = btrfs_del_item(trans, root, path);
1810 btrfs_handle_fs_error(fs_info, ret,
1811 "Failed to remove dev extent item");
1813 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1816 btrfs_free_path(path);
1820 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1821 struct btrfs_device *device,
1822 u64 chunk_offset, u64 start, u64 num_bytes)
1825 struct btrfs_path *path;
1826 struct btrfs_fs_info *fs_info = device->fs_info;
1827 struct btrfs_root *root = fs_info->dev_root;
1828 struct btrfs_dev_extent *extent;
1829 struct extent_buffer *leaf;
1830 struct btrfs_key key;
1832 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1833 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1834 path = btrfs_alloc_path();
1838 key.objectid = device->devid;
1840 key.type = BTRFS_DEV_EXTENT_KEY;
1841 ret = btrfs_insert_empty_item(trans, root, path, &key,
1846 leaf = path->nodes[0];
1847 extent = btrfs_item_ptr(leaf, path->slots[0],
1848 struct btrfs_dev_extent);
1849 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1850 BTRFS_CHUNK_TREE_OBJECTID);
1851 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1852 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1853 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1855 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1856 btrfs_mark_buffer_dirty(leaf);
1858 btrfs_free_path(path);
1862 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1864 struct extent_map_tree *em_tree;
1865 struct extent_map *em;
1869 em_tree = &fs_info->mapping_tree;
1870 read_lock(&em_tree->lock);
1871 n = rb_last(&em_tree->map.rb_root);
1873 em = rb_entry(n, struct extent_map, rb_node);
1874 ret = em->start + em->len;
1876 read_unlock(&em_tree->lock);
1881 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1885 struct btrfs_key key;
1886 struct btrfs_key found_key;
1887 struct btrfs_path *path;
1889 path = btrfs_alloc_path();
1893 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1894 key.type = BTRFS_DEV_ITEM_KEY;
1895 key.offset = (u64)-1;
1897 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1903 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1908 ret = btrfs_previous_item(fs_info->chunk_root, path,
1909 BTRFS_DEV_ITEMS_OBJECTID,
1910 BTRFS_DEV_ITEM_KEY);
1914 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1916 *devid_ret = found_key.offset + 1;
1920 btrfs_free_path(path);
1925 * the device information is stored in the chunk root
1926 * the btrfs_device struct should be fully filled in
1928 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1929 struct btrfs_device *device)
1932 struct btrfs_path *path;
1933 struct btrfs_dev_item *dev_item;
1934 struct extent_buffer *leaf;
1935 struct btrfs_key key;
1938 path = btrfs_alloc_path();
1942 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1943 key.type = BTRFS_DEV_ITEM_KEY;
1944 key.offset = device->devid;
1946 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1947 &key, sizeof(*dev_item));
1951 leaf = path->nodes[0];
1952 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1954 btrfs_set_device_id(leaf, dev_item, device->devid);
1955 btrfs_set_device_generation(leaf, dev_item, 0);
1956 btrfs_set_device_type(leaf, dev_item, device->type);
1957 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1958 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1959 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1960 btrfs_set_device_total_bytes(leaf, dev_item,
1961 btrfs_device_get_disk_total_bytes(device));
1962 btrfs_set_device_bytes_used(leaf, dev_item,
1963 btrfs_device_get_bytes_used(device));
1964 btrfs_set_device_group(leaf, dev_item, 0);
1965 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1966 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1967 btrfs_set_device_start_offset(leaf, dev_item, 0);
1969 ptr = btrfs_device_uuid(dev_item);
1970 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1971 ptr = btrfs_device_fsid(dev_item);
1972 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1973 ptr, BTRFS_FSID_SIZE);
1974 btrfs_mark_buffer_dirty(leaf);
1978 btrfs_free_path(path);
1983 * Function to update ctime/mtime for a given device path.
1984 * Mainly used for ctime/mtime based probe like libblkid.
1986 static void update_dev_time(const char *path_name)
1990 filp = filp_open(path_name, O_RDWR, 0);
1993 file_update_time(filp);
1994 filp_close(filp, NULL);
1997 static int btrfs_rm_dev_item(struct btrfs_device *device)
1999 struct btrfs_root *root = device->fs_info->chunk_root;
2001 struct btrfs_path *path;
2002 struct btrfs_key key;
2003 struct btrfs_trans_handle *trans;
2005 path = btrfs_alloc_path();
2009 trans = btrfs_start_transaction(root, 0);
2010 if (IS_ERR(trans)) {
2011 btrfs_free_path(path);
2012 return PTR_ERR(trans);
2014 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2015 key.type = BTRFS_DEV_ITEM_KEY;
2016 key.offset = device->devid;
2018 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2022 btrfs_abort_transaction(trans, ret);
2023 btrfs_end_transaction(trans);
2027 ret = btrfs_del_item(trans, root, path);
2029 btrfs_abort_transaction(trans, ret);
2030 btrfs_end_transaction(trans);
2034 btrfs_free_path(path);
2036 ret = btrfs_commit_transaction(trans);
2041 * Verify that @num_devices satisfies the RAID profile constraints in the whole
2042 * filesystem. It's up to the caller to adjust that number regarding eg. device
2045 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
2053 seq = read_seqbegin(&fs_info->profiles_lock);
2055 all_avail = fs_info->avail_data_alloc_bits |
2056 fs_info->avail_system_alloc_bits |
2057 fs_info->avail_metadata_alloc_bits;
2058 } while (read_seqretry(&fs_info->profiles_lock, seq));
2060 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2061 if (!(all_avail & btrfs_raid_array[i].bg_flag))
2064 if (num_devices < btrfs_raid_array[i].devs_min) {
2065 int ret = btrfs_raid_array[i].mindev_error;
2075 static struct btrfs_device * btrfs_find_next_active_device(
2076 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2078 struct btrfs_device *next_device;
2080 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2081 if (next_device != device &&
2082 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2083 && next_device->bdev)
2091 * Helper function to check if the given device is part of s_bdev / latest_bdev
2092 * and replace it with the provided or the next active device, in the context
2093 * where this function called, there should be always be another device (or
2094 * this_dev) which is active.
2096 void btrfs_assign_next_active_device(struct btrfs_device *device,
2097 struct btrfs_device *this_dev)
2099 struct btrfs_fs_info *fs_info = device->fs_info;
2100 struct btrfs_device *next_device;
2103 next_device = this_dev;
2105 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2107 ASSERT(next_device);
2109 if (fs_info->sb->s_bdev &&
2110 (fs_info->sb->s_bdev == device->bdev))
2111 fs_info->sb->s_bdev = next_device->bdev;
2113 if (fs_info->fs_devices->latest_bdev == device->bdev)
2114 fs_info->fs_devices->latest_bdev = next_device->bdev;
2118 * Return btrfs_fs_devices::num_devices excluding the device that's being
2119 * currently replaced.
2121 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2123 u64 num_devices = fs_info->fs_devices->num_devices;
2125 down_read(&fs_info->dev_replace.rwsem);
2126 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2127 ASSERT(num_devices > 1);
2130 up_read(&fs_info->dev_replace.rwsem);
2135 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2138 struct btrfs_device *device;
2139 struct btrfs_fs_devices *cur_devices;
2140 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2144 mutex_lock(&uuid_mutex);
2146 num_devices = btrfs_num_devices(fs_info);
2148 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2152 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2154 if (IS_ERR(device)) {
2155 if (PTR_ERR(device) == -ENOENT &&
2156 strcmp(device_path, "missing") == 0)
2157 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2159 ret = PTR_ERR(device);
2163 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2164 btrfs_warn_in_rcu(fs_info,
2165 "cannot remove device %s (devid %llu) due to active swapfile",
2166 rcu_str_deref(device->name), device->devid);
2171 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2172 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2176 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2177 fs_info->fs_devices->rw_devices == 1) {
2178 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2182 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2183 mutex_lock(&fs_info->chunk_mutex);
2184 list_del_init(&device->dev_alloc_list);
2185 device->fs_devices->rw_devices--;
2186 mutex_unlock(&fs_info->chunk_mutex);
2189 mutex_unlock(&uuid_mutex);
2190 ret = btrfs_shrink_device(device, 0);
2191 mutex_lock(&uuid_mutex);
2196 * TODO: the superblock still includes this device in its num_devices
2197 * counter although write_all_supers() is not locked out. This
2198 * could give a filesystem state which requires a degraded mount.
2200 ret = btrfs_rm_dev_item(device);
2204 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2205 btrfs_scrub_cancel_dev(device);
2208 * the device list mutex makes sure that we don't change
2209 * the device list while someone else is writing out all
2210 * the device supers. Whoever is writing all supers, should
2211 * lock the device list mutex before getting the number of
2212 * devices in the super block (super_copy). Conversely,
2213 * whoever updates the number of devices in the super block
2214 * (super_copy) should hold the device list mutex.
2218 * In normal cases the cur_devices == fs_devices. But in case
2219 * of deleting a seed device, the cur_devices should point to
2220 * its own fs_devices listed under the fs_devices->seed.
2222 cur_devices = device->fs_devices;
2223 mutex_lock(&fs_devices->device_list_mutex);
2224 list_del_rcu(&device->dev_list);
2226 cur_devices->num_devices--;
2227 cur_devices->total_devices--;
2228 /* Update total_devices of the parent fs_devices if it's seed */
2229 if (cur_devices != fs_devices)
2230 fs_devices->total_devices--;
2232 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2233 cur_devices->missing_devices--;
2235 btrfs_assign_next_active_device(device, NULL);
2238 cur_devices->open_devices--;
2239 /* remove sysfs entry */
2240 btrfs_sysfs_rm_device_link(fs_devices, device);
2243 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2244 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2245 mutex_unlock(&fs_devices->device_list_mutex);
2248 * at this point, the device is zero sized and detached from
2249 * the devices list. All that's left is to zero out the old
2250 * supers and free the device.
2252 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2253 btrfs_scratch_superblocks(device->bdev, device->name->str);
2255 btrfs_close_bdev(device);
2257 btrfs_free_device(device);
2259 if (cur_devices->open_devices == 0) {
2260 while (fs_devices) {
2261 if (fs_devices->seed == cur_devices) {
2262 fs_devices->seed = cur_devices->seed;
2265 fs_devices = fs_devices->seed;
2267 cur_devices->seed = NULL;
2268 close_fs_devices(cur_devices);
2269 free_fs_devices(cur_devices);
2273 mutex_unlock(&uuid_mutex);
2277 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2278 mutex_lock(&fs_info->chunk_mutex);
2279 list_add(&device->dev_alloc_list,
2280 &fs_devices->alloc_list);
2281 device->fs_devices->rw_devices++;
2282 mutex_unlock(&fs_info->chunk_mutex);
2287 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2289 struct btrfs_fs_devices *fs_devices;
2291 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2294 * in case of fs with no seed, srcdev->fs_devices will point
2295 * to fs_devices of fs_info. However when the dev being replaced is
2296 * a seed dev it will point to the seed's local fs_devices. In short
2297 * srcdev will have its correct fs_devices in both the cases.
2299 fs_devices = srcdev->fs_devices;
2301 list_del_rcu(&srcdev->dev_list);
2302 list_del(&srcdev->dev_alloc_list);
2303 fs_devices->num_devices--;
2304 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2305 fs_devices->missing_devices--;
2307 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2308 fs_devices->rw_devices--;
2311 fs_devices->open_devices--;
2314 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2316 struct btrfs_fs_info *fs_info = srcdev->fs_info;
2317 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2319 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2320 /* zero out the old super if it is writable */
2321 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2324 btrfs_close_bdev(srcdev);
2326 btrfs_free_device(srcdev);
2328 /* if this is no devs we rather delete the fs_devices */
2329 if (!fs_devices->num_devices) {
2330 struct btrfs_fs_devices *tmp_fs_devices;
2333 * On a mounted FS, num_devices can't be zero unless it's a
2334 * seed. In case of a seed device being replaced, the replace
2335 * target added to the sprout FS, so there will be no more
2336 * device left under the seed FS.
2338 ASSERT(fs_devices->seeding);
2340 tmp_fs_devices = fs_info->fs_devices;
2341 while (tmp_fs_devices) {
2342 if (tmp_fs_devices->seed == fs_devices) {
2343 tmp_fs_devices->seed = fs_devices->seed;
2346 tmp_fs_devices = tmp_fs_devices->seed;
2348 fs_devices->seed = NULL;
2349 close_fs_devices(fs_devices);
2350 free_fs_devices(fs_devices);
2354 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2356 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2359 mutex_lock(&fs_devices->device_list_mutex);
2361 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2364 fs_devices->open_devices--;
2366 fs_devices->num_devices--;
2368 btrfs_assign_next_active_device(tgtdev, NULL);
2370 list_del_rcu(&tgtdev->dev_list);
2372 mutex_unlock(&fs_devices->device_list_mutex);
2375 * The update_dev_time() with in btrfs_scratch_superblocks()
2376 * may lead to a call to btrfs_show_devname() which will try
2377 * to hold device_list_mutex. And here this device
2378 * is already out of device list, so we don't have to hold
2379 * the device_list_mutex lock.
2381 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2383 btrfs_close_bdev(tgtdev);
2385 btrfs_free_device(tgtdev);
2388 static struct btrfs_device *btrfs_find_device_by_path(
2389 struct btrfs_fs_info *fs_info, const char *device_path)
2392 struct btrfs_super_block *disk_super;
2395 struct block_device *bdev;
2396 struct buffer_head *bh;
2397 struct btrfs_device *device;
2399 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2400 fs_info->bdev_holder, 0, &bdev, &bh);
2402 return ERR_PTR(ret);
2403 disk_super = (struct btrfs_super_block *)bh->b_data;
2404 devid = btrfs_stack_device_id(&disk_super->dev_item);
2405 dev_uuid = disk_super->dev_item.uuid;
2406 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2407 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2408 disk_super->metadata_uuid, true);
2410 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2411 disk_super->fsid, true);
2415 device = ERR_PTR(-ENOENT);
2416 blkdev_put(bdev, FMODE_READ);
2421 * Lookup a device given by device id, or the path if the id is 0.
2423 struct btrfs_device *btrfs_find_device_by_devspec(
2424 struct btrfs_fs_info *fs_info, u64 devid,
2425 const char *device_path)
2427 struct btrfs_device *device;
2430 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2433 return ERR_PTR(-ENOENT);
2437 if (!device_path || !device_path[0])
2438 return ERR_PTR(-EINVAL);
2440 if (strcmp(device_path, "missing") == 0) {
2441 /* Find first missing device */
2442 list_for_each_entry(device, &fs_info->fs_devices->devices,
2444 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2445 &device->dev_state) && !device->bdev)
2448 return ERR_PTR(-ENOENT);
2451 return btrfs_find_device_by_path(fs_info, device_path);
2455 * does all the dirty work required for changing file system's UUID.
2457 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2459 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2460 struct btrfs_fs_devices *old_devices;
2461 struct btrfs_fs_devices *seed_devices;
2462 struct btrfs_super_block *disk_super = fs_info->super_copy;
2463 struct btrfs_device *device;
2466 lockdep_assert_held(&uuid_mutex);
2467 if (!fs_devices->seeding)
2470 seed_devices = alloc_fs_devices(NULL, NULL);
2471 if (IS_ERR(seed_devices))
2472 return PTR_ERR(seed_devices);
2474 old_devices = clone_fs_devices(fs_devices);
2475 if (IS_ERR(old_devices)) {
2476 kfree(seed_devices);
2477 return PTR_ERR(old_devices);
2480 list_add(&old_devices->fs_list, &fs_uuids);
2482 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2483 seed_devices->opened = 1;
2484 INIT_LIST_HEAD(&seed_devices->devices);
2485 INIT_LIST_HEAD(&seed_devices->alloc_list);
2486 mutex_init(&seed_devices->device_list_mutex);
2488 mutex_lock(&fs_devices->device_list_mutex);
2489 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2491 list_for_each_entry(device, &seed_devices->devices, dev_list)
2492 device->fs_devices = seed_devices;
2494 mutex_lock(&fs_info->chunk_mutex);
2495 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2496 mutex_unlock(&fs_info->chunk_mutex);
2498 fs_devices->seeding = 0;
2499 fs_devices->num_devices = 0;
2500 fs_devices->open_devices = 0;
2501 fs_devices->missing_devices = 0;
2502 fs_devices->rotating = 0;
2503 fs_devices->seed = seed_devices;
2505 generate_random_uuid(fs_devices->fsid);
2506 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2507 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2508 mutex_unlock(&fs_devices->device_list_mutex);
2510 super_flags = btrfs_super_flags(disk_super) &
2511 ~BTRFS_SUPER_FLAG_SEEDING;
2512 btrfs_set_super_flags(disk_super, super_flags);
2518 * Store the expected generation for seed devices in device items.
2520 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2522 struct btrfs_fs_info *fs_info = trans->fs_info;
2523 struct btrfs_root *root = fs_info->chunk_root;
2524 struct btrfs_path *path;
2525 struct extent_buffer *leaf;
2526 struct btrfs_dev_item *dev_item;
2527 struct btrfs_device *device;
2528 struct btrfs_key key;
2529 u8 fs_uuid[BTRFS_FSID_SIZE];
2530 u8 dev_uuid[BTRFS_UUID_SIZE];
2534 path = btrfs_alloc_path();
2538 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2540 key.type = BTRFS_DEV_ITEM_KEY;
2543 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2547 leaf = path->nodes[0];
2549 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2550 ret = btrfs_next_leaf(root, path);
2555 leaf = path->nodes[0];
2556 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2557 btrfs_release_path(path);
2561 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2562 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2563 key.type != BTRFS_DEV_ITEM_KEY)
2566 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2567 struct btrfs_dev_item);
2568 devid = btrfs_device_id(leaf, dev_item);
2569 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2571 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2573 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2575 BUG_ON(!device); /* Logic error */
2577 if (device->fs_devices->seeding) {
2578 btrfs_set_device_generation(leaf, dev_item,
2579 device->generation);
2580 btrfs_mark_buffer_dirty(leaf);
2588 btrfs_free_path(path);
2592 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2594 struct btrfs_root *root = fs_info->dev_root;
2595 struct request_queue *q;
2596 struct btrfs_trans_handle *trans;
2597 struct btrfs_device *device;
2598 struct block_device *bdev;
2599 struct super_block *sb = fs_info->sb;
2600 struct rcu_string *name;
2601 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2602 u64 orig_super_total_bytes;
2603 u64 orig_super_num_devices;
2604 int seeding_dev = 0;
2606 bool unlocked = false;
2608 if (sb_rdonly(sb) && !fs_devices->seeding)
2611 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2612 fs_info->bdev_holder);
2614 return PTR_ERR(bdev);
2616 if (fs_devices->seeding) {
2618 down_write(&sb->s_umount);
2619 mutex_lock(&uuid_mutex);
2622 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2624 mutex_lock(&fs_devices->device_list_mutex);
2625 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2626 if (device->bdev == bdev) {
2629 &fs_devices->device_list_mutex);
2633 mutex_unlock(&fs_devices->device_list_mutex);
2635 device = btrfs_alloc_device(fs_info, NULL, NULL);
2636 if (IS_ERR(device)) {
2637 /* we can safely leave the fs_devices entry around */
2638 ret = PTR_ERR(device);
2642 name = rcu_string_strdup(device_path, GFP_KERNEL);
2645 goto error_free_device;
2647 rcu_assign_pointer(device->name, name);
2649 trans = btrfs_start_transaction(root, 0);
2650 if (IS_ERR(trans)) {
2651 ret = PTR_ERR(trans);
2652 goto error_free_device;
2655 q = bdev_get_queue(bdev);
2656 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2657 device->generation = trans->transid;
2658 device->io_width = fs_info->sectorsize;
2659 device->io_align = fs_info->sectorsize;
2660 device->sector_size = fs_info->sectorsize;
2661 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2662 fs_info->sectorsize);
2663 device->disk_total_bytes = device->total_bytes;
2664 device->commit_total_bytes = device->total_bytes;
2665 device->fs_info = fs_info;
2666 device->bdev = bdev;
2667 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2668 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2669 device->mode = FMODE_EXCL;
2670 device->dev_stats_valid = 1;
2671 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2674 sb->s_flags &= ~SB_RDONLY;
2675 ret = btrfs_prepare_sprout(fs_info);
2677 btrfs_abort_transaction(trans, ret);
2682 device->fs_devices = fs_devices;
2684 mutex_lock(&fs_devices->device_list_mutex);
2685 mutex_lock(&fs_info->chunk_mutex);
2686 list_add_rcu(&device->dev_list, &fs_devices->devices);
2687 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2688 fs_devices->num_devices++;
2689 fs_devices->open_devices++;
2690 fs_devices->rw_devices++;
2691 fs_devices->total_devices++;
2692 fs_devices->total_rw_bytes += device->total_bytes;
2694 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2696 if (!blk_queue_nonrot(q))
2697 fs_devices->rotating = 1;
2699 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2700 btrfs_set_super_total_bytes(fs_info->super_copy,
2701 round_down(orig_super_total_bytes + device->total_bytes,
2702 fs_info->sectorsize));
2704 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2705 btrfs_set_super_num_devices(fs_info->super_copy,
2706 orig_super_num_devices + 1);
2708 /* add sysfs device entry */
2709 btrfs_sysfs_add_device_link(fs_devices, device);
2712 * we've got more storage, clear any full flags on the space
2715 btrfs_clear_space_info_full(fs_info);
2717 mutex_unlock(&fs_info->chunk_mutex);
2718 mutex_unlock(&fs_devices->device_list_mutex);
2721 mutex_lock(&fs_info->chunk_mutex);
2722 ret = init_first_rw_device(trans);
2723 mutex_unlock(&fs_info->chunk_mutex);
2725 btrfs_abort_transaction(trans, ret);
2730 ret = btrfs_add_dev_item(trans, device);
2732 btrfs_abort_transaction(trans, ret);
2737 ret = btrfs_finish_sprout(trans);
2739 btrfs_abort_transaction(trans, ret);
2743 btrfs_sysfs_update_sprout_fsid(fs_devices,
2744 fs_info->fs_devices->fsid);
2747 ret = btrfs_commit_transaction(trans);
2750 mutex_unlock(&uuid_mutex);
2751 up_write(&sb->s_umount);
2754 if (ret) /* transaction commit */
2757 ret = btrfs_relocate_sys_chunks(fs_info);
2759 btrfs_handle_fs_error(fs_info, ret,
2760 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2761 trans = btrfs_attach_transaction(root);
2762 if (IS_ERR(trans)) {
2763 if (PTR_ERR(trans) == -ENOENT)
2765 ret = PTR_ERR(trans);
2769 ret = btrfs_commit_transaction(trans);
2772 /* Update ctime/mtime for libblkid */
2773 update_dev_time(device_path);
2777 btrfs_sysfs_rm_device_link(fs_devices, device);
2778 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2779 mutex_lock(&fs_info->chunk_mutex);
2780 list_del_rcu(&device->dev_list);
2781 list_del(&device->dev_alloc_list);
2782 fs_info->fs_devices->num_devices--;
2783 fs_info->fs_devices->open_devices--;
2784 fs_info->fs_devices->rw_devices--;
2785 fs_info->fs_devices->total_devices--;
2786 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2787 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2788 btrfs_set_super_total_bytes(fs_info->super_copy,
2789 orig_super_total_bytes);
2790 btrfs_set_super_num_devices(fs_info->super_copy,
2791 orig_super_num_devices);
2792 mutex_unlock(&fs_info->chunk_mutex);
2793 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2796 sb->s_flags |= SB_RDONLY;
2798 btrfs_end_transaction(trans);
2800 btrfs_free_device(device);
2802 blkdev_put(bdev, FMODE_EXCL);
2803 if (seeding_dev && !unlocked) {
2804 mutex_unlock(&uuid_mutex);
2805 up_write(&sb->s_umount);
2810 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2811 struct btrfs_device *device)
2814 struct btrfs_path *path;
2815 struct btrfs_root *root = device->fs_info->chunk_root;
2816 struct btrfs_dev_item *dev_item;
2817 struct extent_buffer *leaf;
2818 struct btrfs_key key;
2820 path = btrfs_alloc_path();
2824 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2825 key.type = BTRFS_DEV_ITEM_KEY;
2826 key.offset = device->devid;
2828 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2837 leaf = path->nodes[0];
2838 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2840 btrfs_set_device_id(leaf, dev_item, device->devid);
2841 btrfs_set_device_type(leaf, dev_item, device->type);
2842 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2843 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2844 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2845 btrfs_set_device_total_bytes(leaf, dev_item,
2846 btrfs_device_get_disk_total_bytes(device));
2847 btrfs_set_device_bytes_used(leaf, dev_item,
2848 btrfs_device_get_bytes_used(device));
2849 btrfs_mark_buffer_dirty(leaf);
2852 btrfs_free_path(path);
2856 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2857 struct btrfs_device *device, u64 new_size)
2859 struct btrfs_fs_info *fs_info = device->fs_info;
2860 struct btrfs_super_block *super_copy = fs_info->super_copy;
2864 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2867 new_size = round_down(new_size, fs_info->sectorsize);
2869 mutex_lock(&fs_info->chunk_mutex);
2870 old_total = btrfs_super_total_bytes(super_copy);
2871 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2873 if (new_size <= device->total_bytes ||
2874 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2875 mutex_unlock(&fs_info->chunk_mutex);
2879 btrfs_set_super_total_bytes(super_copy,
2880 round_down(old_total + diff, fs_info->sectorsize));
2881 device->fs_devices->total_rw_bytes += diff;
2883 btrfs_device_set_total_bytes(device, new_size);
2884 btrfs_device_set_disk_total_bytes(device, new_size);
2885 btrfs_clear_space_info_full(device->fs_info);
2886 if (list_empty(&device->post_commit_list))
2887 list_add_tail(&device->post_commit_list,
2888 &trans->transaction->dev_update_list);
2889 mutex_unlock(&fs_info->chunk_mutex);
2891 return btrfs_update_device(trans, device);
2894 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2896 struct btrfs_fs_info *fs_info = trans->fs_info;
2897 struct btrfs_root *root = fs_info->chunk_root;
2899 struct btrfs_path *path;
2900 struct btrfs_key key;
2902 path = btrfs_alloc_path();
2906 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2907 key.offset = chunk_offset;
2908 key.type = BTRFS_CHUNK_ITEM_KEY;
2910 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2913 else if (ret > 0) { /* Logic error or corruption */
2914 btrfs_handle_fs_error(fs_info, -ENOENT,
2915 "Failed lookup while freeing chunk.");
2920 ret = btrfs_del_item(trans, root, path);
2922 btrfs_handle_fs_error(fs_info, ret,
2923 "Failed to delete chunk item.");
2925 btrfs_free_path(path);
2929 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2931 struct btrfs_super_block *super_copy = fs_info->super_copy;
2932 struct btrfs_disk_key *disk_key;
2933 struct btrfs_chunk *chunk;
2940 struct btrfs_key key;
2942 mutex_lock(&fs_info->chunk_mutex);
2943 array_size = btrfs_super_sys_array_size(super_copy);
2945 ptr = super_copy->sys_chunk_array;
2948 while (cur < array_size) {
2949 disk_key = (struct btrfs_disk_key *)ptr;
2950 btrfs_disk_key_to_cpu(&key, disk_key);
2952 len = sizeof(*disk_key);
2954 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2955 chunk = (struct btrfs_chunk *)(ptr + len);
2956 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2957 len += btrfs_chunk_item_size(num_stripes);
2962 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2963 key.offset == chunk_offset) {
2964 memmove(ptr, ptr + len, array_size - (cur + len));
2966 btrfs_set_super_sys_array_size(super_copy, array_size);
2972 mutex_unlock(&fs_info->chunk_mutex);
2977 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2978 * @logical: Logical block offset in bytes.
2979 * @length: Length of extent in bytes.
2981 * Return: Chunk mapping or ERR_PTR.
2983 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2984 u64 logical, u64 length)
2986 struct extent_map_tree *em_tree;
2987 struct extent_map *em;
2989 em_tree = &fs_info->mapping_tree;
2990 read_lock(&em_tree->lock);
2991 em = lookup_extent_mapping(em_tree, logical, length);
2992 read_unlock(&em_tree->lock);
2995 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2997 return ERR_PTR(-EINVAL);
3000 if (em->start > logical || em->start + em->len < logical) {
3002 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
3003 logical, length, em->start, em->start + em->len);
3004 free_extent_map(em);
3005 return ERR_PTR(-EINVAL);
3008 /* callers are responsible for dropping em's ref. */
3012 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3014 struct btrfs_fs_info *fs_info = trans->fs_info;
3015 struct extent_map *em;
3016 struct map_lookup *map;
3017 u64 dev_extent_len = 0;
3019 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3021 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3024 * This is a logic error, but we don't want to just rely on the
3025 * user having built with ASSERT enabled, so if ASSERT doesn't
3026 * do anything we still error out.
3031 map = em->map_lookup;
3032 mutex_lock(&fs_info->chunk_mutex);
3033 check_system_chunk(trans, map->type);
3034 mutex_unlock(&fs_info->chunk_mutex);
3037 * Take the device list mutex to prevent races with the final phase of
3038 * a device replace operation that replaces the device object associated
3039 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
3041 mutex_lock(&fs_devices->device_list_mutex);
3042 for (i = 0; i < map->num_stripes; i++) {
3043 struct btrfs_device *device = map->stripes[i].dev;
3044 ret = btrfs_free_dev_extent(trans, device,
3045 map->stripes[i].physical,
3048 mutex_unlock(&fs_devices->device_list_mutex);
3049 btrfs_abort_transaction(trans, ret);
3053 if (device->bytes_used > 0) {
3054 mutex_lock(&fs_info->chunk_mutex);
3055 btrfs_device_set_bytes_used(device,
3056 device->bytes_used - dev_extent_len);
3057 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3058 btrfs_clear_space_info_full(fs_info);
3059 mutex_unlock(&fs_info->chunk_mutex);
3062 ret = btrfs_update_device(trans, device);
3064 mutex_unlock(&fs_devices->device_list_mutex);
3065 btrfs_abort_transaction(trans, ret);
3069 mutex_unlock(&fs_devices->device_list_mutex);
3071 ret = btrfs_free_chunk(trans, chunk_offset);
3073 btrfs_abort_transaction(trans, ret);
3077 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3079 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3080 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3082 btrfs_abort_transaction(trans, ret);
3087 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3089 btrfs_abort_transaction(trans, ret);
3095 free_extent_map(em);
3099 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3101 struct btrfs_root *root = fs_info->chunk_root;
3102 struct btrfs_trans_handle *trans;
3106 * Prevent races with automatic removal of unused block groups.
3107 * After we relocate and before we remove the chunk with offset
3108 * chunk_offset, automatic removal of the block group can kick in,
3109 * resulting in a failure when calling btrfs_remove_chunk() below.
3111 * Make sure to acquire this mutex before doing a tree search (dev
3112 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3113 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3114 * we release the path used to search the chunk/dev tree and before
3115 * the current task acquires this mutex and calls us.
3117 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3119 /* step one, relocate all the extents inside this chunk */
3120 btrfs_scrub_pause(fs_info);
3121 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3122 btrfs_scrub_continue(fs_info);
3126 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3128 if (IS_ERR(trans)) {
3129 ret = PTR_ERR(trans);
3130 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3135 * step two, delete the device extents and the
3136 * chunk tree entries
3138 ret = btrfs_remove_chunk(trans, chunk_offset);
3139 btrfs_end_transaction(trans);
3143 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3145 struct btrfs_root *chunk_root = fs_info->chunk_root;
3146 struct btrfs_path *path;
3147 struct extent_buffer *leaf;
3148 struct btrfs_chunk *chunk;
3149 struct btrfs_key key;
3150 struct btrfs_key found_key;
3152 bool retried = false;
3156 path = btrfs_alloc_path();
3161 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3162 key.offset = (u64)-1;
3163 key.type = BTRFS_CHUNK_ITEM_KEY;
3166 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3167 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3169 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3172 BUG_ON(ret == 0); /* Corruption */
3174 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3177 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3183 leaf = path->nodes[0];
3184 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3186 chunk = btrfs_item_ptr(leaf, path->slots[0],
3187 struct btrfs_chunk);
3188 chunk_type = btrfs_chunk_type(leaf, chunk);
3189 btrfs_release_path(path);
3191 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3192 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3198 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3200 if (found_key.offset == 0)
3202 key.offset = found_key.offset - 1;
3205 if (failed && !retried) {
3209 } else if (WARN_ON(failed && retried)) {
3213 btrfs_free_path(path);
3218 * return 1 : allocate a data chunk successfully,
3219 * return <0: errors during allocating a data chunk,
3220 * return 0 : no need to allocate a data chunk.
3222 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3225 struct btrfs_block_group_cache *cache;
3229 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3231 chunk_type = cache->flags;
3232 btrfs_put_block_group(cache);
3234 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3235 spin_lock(&fs_info->data_sinfo->lock);
3236 bytes_used = fs_info->data_sinfo->bytes_used;
3237 spin_unlock(&fs_info->data_sinfo->lock);
3240 struct btrfs_trans_handle *trans;
3243 trans = btrfs_join_transaction(fs_info->tree_root);
3245 return PTR_ERR(trans);
3247 ret = btrfs_force_chunk_alloc(trans,
3248 BTRFS_BLOCK_GROUP_DATA);
3249 btrfs_end_transaction(trans);
3258 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3259 struct btrfs_balance_control *bctl)
3261 struct btrfs_root *root = fs_info->tree_root;
3262 struct btrfs_trans_handle *trans;
3263 struct btrfs_balance_item *item;
3264 struct btrfs_disk_balance_args disk_bargs;
3265 struct btrfs_path *path;
3266 struct extent_buffer *leaf;
3267 struct btrfs_key key;
3270 path = btrfs_alloc_path();
3274 trans = btrfs_start_transaction(root, 0);
3275 if (IS_ERR(trans)) {
3276 btrfs_free_path(path);
3277 return PTR_ERR(trans);
3280 key.objectid = BTRFS_BALANCE_OBJECTID;
3281 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3284 ret = btrfs_insert_empty_item(trans, root, path, &key,
3289 leaf = path->nodes[0];
3290 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3292 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3294 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3295 btrfs_set_balance_data(leaf, item, &disk_bargs);
3296 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3297 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3298 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3299 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3301 btrfs_set_balance_flags(leaf, item, bctl->flags);
3303 btrfs_mark_buffer_dirty(leaf);
3305 btrfs_free_path(path);
3306 err = btrfs_commit_transaction(trans);
3312 static int del_balance_item(struct btrfs_fs_info *fs_info)
3314 struct btrfs_root *root = fs_info->tree_root;
3315 struct btrfs_trans_handle *trans;
3316 struct btrfs_path *path;
3317 struct btrfs_key key;
3320 path = btrfs_alloc_path();
3324 trans = btrfs_start_transaction(root, 0);
3325 if (IS_ERR(trans)) {
3326 btrfs_free_path(path);
3327 return PTR_ERR(trans);
3330 key.objectid = BTRFS_BALANCE_OBJECTID;
3331 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3334 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3342 ret = btrfs_del_item(trans, root, path);
3344 btrfs_free_path(path);
3345 err = btrfs_commit_transaction(trans);
3352 * This is a heuristic used to reduce the number of chunks balanced on
3353 * resume after balance was interrupted.
3355 static void update_balance_args(struct btrfs_balance_control *bctl)
3358 * Turn on soft mode for chunk types that were being converted.
3360 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3361 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3362 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3363 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3364 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3365 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3368 * Turn on usage filter if is not already used. The idea is
3369 * that chunks that we have already balanced should be
3370 * reasonably full. Don't do it for chunks that are being
3371 * converted - that will keep us from relocating unconverted
3372 * (albeit full) chunks.
3374 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3375 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3376 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3377 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3378 bctl->data.usage = 90;
3380 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3381 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3382 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3383 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3384 bctl->sys.usage = 90;
3386 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3387 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3388 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3389 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3390 bctl->meta.usage = 90;
3395 * Clear the balance status in fs_info and delete the balance item from disk.
3397 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3399 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3402 BUG_ON(!fs_info->balance_ctl);
3404 spin_lock(&fs_info->balance_lock);
3405 fs_info->balance_ctl = NULL;
3406 spin_unlock(&fs_info->balance_lock);
3409 ret = del_balance_item(fs_info);
3411 btrfs_handle_fs_error(fs_info, ret, NULL);
3415 * Balance filters. Return 1 if chunk should be filtered out
3416 * (should not be balanced).
3418 static int chunk_profiles_filter(u64 chunk_type,
3419 struct btrfs_balance_args *bargs)
3421 chunk_type = chunk_to_extended(chunk_type) &
3422 BTRFS_EXTENDED_PROFILE_MASK;
3424 if (bargs->profiles & chunk_type)
3430 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3431 struct btrfs_balance_args *bargs)
3433 struct btrfs_block_group_cache *cache;
3435 u64 user_thresh_min;
3436 u64 user_thresh_max;
3439 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3440 chunk_used = btrfs_block_group_used(&cache->item);
3442 if (bargs->usage_min == 0)
3443 user_thresh_min = 0;
3445 user_thresh_min = div_factor_fine(cache->key.offset,
3448 if (bargs->usage_max == 0)
3449 user_thresh_max = 1;
3450 else if (bargs->usage_max > 100)
3451 user_thresh_max = cache->key.offset;
3453 user_thresh_max = div_factor_fine(cache->key.offset,
3456 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3459 btrfs_put_block_group(cache);
3463 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3464 u64 chunk_offset, struct btrfs_balance_args *bargs)
3466 struct btrfs_block_group_cache *cache;
3467 u64 chunk_used, user_thresh;
3470 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3471 chunk_used = btrfs_block_group_used(&cache->item);
3473 if (bargs->usage_min == 0)
3475 else if (bargs->usage > 100)
3476 user_thresh = cache->key.offset;
3478 user_thresh = div_factor_fine(cache->key.offset,
3481 if (chunk_used < user_thresh)
3484 btrfs_put_block_group(cache);
3488 static int chunk_devid_filter(struct extent_buffer *leaf,
3489 struct btrfs_chunk *chunk,
3490 struct btrfs_balance_args *bargs)
3492 struct btrfs_stripe *stripe;
3493 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3496 for (i = 0; i < num_stripes; i++) {
3497 stripe = btrfs_stripe_nr(chunk, i);
3498 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3505 static u64 calc_data_stripes(u64 type, int num_stripes)
3507 const int index = btrfs_bg_flags_to_raid_index(type);
3508 const int ncopies = btrfs_raid_array[index].ncopies;
3509 const int nparity = btrfs_raid_array[index].nparity;
3512 return num_stripes - nparity;
3514 return num_stripes / ncopies;
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);
3530 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3533 type = btrfs_chunk_type(leaf, chunk);
3534 factor = calc_data_stripes(type, num_stripes);
3536 for (i = 0; i < num_stripes; i++) {
3537 stripe = btrfs_stripe_nr(chunk, i);
3538 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3541 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3542 stripe_length = btrfs_chunk_length(leaf, chunk);
3543 stripe_length = div_u64(stripe_length, factor);
3545 if (stripe_offset < bargs->pend &&
3546 stripe_offset + stripe_length > bargs->pstart)
3553 /* [vstart, vend) */
3554 static int chunk_vrange_filter(struct extent_buffer *leaf,
3555 struct btrfs_chunk *chunk,
3557 struct btrfs_balance_args *bargs)
3559 if (chunk_offset < bargs->vend &&
3560 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3561 /* at least part of the chunk is inside this vrange */
3567 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3568 struct btrfs_chunk *chunk,
3569 struct btrfs_balance_args *bargs)
3571 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3573 if (bargs->stripes_min <= num_stripes
3574 && num_stripes <= bargs->stripes_max)
3580 static int chunk_soft_convert_filter(u64 chunk_type,
3581 struct btrfs_balance_args *bargs)
3583 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3586 chunk_type = chunk_to_extended(chunk_type) &
3587 BTRFS_EXTENDED_PROFILE_MASK;
3589 if (bargs->target == chunk_type)
3595 static int should_balance_chunk(struct extent_buffer *leaf,
3596 struct btrfs_chunk *chunk, u64 chunk_offset)
3598 struct btrfs_fs_info *fs_info = leaf->fs_info;
3599 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3600 struct btrfs_balance_args *bargs = NULL;
3601 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3604 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3605 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3609 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3610 bargs = &bctl->data;
3611 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3613 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3614 bargs = &bctl->meta;
3616 /* profiles filter */
3617 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3618 chunk_profiles_filter(chunk_type, bargs)) {
3623 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3624 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3626 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3627 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3632 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3633 chunk_devid_filter(leaf, chunk, bargs)) {
3637 /* drange filter, makes sense only with devid filter */
3638 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3639 chunk_drange_filter(leaf, chunk, bargs)) {
3644 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3645 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3649 /* stripes filter */
3650 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3651 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3655 /* soft profile changing mode */
3656 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3657 chunk_soft_convert_filter(chunk_type, bargs)) {
3662 * limited by count, must be the last filter
3664 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3665 if (bargs->limit == 0)
3669 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3671 * Same logic as the 'limit' filter; the minimum cannot be
3672 * determined here because we do not have the global information
3673 * about the count of all chunks that satisfy the filters.
3675 if (bargs->limit_max == 0)
3684 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3686 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3687 struct btrfs_root *chunk_root = fs_info->chunk_root;
3689 struct btrfs_chunk *chunk;
3690 struct btrfs_path *path = NULL;
3691 struct btrfs_key key;
3692 struct btrfs_key found_key;
3693 struct extent_buffer *leaf;
3696 int enospc_errors = 0;
3697 bool counting = true;
3698 /* The single value limit and min/max limits use the same bytes in the */
3699 u64 limit_data = bctl->data.limit;
3700 u64 limit_meta = bctl->meta.limit;
3701 u64 limit_sys = bctl->sys.limit;
3705 int chunk_reserved = 0;
3707 path = btrfs_alloc_path();
3713 /* zero out stat counters */
3714 spin_lock(&fs_info->balance_lock);
3715 memset(&bctl->stat, 0, sizeof(bctl->stat));
3716 spin_unlock(&fs_info->balance_lock);
3720 * The single value limit and min/max limits use the same bytes
3723 bctl->data.limit = limit_data;
3724 bctl->meta.limit = limit_meta;
3725 bctl->sys.limit = limit_sys;
3727 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3728 key.offset = (u64)-1;
3729 key.type = BTRFS_CHUNK_ITEM_KEY;
3732 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3733 atomic_read(&fs_info->balance_cancel_req)) {
3738 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3739 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3741 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3746 * this shouldn't happen, it means the last relocate
3750 BUG(); /* FIXME break ? */
3752 ret = btrfs_previous_item(chunk_root, path, 0,
3753 BTRFS_CHUNK_ITEM_KEY);
3755 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3760 leaf = path->nodes[0];
3761 slot = path->slots[0];
3762 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3764 if (found_key.objectid != key.objectid) {
3765 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3769 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3770 chunk_type = btrfs_chunk_type(leaf, chunk);
3773 spin_lock(&fs_info->balance_lock);
3774 bctl->stat.considered++;
3775 spin_unlock(&fs_info->balance_lock);
3778 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3780 btrfs_release_path(path);
3782 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3787 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3788 spin_lock(&fs_info->balance_lock);
3789 bctl->stat.expected++;
3790 spin_unlock(&fs_info->balance_lock);
3792 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3794 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3796 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3803 * Apply limit_min filter, no need to check if the LIMITS
3804 * filter is used, limit_min is 0 by default
3806 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3807 count_data < bctl->data.limit_min)
3808 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3809 count_meta < bctl->meta.limit_min)
3810 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3811 count_sys < bctl->sys.limit_min)) {
3812 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3816 if (!chunk_reserved) {
3818 * We may be relocating the only data chunk we have,
3819 * which could potentially end up with losing data's
3820 * raid profile, so lets allocate an empty one in
3823 ret = btrfs_may_alloc_data_chunk(fs_info,
3826 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3828 } else if (ret == 1) {
3833 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3834 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3835 if (ret == -ENOSPC) {
3837 } else if (ret == -ETXTBSY) {
3839 "skipping relocation of block group %llu due to active swapfile",
3845 spin_lock(&fs_info->balance_lock);
3846 bctl->stat.completed++;
3847 spin_unlock(&fs_info->balance_lock);
3850 if (found_key.offset == 0)
3852 key.offset = found_key.offset - 1;
3856 btrfs_release_path(path);
3861 btrfs_free_path(path);
3862 if (enospc_errors) {
3863 btrfs_info(fs_info, "%d enospc errors during balance",
3873 * alloc_profile_is_valid - see if a given profile is valid and reduced
3874 * @flags: profile to validate
3875 * @extended: if true @flags is treated as an extended profile
3877 static int alloc_profile_is_valid(u64 flags, int extended)
3879 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3880 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3882 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3884 /* 1) check that all other bits are zeroed */
3888 /* 2) see if profile is reduced */
3890 return !extended; /* "0" is valid for usual profiles */
3892 /* true if exactly one bit set */
3894 * Don't use is_power_of_2(unsigned long) because it won't work
3895 * for the single profile (1ULL << 48) on 32-bit CPUs.
3897 return flags != 0 && (flags & (flags - 1)) == 0;
3900 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3902 /* cancel requested || normal exit path */
3903 return atomic_read(&fs_info->balance_cancel_req) ||
3904 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3905 atomic_read(&fs_info->balance_cancel_req) == 0);
3908 /* Non-zero return value signifies invalidity */
3909 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3912 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3913 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3914 (bctl_arg->target & ~allowed)));
3918 * Fill @buf with textual description of balance filter flags @bargs, up to
3919 * @size_buf including the terminating null. The output may be trimmed if it
3920 * does not fit into the provided buffer.
3922 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3926 u32 size_bp = size_buf;
3928 u64 flags = bargs->flags;
3929 char tmp_buf[128] = {'\0'};
3934 #define CHECK_APPEND_NOARG(a) \
3936 ret = snprintf(bp, size_bp, (a)); \
3937 if (ret < 0 || ret >= size_bp) \
3938 goto out_overflow; \
3943 #define CHECK_APPEND_1ARG(a, v1) \
3945 ret = snprintf(bp, size_bp, (a), (v1)); \
3946 if (ret < 0 || ret >= size_bp) \
3947 goto out_overflow; \
3952 #define CHECK_APPEND_2ARG(a, v1, v2) \
3954 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3955 if (ret < 0 || ret >= size_bp) \
3956 goto out_overflow; \
3961 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
3962 CHECK_APPEND_1ARG("convert=%s,",
3963 btrfs_bg_type_to_raid_name(bargs->target));
3965 if (flags & BTRFS_BALANCE_ARGS_SOFT)
3966 CHECK_APPEND_NOARG("soft,");
3968 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
3969 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
3971 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
3974 if (flags & BTRFS_BALANCE_ARGS_USAGE)
3975 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
3977 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
3978 CHECK_APPEND_2ARG("usage=%u..%u,",
3979 bargs->usage_min, bargs->usage_max);
3981 if (flags & BTRFS_BALANCE_ARGS_DEVID)
3982 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
3984 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
3985 CHECK_APPEND_2ARG("drange=%llu..%llu,",
3986 bargs->pstart, bargs->pend);
3988 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
3989 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
3990 bargs->vstart, bargs->vend);
3992 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
3993 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
3995 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
3996 CHECK_APPEND_2ARG("limit=%u..%u,",
3997 bargs->limit_min, bargs->limit_max);
3999 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4000 CHECK_APPEND_2ARG("stripes=%u..%u,",
4001 bargs->stripes_min, bargs->stripes_max);
4003 #undef CHECK_APPEND_2ARG
4004 #undef CHECK_APPEND_1ARG
4005 #undef CHECK_APPEND_NOARG
4009 if (size_bp < size_buf)
4010 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4015 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4017 u32 size_buf = 1024;
4018 char tmp_buf[192] = {'\0'};
4021 u32 size_bp = size_buf;
4023 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4025 buf = kzalloc(size_buf, GFP_KERNEL);
4031 #define CHECK_APPEND_1ARG(a, v1) \
4033 ret = snprintf(bp, size_bp, (a), (v1)); \
4034 if (ret < 0 || ret >= size_bp) \
4035 goto out_overflow; \
4040 if (bctl->flags & BTRFS_BALANCE_FORCE)
4041 CHECK_APPEND_1ARG("%s", "-f ");
4043 if (bctl->flags & BTRFS_BALANCE_DATA) {
4044 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4045 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4048 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4049 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4050 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4053 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4054 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4055 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4058 #undef CHECK_APPEND_1ARG
4062 if (size_bp < size_buf)
4063 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4064 btrfs_info(fs_info, "balance: %s %s",
4065 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4066 "resume" : "start", buf);
4072 * Should be called with balance mutexe held
4074 int btrfs_balance(struct btrfs_fs_info *fs_info,
4075 struct btrfs_balance_control *bctl,
4076 struct btrfs_ioctl_balance_args *bargs)
4078 u64 meta_target, data_target;
4084 bool reducing_integrity;
4087 if (btrfs_fs_closing(fs_info) ||
4088 atomic_read(&fs_info->balance_pause_req) ||
4089 atomic_read(&fs_info->balance_cancel_req)) {
4094 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4095 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4099 * In case of mixed groups both data and meta should be picked,
4100 * and identical options should be given for both of them.
4102 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4103 if (mixed && (bctl->flags & allowed)) {
4104 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4105 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4106 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4108 "balance: mixed groups data and metadata options must be the same");
4115 * rw_devices will not change at the moment, device add/delete/replace
4116 * are excluded by EXCL_OP
4118 num_devices = fs_info->fs_devices->rw_devices;
4121 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4122 * special bit for it, to make it easier to distinguish. Thus we need
4123 * to set it manually, or balance would refuse the profile.
4125 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4126 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4127 if (num_devices >= btrfs_raid_array[i].devs_min)
4128 allowed |= btrfs_raid_array[i].bg_flag;
4130 if (validate_convert_profile(&bctl->data, allowed)) {
4132 "balance: invalid convert data profile %s",
4133 btrfs_bg_type_to_raid_name(bctl->data.target));
4137 if (validate_convert_profile(&bctl->meta, allowed)) {
4139 "balance: invalid convert metadata profile %s",
4140 btrfs_bg_type_to_raid_name(bctl->meta.target));
4144 if (validate_convert_profile(&bctl->sys, allowed)) {
4146 "balance: invalid convert system profile %s",
4147 btrfs_bg_type_to_raid_name(bctl->sys.target));
4153 * Allow to reduce metadata or system integrity only if force set for
4154 * profiles with redundancy (copies, parity)
4157 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4158 if (btrfs_raid_array[i].ncopies >= 2 ||
4159 btrfs_raid_array[i].tolerated_failures >= 1)
4160 allowed |= btrfs_raid_array[i].bg_flag;
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)) {
4197 "balance: metadata profile %s has lower redundancy than data profile %s",
4198 btrfs_bg_type_to_raid_name(meta_target),
4199 btrfs_bg_type_to_raid_name(data_target));
4202 if (fs_info->send_in_progress) {
4203 btrfs_warn_rl(fs_info,
4204 "cannot run balance while send operations are in progress (%d in progress)",
4205 fs_info->send_in_progress);
4210 ret = insert_balance_item(fs_info, bctl);
4211 if (ret && ret != -EEXIST)
4214 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4215 BUG_ON(ret == -EEXIST);
4216 BUG_ON(fs_info->balance_ctl);
4217 spin_lock(&fs_info->balance_lock);
4218 fs_info->balance_ctl = bctl;
4219 spin_unlock(&fs_info->balance_lock);
4221 BUG_ON(ret != -EEXIST);
4222 spin_lock(&fs_info->balance_lock);
4223 update_balance_args(bctl);
4224 spin_unlock(&fs_info->balance_lock);
4227 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4228 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4229 describe_balance_start_or_resume(fs_info);
4230 mutex_unlock(&fs_info->balance_mutex);
4232 ret = __btrfs_balance(fs_info);
4234 mutex_lock(&fs_info->balance_mutex);
4235 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4236 btrfs_info(fs_info, "balance: paused");
4237 else if (ret == -ECANCELED && atomic_read(&fs_info->balance_cancel_req))
4238 btrfs_info(fs_info, "balance: canceled");
4240 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4242 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4245 memset(bargs, 0, sizeof(*bargs));
4246 btrfs_update_ioctl_balance_args(fs_info, bargs);
4249 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4250 balance_need_close(fs_info)) {
4251 reset_balance_state(fs_info);
4252 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4255 wake_up(&fs_info->balance_wait_q);
4259 if (bctl->flags & BTRFS_BALANCE_RESUME)
4260 reset_balance_state(fs_info);
4263 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4268 static int balance_kthread(void *data)
4270 struct btrfs_fs_info *fs_info = data;
4273 mutex_lock(&fs_info->balance_mutex);
4274 if (fs_info->balance_ctl)
4275 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4276 mutex_unlock(&fs_info->balance_mutex);
4281 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4283 struct task_struct *tsk;
4285 mutex_lock(&fs_info->balance_mutex);
4286 if (!fs_info->balance_ctl) {
4287 mutex_unlock(&fs_info->balance_mutex);
4290 mutex_unlock(&fs_info->balance_mutex);
4292 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4293 btrfs_info(fs_info, "balance: resume skipped");
4298 * A ro->rw remount sequence should continue with the paused balance
4299 * regardless of who pauses it, system or the user as of now, so set
4302 spin_lock(&fs_info->balance_lock);
4303 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4304 spin_unlock(&fs_info->balance_lock);
4306 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4307 return PTR_ERR_OR_ZERO(tsk);
4310 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4312 struct btrfs_balance_control *bctl;
4313 struct btrfs_balance_item *item;
4314 struct btrfs_disk_balance_args disk_bargs;
4315 struct btrfs_path *path;
4316 struct extent_buffer *leaf;
4317 struct btrfs_key key;
4320 path = btrfs_alloc_path();
4324 key.objectid = BTRFS_BALANCE_OBJECTID;
4325 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4328 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4331 if (ret > 0) { /* ret = -ENOENT; */
4336 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4342 leaf = path->nodes[0];
4343 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4345 bctl->flags = btrfs_balance_flags(leaf, item);
4346 bctl->flags |= BTRFS_BALANCE_RESUME;
4348 btrfs_balance_data(leaf, item, &disk_bargs);
4349 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4350 btrfs_balance_meta(leaf, item, &disk_bargs);
4351 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4352 btrfs_balance_sys(leaf, item, &disk_bargs);
4353 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4356 * This should never happen, as the paused balance state is recovered
4357 * during mount without any chance of other exclusive ops to collide.
4359 * This gives the exclusive op status to balance and keeps in paused
4360 * state until user intervention (cancel or umount). If the ownership
4361 * cannot be assigned, show a message but do not fail. The balance
4362 * is in a paused state and must have fs_info::balance_ctl properly
4365 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4367 "balance: cannot set exclusive op status, resume manually");
4369 mutex_lock(&fs_info->balance_mutex);
4370 BUG_ON(fs_info->balance_ctl);
4371 spin_lock(&fs_info->balance_lock);
4372 fs_info->balance_ctl = bctl;
4373 spin_unlock(&fs_info->balance_lock);
4374 mutex_unlock(&fs_info->balance_mutex);
4376 btrfs_free_path(path);
4380 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4384 mutex_lock(&fs_info->balance_mutex);
4385 if (!fs_info->balance_ctl) {
4386 mutex_unlock(&fs_info->balance_mutex);
4390 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4391 atomic_inc(&fs_info->balance_pause_req);
4392 mutex_unlock(&fs_info->balance_mutex);
4394 wait_event(fs_info->balance_wait_q,
4395 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4397 mutex_lock(&fs_info->balance_mutex);
4398 /* we are good with balance_ctl ripped off from under us */
4399 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4400 atomic_dec(&fs_info->balance_pause_req);
4405 mutex_unlock(&fs_info->balance_mutex);
4409 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4411 mutex_lock(&fs_info->balance_mutex);
4412 if (!fs_info->balance_ctl) {
4413 mutex_unlock(&fs_info->balance_mutex);
4418 * A paused balance with the item stored on disk can be resumed at
4419 * mount time if the mount is read-write. Otherwise it's still paused
4420 * and we must not allow cancelling as it deletes the item.
4422 if (sb_rdonly(fs_info->sb)) {
4423 mutex_unlock(&fs_info->balance_mutex);
4427 atomic_inc(&fs_info->balance_cancel_req);
4429 * if we are running just wait and return, balance item is
4430 * deleted in btrfs_balance in this case
4432 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4433 mutex_unlock(&fs_info->balance_mutex);
4434 wait_event(fs_info->balance_wait_q,
4435 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4436 mutex_lock(&fs_info->balance_mutex);
4438 mutex_unlock(&fs_info->balance_mutex);
4440 * Lock released to allow other waiters to continue, we'll
4441 * reexamine the status again.
4443 mutex_lock(&fs_info->balance_mutex);
4445 if (fs_info->balance_ctl) {
4446 reset_balance_state(fs_info);
4447 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4448 btrfs_info(fs_info, "balance: canceled");
4452 BUG_ON(fs_info->balance_ctl ||
4453 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4454 atomic_dec(&fs_info->balance_cancel_req);
4455 mutex_unlock(&fs_info->balance_mutex);
4459 static int btrfs_uuid_scan_kthread(void *data)
4461 struct btrfs_fs_info *fs_info = data;
4462 struct btrfs_root *root = fs_info->tree_root;
4463 struct btrfs_key key;
4464 struct btrfs_path *path = NULL;
4466 struct extent_buffer *eb;
4468 struct btrfs_root_item root_item;
4470 struct btrfs_trans_handle *trans = NULL;
4472 path = btrfs_alloc_path();
4479 key.type = BTRFS_ROOT_ITEM_KEY;
4483 ret = btrfs_search_forward(root, &key, path,
4484 BTRFS_OLDEST_GENERATION);
4491 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4492 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4493 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4494 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4497 eb = path->nodes[0];
4498 slot = path->slots[0];
4499 item_size = btrfs_item_size_nr(eb, slot);
4500 if (item_size < sizeof(root_item))
4503 read_extent_buffer(eb, &root_item,
4504 btrfs_item_ptr_offset(eb, slot),
4505 (int)sizeof(root_item));
4506 if (btrfs_root_refs(&root_item) == 0)
4509 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4510 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4514 btrfs_release_path(path);
4516 * 1 - subvol uuid item
4517 * 1 - received_subvol uuid item
4519 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4520 if (IS_ERR(trans)) {
4521 ret = PTR_ERR(trans);
4529 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4530 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4531 BTRFS_UUID_KEY_SUBVOL,
4534 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4540 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4541 ret = btrfs_uuid_tree_add(trans,
4542 root_item.received_uuid,
4543 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4546 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4554 ret = btrfs_end_transaction(trans);
4560 btrfs_release_path(path);
4561 if (key.offset < (u64)-1) {
4563 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4565 key.type = BTRFS_ROOT_ITEM_KEY;
4566 } else if (key.objectid < (u64)-1) {
4568 key.type = BTRFS_ROOT_ITEM_KEY;
4577 btrfs_free_path(path);
4578 if (trans && !IS_ERR(trans))
4579 btrfs_end_transaction(trans);
4581 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4583 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4584 up(&fs_info->uuid_tree_rescan_sem);
4589 * Callback for btrfs_uuid_tree_iterate().
4591 * 0 check succeeded, the entry is not outdated.
4592 * < 0 if an error occurred.
4593 * > 0 if the check failed, which means the caller shall remove the entry.
4595 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4596 u8 *uuid, u8 type, u64 subid)
4598 struct btrfs_key key;
4600 struct btrfs_root *subvol_root;
4602 if (type != BTRFS_UUID_KEY_SUBVOL &&
4603 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4606 key.objectid = subid;
4607 key.type = BTRFS_ROOT_ITEM_KEY;
4608 key.offset = (u64)-1;
4609 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4610 if (IS_ERR(subvol_root)) {
4611 ret = PTR_ERR(subvol_root);
4618 case BTRFS_UUID_KEY_SUBVOL:
4619 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4622 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4623 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4633 static int btrfs_uuid_rescan_kthread(void *data)
4635 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4639 * 1st step is to iterate through the existing UUID tree and
4640 * to delete all entries that contain outdated data.
4641 * 2nd step is to add all missing entries to the UUID tree.
4643 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4645 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4646 up(&fs_info->uuid_tree_rescan_sem);
4649 return btrfs_uuid_scan_kthread(data);
4652 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4654 struct btrfs_trans_handle *trans;
4655 struct btrfs_root *tree_root = fs_info->tree_root;
4656 struct btrfs_root *uuid_root;
4657 struct task_struct *task;
4664 trans = btrfs_start_transaction(tree_root, 2);
4666 return PTR_ERR(trans);
4668 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4669 if (IS_ERR(uuid_root)) {
4670 ret = PTR_ERR(uuid_root);
4671 btrfs_abort_transaction(trans, ret);
4672 btrfs_end_transaction(trans);
4676 fs_info->uuid_root = uuid_root;
4678 ret = btrfs_commit_transaction(trans);
4682 down(&fs_info->uuid_tree_rescan_sem);
4683 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4685 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4686 btrfs_warn(fs_info, "failed to start uuid_scan task");
4687 up(&fs_info->uuid_tree_rescan_sem);
4688 return PTR_ERR(task);
4694 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4696 struct task_struct *task;
4698 down(&fs_info->uuid_tree_rescan_sem);
4699 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4701 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4702 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4703 up(&fs_info->uuid_tree_rescan_sem);
4704 return PTR_ERR(task);
4711 * shrinking a device means finding all of the device extents past
4712 * the new size, and then following the back refs to the chunks.
4713 * The chunk relocation code actually frees the device extent
4715 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4717 struct btrfs_fs_info *fs_info = device->fs_info;
4718 struct btrfs_root *root = fs_info->dev_root;
4719 struct btrfs_trans_handle *trans;
4720 struct btrfs_dev_extent *dev_extent = NULL;
4721 struct btrfs_path *path;
4727 bool retried = false;
4728 struct extent_buffer *l;
4729 struct btrfs_key key;
4730 struct btrfs_super_block *super_copy = fs_info->super_copy;
4731 u64 old_total = btrfs_super_total_bytes(super_copy);
4732 u64 old_size = btrfs_device_get_total_bytes(device);
4736 new_size = round_down(new_size, fs_info->sectorsize);
4738 diff = round_down(old_size - new_size, fs_info->sectorsize);
4740 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4743 path = btrfs_alloc_path();
4747 path->reada = READA_BACK;
4749 trans = btrfs_start_transaction(root, 0);
4750 if (IS_ERR(trans)) {
4751 btrfs_free_path(path);
4752 return PTR_ERR(trans);
4755 mutex_lock(&fs_info->chunk_mutex);
4757 btrfs_device_set_total_bytes(device, new_size);
4758 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4759 device->fs_devices->total_rw_bytes -= diff;
4760 atomic64_sub(diff, &fs_info->free_chunk_space);
4764 * Once the device's size has been set to the new size, ensure all
4765 * in-memory chunks are synced to disk so that the loop below sees them
4766 * and relocates them accordingly.
4768 if (contains_pending_extent(device, &start, diff)) {
4769 mutex_unlock(&fs_info->chunk_mutex);
4770 ret = btrfs_commit_transaction(trans);
4774 mutex_unlock(&fs_info->chunk_mutex);
4775 btrfs_end_transaction(trans);
4779 key.objectid = device->devid;
4780 key.offset = (u64)-1;
4781 key.type = BTRFS_DEV_EXTENT_KEY;
4784 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4785 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4787 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4791 ret = btrfs_previous_item(root, path, 0, key.type);
4793 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4798 btrfs_release_path(path);
4803 slot = path->slots[0];
4804 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4806 if (key.objectid != device->devid) {
4807 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4808 btrfs_release_path(path);
4812 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4813 length = btrfs_dev_extent_length(l, dev_extent);
4815 if (key.offset + length <= new_size) {
4816 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4817 btrfs_release_path(path);
4821 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4822 btrfs_release_path(path);
4825 * We may be relocating the only data chunk we have,
4826 * which could potentially end up with losing data's
4827 * raid profile, so lets allocate an empty one in
4830 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4832 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4836 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4837 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4838 if (ret == -ENOSPC) {
4841 if (ret == -ETXTBSY) {
4843 "could not shrink block group %llu due to active swapfile",
4848 } while (key.offset-- > 0);
4850 if (failed && !retried) {
4854 } else if (failed && retried) {
4859 /* Shrinking succeeded, else we would be at "done". */
4860 trans = btrfs_start_transaction(root, 0);
4861 if (IS_ERR(trans)) {
4862 ret = PTR_ERR(trans);
4866 mutex_lock(&fs_info->chunk_mutex);
4867 btrfs_device_set_disk_total_bytes(device, new_size);
4868 if (list_empty(&device->post_commit_list))
4869 list_add_tail(&device->post_commit_list,
4870 &trans->transaction->dev_update_list);
4872 WARN_ON(diff > old_total);
4873 btrfs_set_super_total_bytes(super_copy,
4874 round_down(old_total - diff, fs_info->sectorsize));
4875 mutex_unlock(&fs_info->chunk_mutex);
4877 /* Now btrfs_update_device() will change the on-disk size. */
4878 ret = btrfs_update_device(trans, device);
4880 btrfs_abort_transaction(trans, ret);
4881 btrfs_end_transaction(trans);
4883 ret = btrfs_commit_transaction(trans);
4886 btrfs_free_path(path);
4888 mutex_lock(&fs_info->chunk_mutex);
4889 btrfs_device_set_total_bytes(device, old_size);
4890 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4891 device->fs_devices->total_rw_bytes += diff;
4892 atomic64_add(diff, &fs_info->free_chunk_space);
4893 mutex_unlock(&fs_info->chunk_mutex);
4898 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4899 struct btrfs_key *key,
4900 struct btrfs_chunk *chunk, int item_size)
4902 struct btrfs_super_block *super_copy = fs_info->super_copy;
4903 struct btrfs_disk_key disk_key;
4907 mutex_lock(&fs_info->chunk_mutex);
4908 array_size = btrfs_super_sys_array_size(super_copy);
4909 if (array_size + item_size + sizeof(disk_key)
4910 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4911 mutex_unlock(&fs_info->chunk_mutex);
4915 ptr = super_copy->sys_chunk_array + array_size;
4916 btrfs_cpu_key_to_disk(&disk_key, key);
4917 memcpy(ptr, &disk_key, sizeof(disk_key));
4918 ptr += sizeof(disk_key);
4919 memcpy(ptr, chunk, item_size);
4920 item_size += sizeof(disk_key);
4921 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4922 mutex_unlock(&fs_info->chunk_mutex);
4928 * sort the devices in descending order by max_avail, total_avail
4930 static int btrfs_cmp_device_info(const void *a, const void *b)
4932 const struct btrfs_device_info *di_a = a;
4933 const struct btrfs_device_info *di_b = b;
4935 if (di_a->max_avail > di_b->max_avail)
4937 if (di_a->max_avail < di_b->max_avail)
4939 if (di_a->total_avail > di_b->total_avail)
4941 if (di_a->total_avail < di_b->total_avail)
4946 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4948 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4951 btrfs_set_fs_incompat(info, RAID56);
4954 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4955 u64 start, u64 type)
4957 struct btrfs_fs_info *info = trans->fs_info;
4958 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4959 struct btrfs_device *device;
4960 struct map_lookup *map = NULL;
4961 struct extent_map_tree *em_tree;
4962 struct extent_map *em;
4963 struct btrfs_device_info *devices_info = NULL;
4965 int num_stripes; /* total number of stripes to allocate */
4966 int data_stripes; /* number of stripes that count for
4968 int sub_stripes; /* sub_stripes info for map */
4969 int dev_stripes; /* stripes per dev */
4970 int devs_max; /* max devs to use */
4971 int devs_min; /* min devs needed */
4972 int devs_increment; /* ndevs has to be a multiple of this */
4973 int ncopies; /* how many copies to data has */
4974 int nparity; /* number of stripes worth of bytes to
4975 store parity information */
4977 u64 max_stripe_size;
4986 BUG_ON(!alloc_profile_is_valid(type, 0));
4988 if (list_empty(&fs_devices->alloc_list)) {
4989 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4990 btrfs_debug(info, "%s: no writable device", __func__);
4994 index = btrfs_bg_flags_to_raid_index(type);
4996 sub_stripes = btrfs_raid_array[index].sub_stripes;
4997 dev_stripes = btrfs_raid_array[index].dev_stripes;
4998 devs_max = btrfs_raid_array[index].devs_max;
5000 devs_max = BTRFS_MAX_DEVS(info);
5001 devs_min = btrfs_raid_array[index].devs_min;
5002 devs_increment = btrfs_raid_array[index].devs_increment;
5003 ncopies = btrfs_raid_array[index].ncopies;
5004 nparity = btrfs_raid_array[index].nparity;
5006 if (type & BTRFS_BLOCK_GROUP_DATA) {
5007 max_stripe_size = SZ_1G;
5008 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
5009 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5010 /* for larger filesystems, use larger metadata chunks */
5011 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
5012 max_stripe_size = SZ_1G;
5014 max_stripe_size = SZ_256M;
5015 max_chunk_size = max_stripe_size;
5016 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5017 max_stripe_size = SZ_32M;
5018 max_chunk_size = 2 * max_stripe_size;
5019 devs_max = min_t(int, devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
5021 btrfs_err(info, "invalid chunk type 0x%llx requested",
5026 /* We don't want a chunk larger than 10% of writable space */
5027 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
5030 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5036 * in the first pass through the devices list, we gather information
5037 * about the available holes on each device.
5040 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5044 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5046 "BTRFS: read-only device in alloc_list\n");
5050 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5051 &device->dev_state) ||
5052 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5055 if (device->total_bytes > device->bytes_used)
5056 total_avail = device->total_bytes - device->bytes_used;
5060 /* If there is no space on this device, skip it. */
5061 if (total_avail == 0)
5064 ret = find_free_dev_extent(device,
5065 max_stripe_size * dev_stripes,
5066 &dev_offset, &max_avail);
5067 if (ret && ret != -ENOSPC)
5071 max_avail = max_stripe_size * dev_stripes;
5073 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
5074 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5076 "%s: devid %llu has no free space, have=%llu want=%u",
5077 __func__, device->devid, max_avail,
5078 BTRFS_STRIPE_LEN * dev_stripes);
5082 if (ndevs == fs_devices->rw_devices) {
5083 WARN(1, "%s: found more than %llu devices\n",
5084 __func__, fs_devices->rw_devices);
5087 devices_info[ndevs].dev_offset = dev_offset;
5088 devices_info[ndevs].max_avail = max_avail;
5089 devices_info[ndevs].total_avail = total_avail;
5090 devices_info[ndevs].dev = device;
5095 * now sort the devices by hole size / available space
5097 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5098 btrfs_cmp_device_info, NULL);
5100 /* round down to number of usable stripes */
5101 ndevs = round_down(ndevs, devs_increment);
5103 if (ndevs < devs_min) {
5105 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5107 "%s: not enough devices with free space: have=%d minimum required=%d",
5108 __func__, ndevs, devs_min);
5113 ndevs = min(ndevs, devs_max);
5116 * The primary goal is to maximize the number of stripes, so use as
5117 * many devices as possible, even if the stripes are not maximum sized.
5119 * The DUP profile stores more than one stripe per device, the
5120 * max_avail is the total size so we have to adjust.
5122 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
5123 num_stripes = ndevs * dev_stripes;
5126 * this will have to be fixed for RAID1 and RAID10 over
5129 data_stripes = (num_stripes - nparity) / ncopies;
5132 * Use the number of data stripes to figure out how big this chunk
5133 * is really going to be in terms of logical address space,
5134 * and compare that answer with the max chunk size. If it's higher,
5135 * we try to reduce stripe_size.
5137 if (stripe_size * data_stripes > max_chunk_size) {
5139 * Reduce stripe_size, round it up to a 16MB boundary again and
5140 * then use it, unless it ends up being even bigger than the
5141 * previous value we had already.
5143 stripe_size = min(round_up(div_u64(max_chunk_size,
5144 data_stripes), SZ_16M),
5148 /* align to BTRFS_STRIPE_LEN */
5149 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
5151 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5156 map->num_stripes = num_stripes;
5158 for (i = 0; i < ndevs; ++i) {
5159 for (j = 0; j < dev_stripes; ++j) {
5160 int s = i * dev_stripes + j;
5161 map->stripes[s].dev = devices_info[i].dev;
5162 map->stripes[s].physical = devices_info[i].dev_offset +
5166 map->stripe_len = BTRFS_STRIPE_LEN;
5167 map->io_align = BTRFS_STRIPE_LEN;
5168 map->io_width = BTRFS_STRIPE_LEN;
5170 map->sub_stripes = sub_stripes;
5172 chunk_size = stripe_size * data_stripes;
5174 trace_btrfs_chunk_alloc(info, map, start, chunk_size);
5176 em = alloc_extent_map();
5182 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5183 em->map_lookup = map;
5185 em->len = chunk_size;
5186 em->block_start = 0;
5187 em->block_len = em->len;
5188 em->orig_block_len = stripe_size;
5190 em_tree = &info->mapping_tree;
5191 write_lock(&em_tree->lock);
5192 ret = add_extent_mapping(em_tree, em, 0);
5194 write_unlock(&em_tree->lock);
5195 free_extent_map(em);
5198 write_unlock(&em_tree->lock);
5200 ret = btrfs_make_block_group(trans, 0, type, start, chunk_size);
5202 goto error_del_extent;
5204 for (i = 0; i < map->num_stripes; i++) {
5205 struct btrfs_device *dev = map->stripes[i].dev;
5207 btrfs_device_set_bytes_used(dev, dev->bytes_used + stripe_size);
5208 if (list_empty(&dev->post_commit_list))
5209 list_add_tail(&dev->post_commit_list,
5210 &trans->transaction->dev_update_list);
5213 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
5215 free_extent_map(em);
5216 check_raid56_incompat_flag(info, type);
5218 kfree(devices_info);
5222 write_lock(&em_tree->lock);
5223 remove_extent_mapping(em_tree, em);
5224 write_unlock(&em_tree->lock);
5226 /* One for our allocation */
5227 free_extent_map(em);
5228 /* One for the tree reference */
5229 free_extent_map(em);
5231 kfree(devices_info);
5235 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5236 u64 chunk_offset, u64 chunk_size)
5238 struct btrfs_fs_info *fs_info = trans->fs_info;
5239 struct btrfs_root *extent_root = fs_info->extent_root;
5240 struct btrfs_root *chunk_root = fs_info->chunk_root;
5241 struct btrfs_key key;
5242 struct btrfs_device *device;
5243 struct btrfs_chunk *chunk;
5244 struct btrfs_stripe *stripe;
5245 struct extent_map *em;
5246 struct map_lookup *map;
5253 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5257 map = em->map_lookup;
5258 item_size = btrfs_chunk_item_size(map->num_stripes);
5259 stripe_size = em->orig_block_len;
5261 chunk = kzalloc(item_size, GFP_NOFS);
5268 * Take the device list mutex to prevent races with the final phase of
5269 * a device replace operation that replaces the device object associated
5270 * with the map's stripes, because the device object's id can change
5271 * at any time during that final phase of the device replace operation
5272 * (dev-replace.c:btrfs_dev_replace_finishing()).
5274 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5275 for (i = 0; i < map->num_stripes; i++) {
5276 device = map->stripes[i].dev;
5277 dev_offset = map->stripes[i].physical;
5279 ret = btrfs_update_device(trans, device);
5282 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5283 dev_offset, stripe_size);
5288 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5292 stripe = &chunk->stripe;
5293 for (i = 0; i < map->num_stripes; i++) {
5294 device = map->stripes[i].dev;
5295 dev_offset = map->stripes[i].physical;
5297 btrfs_set_stack_stripe_devid(stripe, device->devid);
5298 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5299 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5302 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5304 btrfs_set_stack_chunk_length(chunk, chunk_size);
5305 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5306 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5307 btrfs_set_stack_chunk_type(chunk, map->type);
5308 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5309 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5310 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5311 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5312 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5314 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5315 key.type = BTRFS_CHUNK_ITEM_KEY;
5316 key.offset = chunk_offset;
5318 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5319 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5321 * TODO: Cleanup of inserted chunk root in case of
5324 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5329 free_extent_map(em);
5334 * Chunk allocation falls into two parts. The first part does work
5335 * that makes the new allocated chunk usable, but does not do any operation
5336 * that modifies the chunk tree. The second part does the work that
5337 * requires modifying the chunk tree. This division is important for the
5338 * bootstrap process of adding storage to a seed btrfs.
5340 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5344 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5345 chunk_offset = find_next_chunk(trans->fs_info);
5346 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5349 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5351 struct btrfs_fs_info *fs_info = trans->fs_info;
5353 u64 sys_chunk_offset;
5357 chunk_offset = find_next_chunk(fs_info);
5358 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5359 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5363 sys_chunk_offset = find_next_chunk(fs_info);
5364 alloc_profile = btrfs_system_alloc_profile(fs_info);
5365 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5369 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5371 const int index = btrfs_bg_flags_to_raid_index(map->type);
5373 return btrfs_raid_array[index].tolerated_failures;
5376 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5378 struct extent_map *em;
5379 struct map_lookup *map;
5384 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5388 map = em->map_lookup;
5389 for (i = 0; i < map->num_stripes; i++) {
5390 if (test_bit(BTRFS_DEV_STATE_MISSING,
5391 &map->stripes[i].dev->dev_state)) {
5395 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5396 &map->stripes[i].dev->dev_state)) {
5403 * If the number of missing devices is larger than max errors,
5404 * we can not write the data into that chunk successfully, so
5407 if (miss_ndevs > btrfs_chunk_max_errors(map))
5410 free_extent_map(em);
5414 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5416 struct extent_map *em;
5419 write_lock(&tree->lock);
5420 em = lookup_extent_mapping(tree, 0, (u64)-1);
5422 remove_extent_mapping(tree, em);
5423 write_unlock(&tree->lock);
5427 free_extent_map(em);
5428 /* once for the tree */
5429 free_extent_map(em);
5433 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5435 struct extent_map *em;
5436 struct map_lookup *map;
5439 em = btrfs_get_chunk_map(fs_info, logical, len);
5442 * We could return errors for these cases, but that could get
5443 * ugly and we'd probably do the same thing which is just not do
5444 * anything else and exit, so return 1 so the callers don't try
5445 * to use other copies.
5449 map = em->map_lookup;
5450 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5451 ret = map->num_stripes;
5452 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5453 ret = map->sub_stripes;
5454 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5456 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5458 * There could be two corrupted data stripes, we need
5459 * to loop retry in order to rebuild the correct data.
5461 * Fail a stripe at a time on every retry except the
5462 * stripe under reconstruction.
5464 ret = map->num_stripes;
5467 free_extent_map(em);
5469 down_read(&fs_info->dev_replace.rwsem);
5470 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5471 fs_info->dev_replace.tgtdev)
5473 up_read(&fs_info->dev_replace.rwsem);
5478 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5481 struct extent_map *em;
5482 struct map_lookup *map;
5483 unsigned long len = fs_info->sectorsize;
5485 em = btrfs_get_chunk_map(fs_info, logical, len);
5487 if (!WARN_ON(IS_ERR(em))) {
5488 map = em->map_lookup;
5489 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5490 len = map->stripe_len * nr_data_stripes(map);
5491 free_extent_map(em);
5496 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5498 struct extent_map *em;
5499 struct map_lookup *map;
5502 em = btrfs_get_chunk_map(fs_info, logical, len);
5504 if(!WARN_ON(IS_ERR(em))) {
5505 map = em->map_lookup;
5506 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5508 free_extent_map(em);
5513 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5514 struct map_lookup *map, int first,
5515 int dev_replace_is_ongoing)
5519 int preferred_mirror;
5521 struct btrfs_device *srcdev;
5524 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5526 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5527 num_stripes = map->sub_stripes;
5529 num_stripes = map->num_stripes;
5531 preferred_mirror = first + current->pid % num_stripes;
5533 if (dev_replace_is_ongoing &&
5534 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5535 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5536 srcdev = fs_info->dev_replace.srcdev;
5541 * try to avoid the drive that is the source drive for a
5542 * dev-replace procedure, only choose it if no other non-missing
5543 * mirror is available
5545 for (tolerance = 0; tolerance < 2; tolerance++) {
5546 if (map->stripes[preferred_mirror].dev->bdev &&
5547 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5548 return preferred_mirror;
5549 for (i = first; i < first + num_stripes; i++) {
5550 if (map->stripes[i].dev->bdev &&
5551 (tolerance || map->stripes[i].dev != srcdev))
5556 /* we couldn't find one that doesn't fail. Just return something
5557 * and the io error handling code will clean up eventually
5559 return preferred_mirror;
5562 static inline int parity_smaller(u64 a, u64 b)
5567 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5568 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5570 struct btrfs_bio_stripe s;
5577 for (i = 0; i < num_stripes - 1; i++) {
5578 if (parity_smaller(bbio->raid_map[i],
5579 bbio->raid_map[i+1])) {
5580 s = bbio->stripes[i];
5581 l = bbio->raid_map[i];
5582 bbio->stripes[i] = bbio->stripes[i+1];
5583 bbio->raid_map[i] = bbio->raid_map[i+1];
5584 bbio->stripes[i+1] = s;
5585 bbio->raid_map[i+1] = l;
5593 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5595 struct btrfs_bio *bbio = kzalloc(
5596 /* the size of the btrfs_bio */
5597 sizeof(struct btrfs_bio) +
5598 /* plus the variable array for the stripes */
5599 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5600 /* plus the variable array for the tgt dev */
5601 sizeof(int) * (real_stripes) +
5603 * plus the raid_map, which includes both the tgt dev
5606 sizeof(u64) * (total_stripes),
5607 GFP_NOFS|__GFP_NOFAIL);
5609 atomic_set(&bbio->error, 0);
5610 refcount_set(&bbio->refs, 1);
5615 void btrfs_get_bbio(struct btrfs_bio *bbio)
5617 WARN_ON(!refcount_read(&bbio->refs));
5618 refcount_inc(&bbio->refs);
5621 void btrfs_put_bbio(struct btrfs_bio *bbio)
5625 if (refcount_dec_and_test(&bbio->refs))
5629 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5631 * Please note that, discard won't be sent to target device of device
5634 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5635 u64 logical, u64 length,
5636 struct btrfs_bio **bbio_ret)
5638 struct extent_map *em;
5639 struct map_lookup *map;
5640 struct btrfs_bio *bbio;
5644 u64 stripe_end_offset;
5651 u32 sub_stripes = 0;
5652 u64 stripes_per_dev = 0;
5653 u32 remaining_stripes = 0;
5654 u32 last_stripe = 0;
5658 /* discard always return a bbio */
5661 em = btrfs_get_chunk_map(fs_info, logical, length);
5665 map = em->map_lookup;
5666 /* we don't discard raid56 yet */
5667 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5672 offset = logical - em->start;
5673 length = min_t(u64, em->len - offset, length);
5675 stripe_len = map->stripe_len;
5677 * stripe_nr counts the total number of stripes we have to stride
5678 * to get to this block
5680 stripe_nr = div64_u64(offset, stripe_len);
5682 /* stripe_offset is the offset of this block in its stripe */
5683 stripe_offset = offset - stripe_nr * stripe_len;
5685 stripe_nr_end = round_up(offset + length, map->stripe_len);
5686 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5687 stripe_cnt = stripe_nr_end - stripe_nr;
5688 stripe_end_offset = stripe_nr_end * map->stripe_len -
5691 * after this, stripe_nr is the number of stripes on this
5692 * device we have to walk to find the data, and stripe_index is
5693 * the number of our device in the stripe array
5697 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5698 BTRFS_BLOCK_GROUP_RAID10)) {
5699 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5702 sub_stripes = map->sub_stripes;
5704 factor = map->num_stripes / sub_stripes;
5705 num_stripes = min_t(u64, map->num_stripes,
5706 sub_stripes * stripe_cnt);
5707 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5708 stripe_index *= sub_stripes;
5709 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5710 &remaining_stripes);
5711 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5712 last_stripe *= sub_stripes;
5713 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5714 BTRFS_BLOCK_GROUP_DUP)) {
5715 num_stripes = map->num_stripes;
5717 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5721 bbio = alloc_btrfs_bio(num_stripes, 0);
5727 for (i = 0; i < num_stripes; i++) {
5728 bbio->stripes[i].physical =
5729 map->stripes[stripe_index].physical +
5730 stripe_offset + stripe_nr * map->stripe_len;
5731 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5733 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5734 BTRFS_BLOCK_GROUP_RAID10)) {
5735 bbio->stripes[i].length = stripes_per_dev *
5738 if (i / sub_stripes < remaining_stripes)
5739 bbio->stripes[i].length +=
5743 * Special for the first stripe and
5746 * |-------|...|-------|
5750 if (i < sub_stripes)
5751 bbio->stripes[i].length -=
5754 if (stripe_index >= last_stripe &&
5755 stripe_index <= (last_stripe +
5757 bbio->stripes[i].length -=
5760 if (i == sub_stripes - 1)
5763 bbio->stripes[i].length = length;
5767 if (stripe_index == map->num_stripes) {
5774 bbio->map_type = map->type;
5775 bbio->num_stripes = num_stripes;
5777 free_extent_map(em);
5782 * In dev-replace case, for repair case (that's the only case where the mirror
5783 * is selected explicitly when calling btrfs_map_block), blocks left of the
5784 * left cursor can also be read from the target drive.
5786 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5788 * For READ, it also needs to be supported using the same mirror number.
5790 * If the requested block is not left of the left cursor, EIO is returned. This
5791 * can happen because btrfs_num_copies() returns one more in the dev-replace
5794 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5795 u64 logical, u64 length,
5796 u64 srcdev_devid, int *mirror_num,
5799 struct btrfs_bio *bbio = NULL;
5801 int index_srcdev = 0;
5803 u64 physical_of_found = 0;
5807 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5808 logical, &length, &bbio, 0, 0);
5810 ASSERT(bbio == NULL);
5814 num_stripes = bbio->num_stripes;
5815 if (*mirror_num > num_stripes) {
5817 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5818 * that means that the requested area is not left of the left
5821 btrfs_put_bbio(bbio);
5826 * process the rest of the function using the mirror_num of the source
5827 * drive. Therefore look it up first. At the end, patch the device
5828 * pointer to the one of the target drive.
5830 for (i = 0; i < num_stripes; i++) {
5831 if (bbio->stripes[i].dev->devid != srcdev_devid)
5835 * In case of DUP, in order to keep it simple, only add the
5836 * mirror with the lowest physical address
5839 physical_of_found <= bbio->stripes[i].physical)
5844 physical_of_found = bbio->stripes[i].physical;
5847 btrfs_put_bbio(bbio);
5853 *mirror_num = index_srcdev + 1;
5854 *physical = physical_of_found;
5858 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5859 struct btrfs_bio **bbio_ret,
5860 struct btrfs_dev_replace *dev_replace,
5861 int *num_stripes_ret, int *max_errors_ret)
5863 struct btrfs_bio *bbio = *bbio_ret;
5864 u64 srcdev_devid = dev_replace->srcdev->devid;
5865 int tgtdev_indexes = 0;
5866 int num_stripes = *num_stripes_ret;
5867 int max_errors = *max_errors_ret;
5870 if (op == BTRFS_MAP_WRITE) {
5871 int index_where_to_add;
5874 * duplicate the write operations while the dev replace
5875 * procedure is running. Since the copying of the old disk to
5876 * the new disk takes place at run time while the filesystem is
5877 * mounted writable, the regular write operations to the old
5878 * disk have to be duplicated to go to the new disk as well.
5880 * Note that device->missing is handled by the caller, and that
5881 * the write to the old disk is already set up in the stripes
5884 index_where_to_add = num_stripes;
5885 for (i = 0; i < num_stripes; i++) {
5886 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5887 /* write to new disk, too */
5888 struct btrfs_bio_stripe *new =
5889 bbio->stripes + index_where_to_add;
5890 struct btrfs_bio_stripe *old =
5893 new->physical = old->physical;
5894 new->length = old->length;
5895 new->dev = dev_replace->tgtdev;
5896 bbio->tgtdev_map[i] = index_where_to_add;
5897 index_where_to_add++;
5902 num_stripes = index_where_to_add;
5903 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5904 int index_srcdev = 0;
5906 u64 physical_of_found = 0;
5909 * During the dev-replace procedure, the target drive can also
5910 * be used to read data in case it is needed to repair a corrupt
5911 * block elsewhere. This is possible if the requested area is
5912 * left of the left cursor. In this area, the target drive is a
5913 * full copy of the source drive.
5915 for (i = 0; i < num_stripes; i++) {
5916 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5918 * In case of DUP, in order to keep it simple,
5919 * only add the mirror with the lowest physical
5923 physical_of_found <=
5924 bbio->stripes[i].physical)
5928 physical_of_found = bbio->stripes[i].physical;
5932 struct btrfs_bio_stripe *tgtdev_stripe =
5933 bbio->stripes + num_stripes;
5935 tgtdev_stripe->physical = physical_of_found;
5936 tgtdev_stripe->length =
5937 bbio->stripes[index_srcdev].length;
5938 tgtdev_stripe->dev = dev_replace->tgtdev;
5939 bbio->tgtdev_map[index_srcdev] = num_stripes;
5946 *num_stripes_ret = num_stripes;
5947 *max_errors_ret = max_errors;
5948 bbio->num_tgtdevs = tgtdev_indexes;
5952 static bool need_full_stripe(enum btrfs_map_op op)
5954 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5958 * btrfs_get_io_geometry - calculates the geomery of a particular (address, len)
5959 * tuple. This information is used to calculate how big a
5960 * particular bio can get before it straddles a stripe.
5962 * @fs_info - the filesystem
5963 * @logical - address that we want to figure out the geometry of
5964 * @len - the length of IO we are going to perform, starting at @logical
5965 * @op - type of operation - write or read
5966 * @io_geom - pointer used to return values
5968 * Returns < 0 in case a chunk for the given logical address cannot be found,
5969 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
5971 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5972 u64 logical, u64 len, struct btrfs_io_geometry *io_geom)
5974 struct extent_map *em;
5975 struct map_lookup *map;
5980 u64 raid56_full_stripe_start = (u64)-1;
5984 ASSERT(op != BTRFS_MAP_DISCARD);
5986 em = btrfs_get_chunk_map(fs_info, logical, len);
5990 map = em->map_lookup;
5991 /* Offset of this logical address in the chunk */
5992 offset = logical - em->start;
5993 /* Len of a stripe in a chunk */
5994 stripe_len = map->stripe_len;
5995 /* Stripe wher this block falls in */
5996 stripe_nr = div64_u64(offset, stripe_len);
5997 /* Offset of stripe in the chunk */
5998 stripe_offset = stripe_nr * stripe_len;
5999 if (offset < stripe_offset) {
6001 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
6002 stripe_offset, offset, em->start, logical, stripe_len);
6007 /* stripe_offset is the offset of this block in its stripe */
6008 stripe_offset = offset - stripe_offset;
6009 data_stripes = nr_data_stripes(map);
6011 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6012 u64 max_len = stripe_len - stripe_offset;
6015 * In case of raid56, we need to know the stripe aligned start
6017 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6018 unsigned long full_stripe_len = stripe_len * data_stripes;
6019 raid56_full_stripe_start = offset;
6022 * Allow a write of a full stripe, but make sure we
6023 * don't allow straddling of stripes
6025 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6027 raid56_full_stripe_start *= full_stripe_len;
6030 * For writes to RAID[56], allow a full stripeset across
6031 * all disks. For other RAID types and for RAID[56]
6032 * reads, just allow a single stripe (on a single disk).
6034 if (op == BTRFS_MAP_WRITE) {
6035 max_len = stripe_len * data_stripes -
6036 (offset - raid56_full_stripe_start);
6039 len = min_t(u64, em->len - offset, max_len);
6041 len = em->len - offset;
6045 io_geom->offset = offset;
6046 io_geom->stripe_len = stripe_len;
6047 io_geom->stripe_nr = stripe_nr;
6048 io_geom->stripe_offset = stripe_offset;
6049 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6053 free_extent_map(em);
6057 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6058 enum btrfs_map_op op,
6059 u64 logical, u64 *length,
6060 struct btrfs_bio **bbio_ret,
6061 int mirror_num, int need_raid_map)
6063 struct extent_map *em;
6064 struct map_lookup *map;
6074 int tgtdev_indexes = 0;
6075 struct btrfs_bio *bbio = NULL;
6076 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6077 int dev_replace_is_ongoing = 0;
6078 int num_alloc_stripes;
6079 int patch_the_first_stripe_for_dev_replace = 0;
6080 u64 physical_to_patch_in_first_stripe = 0;
6081 u64 raid56_full_stripe_start = (u64)-1;
6082 struct btrfs_io_geometry geom;
6086 if (op == BTRFS_MAP_DISCARD)
6087 return __btrfs_map_block_for_discard(fs_info, logical,
6090 ret = btrfs_get_io_geometry(fs_info, op, logical, *length, &geom);
6094 em = btrfs_get_chunk_map(fs_info, logical, *length);
6095 ASSERT(!IS_ERR(em));
6096 map = em->map_lookup;
6099 stripe_len = geom.stripe_len;
6100 stripe_nr = geom.stripe_nr;
6101 stripe_offset = geom.stripe_offset;
6102 raid56_full_stripe_start = geom.raid56_stripe_offset;
6103 data_stripes = nr_data_stripes(map);
6105 down_read(&dev_replace->rwsem);
6106 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6108 * Hold the semaphore for read during the whole operation, write is
6109 * requested at commit time but must wait.
6111 if (!dev_replace_is_ongoing)
6112 up_read(&dev_replace->rwsem);
6114 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6115 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6116 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6117 dev_replace->srcdev->devid,
6119 &physical_to_patch_in_first_stripe);
6123 patch_the_first_stripe_for_dev_replace = 1;
6124 } else if (mirror_num > map->num_stripes) {
6130 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6131 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6133 if (!need_full_stripe(op))
6135 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6136 if (need_full_stripe(op))
6137 num_stripes = map->num_stripes;
6138 else if (mirror_num)
6139 stripe_index = mirror_num - 1;
6141 stripe_index = find_live_mirror(fs_info, map, 0,
6142 dev_replace_is_ongoing);
6143 mirror_num = stripe_index + 1;
6146 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6147 if (need_full_stripe(op)) {
6148 num_stripes = map->num_stripes;
6149 } else if (mirror_num) {
6150 stripe_index = mirror_num - 1;
6155 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6156 u32 factor = map->num_stripes / map->sub_stripes;
6158 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6159 stripe_index *= map->sub_stripes;
6161 if (need_full_stripe(op))
6162 num_stripes = map->sub_stripes;
6163 else if (mirror_num)
6164 stripe_index += mirror_num - 1;
6166 int old_stripe_index = stripe_index;
6167 stripe_index = find_live_mirror(fs_info, map,
6169 dev_replace_is_ongoing);
6170 mirror_num = stripe_index - old_stripe_index + 1;
6173 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6174 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6175 /* push stripe_nr back to the start of the full stripe */
6176 stripe_nr = div64_u64(raid56_full_stripe_start,
6177 stripe_len * data_stripes);
6179 /* RAID[56] write or recovery. Return all stripes */
6180 num_stripes = map->num_stripes;
6181 max_errors = nr_parity_stripes(map);
6183 *length = map->stripe_len;
6188 * Mirror #0 or #1 means the original data block.
6189 * Mirror #2 is RAID5 parity block.
6190 * Mirror #3 is RAID6 Q block.
6192 stripe_nr = div_u64_rem(stripe_nr,
6193 data_stripes, &stripe_index);
6195 stripe_index = data_stripes + mirror_num - 2;
6197 /* We distribute the parity blocks across stripes */
6198 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6200 if (!need_full_stripe(op) && mirror_num <= 1)
6205 * after this, stripe_nr is the number of stripes on this
6206 * device we have to walk to find the data, and stripe_index is
6207 * the number of our device in the stripe array
6209 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6211 mirror_num = stripe_index + 1;
6213 if (stripe_index >= map->num_stripes) {
6215 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6216 stripe_index, map->num_stripes);
6221 num_alloc_stripes = num_stripes;
6222 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6223 if (op == BTRFS_MAP_WRITE)
6224 num_alloc_stripes <<= 1;
6225 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6226 num_alloc_stripes++;
6227 tgtdev_indexes = num_stripes;
6230 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6235 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
6236 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
6238 /* build raid_map */
6239 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6240 (need_full_stripe(op) || mirror_num > 1)) {
6244 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6245 sizeof(struct btrfs_bio_stripe) *
6247 sizeof(int) * tgtdev_indexes);
6249 /* Work out the disk rotation on this stripe-set */
6250 div_u64_rem(stripe_nr, num_stripes, &rot);
6252 /* Fill in the logical address of each stripe */
6253 tmp = stripe_nr * data_stripes;
6254 for (i = 0; i < data_stripes; i++)
6255 bbio->raid_map[(i+rot) % num_stripes] =
6256 em->start + (tmp + i) * map->stripe_len;
6258 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6259 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6260 bbio->raid_map[(i+rot+1) % num_stripes] =
6265 for (i = 0; i < num_stripes; i++) {
6266 bbio->stripes[i].physical =
6267 map->stripes[stripe_index].physical +
6269 stripe_nr * map->stripe_len;
6270 bbio->stripes[i].dev =
6271 map->stripes[stripe_index].dev;
6275 if (need_full_stripe(op))
6276 max_errors = btrfs_chunk_max_errors(map);
6279 sort_parity_stripes(bbio, num_stripes);
6281 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6282 need_full_stripe(op)) {
6283 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6288 bbio->map_type = map->type;
6289 bbio->num_stripes = num_stripes;
6290 bbio->max_errors = max_errors;
6291 bbio->mirror_num = mirror_num;
6294 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6295 * mirror_num == num_stripes + 1 && dev_replace target drive is
6296 * available as a mirror
6298 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6299 WARN_ON(num_stripes > 1);
6300 bbio->stripes[0].dev = dev_replace->tgtdev;
6301 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6302 bbio->mirror_num = map->num_stripes + 1;
6305 if (dev_replace_is_ongoing) {
6306 lockdep_assert_held(&dev_replace->rwsem);
6307 /* Unlock and let waiting writers proceed */
6308 up_read(&dev_replace->rwsem);
6310 free_extent_map(em);
6314 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6315 u64 logical, u64 *length,
6316 struct btrfs_bio **bbio_ret, int mirror_num)
6318 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6322 /* For Scrub/replace */
6323 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6324 u64 logical, u64 *length,
6325 struct btrfs_bio **bbio_ret)
6327 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6330 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
6331 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
6333 struct extent_map *em;
6334 struct map_lookup *map;
6342 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
6346 map = em->map_lookup;
6348 rmap_len = map->stripe_len;
6350 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6351 length = div_u64(length, map->num_stripes / map->sub_stripes);
6352 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6353 length = div_u64(length, map->num_stripes);
6354 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6355 length = div_u64(length, nr_data_stripes(map));
6356 rmap_len = map->stripe_len * nr_data_stripes(map);
6359 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6360 BUG_ON(!buf); /* -ENOMEM */
6362 for (i = 0; i < map->num_stripes; i++) {
6363 if (map->stripes[i].physical > physical ||
6364 map->stripes[i].physical + length <= physical)
6367 stripe_nr = physical - map->stripes[i].physical;
6368 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6370 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6371 stripe_nr = stripe_nr * map->num_stripes + i;
6372 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6373 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6374 stripe_nr = stripe_nr * map->num_stripes + i;
6375 } /* else if RAID[56], multiply by nr_data_stripes().
6376 * Alternatively, just use rmap_len below instead of
6377 * map->stripe_len */
6379 bytenr = chunk_start + stripe_nr * rmap_len;
6380 WARN_ON(nr >= map->num_stripes);
6381 for (j = 0; j < nr; j++) {
6382 if (buf[j] == bytenr)
6386 WARN_ON(nr >= map->num_stripes);
6393 *stripe_len = rmap_len;
6395 free_extent_map(em);
6399 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6401 bio->bi_private = bbio->private;
6402 bio->bi_end_io = bbio->end_io;
6405 btrfs_put_bbio(bbio);
6408 static void btrfs_end_bio(struct bio *bio)
6410 struct btrfs_bio *bbio = bio->bi_private;
6411 int is_orig_bio = 0;
6413 if (bio->bi_status) {
6414 atomic_inc(&bbio->error);
6415 if (bio->bi_status == BLK_STS_IOERR ||
6416 bio->bi_status == BLK_STS_TARGET) {
6417 unsigned int stripe_index =
6418 btrfs_io_bio(bio)->stripe_index;
6419 struct btrfs_device *dev;
6421 BUG_ON(stripe_index >= bbio->num_stripes);
6422 dev = bbio->stripes[stripe_index].dev;
6424 if (bio_op(bio) == REQ_OP_WRITE)
6425 btrfs_dev_stat_inc_and_print(dev,
6426 BTRFS_DEV_STAT_WRITE_ERRS);
6427 else if (!(bio->bi_opf & REQ_RAHEAD))
6428 btrfs_dev_stat_inc_and_print(dev,
6429 BTRFS_DEV_STAT_READ_ERRS);
6430 if (bio->bi_opf & REQ_PREFLUSH)
6431 btrfs_dev_stat_inc_and_print(dev,
6432 BTRFS_DEV_STAT_FLUSH_ERRS);
6437 if (bio == bbio->orig_bio)
6440 btrfs_bio_counter_dec(bbio->fs_info);
6442 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6445 bio = bbio->orig_bio;
6448 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6449 /* only send an error to the higher layers if it is
6450 * beyond the tolerance of the btrfs bio
6452 if (atomic_read(&bbio->error) > bbio->max_errors) {
6453 bio->bi_status = BLK_STS_IOERR;
6456 * this bio is actually up to date, we didn't
6457 * go over the max number of errors
6459 bio->bi_status = BLK_STS_OK;
6462 btrfs_end_bbio(bbio, bio);
6463 } else if (!is_orig_bio) {
6469 * see run_scheduled_bios for a description of why bios are collected for
6472 * This will add one bio to the pending list for a device and make sure
6473 * the work struct is scheduled.
6475 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6478 struct btrfs_fs_info *fs_info = device->fs_info;
6479 int should_queue = 1;
6480 struct btrfs_pending_bios *pending_bios;
6482 /* don't bother with additional async steps for reads, right now */
6483 if (bio_op(bio) == REQ_OP_READ) {
6484 btrfsic_submit_bio(bio);
6488 WARN_ON(bio->bi_next);
6489 bio->bi_next = NULL;
6491 spin_lock(&device->io_lock);
6492 if (op_is_sync(bio->bi_opf))
6493 pending_bios = &device->pending_sync_bios;
6495 pending_bios = &device->pending_bios;
6497 if (pending_bios->tail)
6498 pending_bios->tail->bi_next = bio;
6500 pending_bios->tail = bio;
6501 if (!pending_bios->head)
6502 pending_bios->head = bio;
6503 if (device->running_pending)
6506 spin_unlock(&device->io_lock);
6509 btrfs_queue_work(fs_info->submit_workers, &device->work);
6512 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6513 u64 physical, int dev_nr, int async)
6515 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6516 struct btrfs_fs_info *fs_info = bbio->fs_info;
6518 bio->bi_private = bbio;
6519 btrfs_io_bio(bio)->stripe_index = dev_nr;
6520 bio->bi_end_io = btrfs_end_bio;
6521 bio->bi_iter.bi_sector = physical >> 9;
6522 btrfs_debug_in_rcu(fs_info,
6523 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6524 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6525 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6526 bio->bi_iter.bi_size);
6527 bio_set_dev(bio, dev->bdev);
6529 btrfs_bio_counter_inc_noblocked(fs_info);
6532 btrfs_schedule_bio(dev, bio);
6534 btrfsic_submit_bio(bio);
6537 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6539 atomic_inc(&bbio->error);
6540 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6541 /* Should be the original bio. */
6542 WARN_ON(bio != bbio->orig_bio);
6544 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6545 bio->bi_iter.bi_sector = logical >> 9;
6546 if (atomic_read(&bbio->error) > bbio->max_errors)
6547 bio->bi_status = BLK_STS_IOERR;
6549 bio->bi_status = BLK_STS_OK;
6550 btrfs_end_bbio(bbio, bio);
6554 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6555 int mirror_num, int async_submit)
6557 struct btrfs_device *dev;
6558 struct bio *first_bio = bio;
6559 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6565 struct btrfs_bio *bbio = NULL;
6567 length = bio->bi_iter.bi_size;
6568 map_length = length;
6570 btrfs_bio_counter_inc_blocked(fs_info);
6571 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6572 &map_length, &bbio, mirror_num, 1);
6574 btrfs_bio_counter_dec(fs_info);
6575 return errno_to_blk_status(ret);
6578 total_devs = bbio->num_stripes;
6579 bbio->orig_bio = first_bio;
6580 bbio->private = first_bio->bi_private;
6581 bbio->end_io = first_bio->bi_end_io;
6582 bbio->fs_info = fs_info;
6583 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6585 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6586 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6587 /* In this case, map_length has been set to the length of
6588 a single stripe; not the whole write */
6589 if (bio_op(bio) == REQ_OP_WRITE) {
6590 ret = raid56_parity_write(fs_info, bio, bbio,
6593 ret = raid56_parity_recover(fs_info, bio, bbio,
6594 map_length, mirror_num, 1);
6597 btrfs_bio_counter_dec(fs_info);
6598 return errno_to_blk_status(ret);
6601 if (map_length < length) {
6603 "mapping failed logical %llu bio len %llu len %llu",
6604 logical, length, map_length);
6608 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6609 dev = bbio->stripes[dev_nr].dev;
6610 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6612 (bio_op(first_bio) == REQ_OP_WRITE &&
6613 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6614 bbio_error(bbio, first_bio, logical);
6618 if (dev_nr < total_devs - 1)
6619 bio = btrfs_bio_clone(first_bio);
6623 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6624 dev_nr, async_submit);
6626 btrfs_bio_counter_dec(fs_info);
6631 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6634 * If devid and uuid are both specified, the match must be exact, otherwise
6635 * only devid is used.
6637 * If @seed is true, traverse through the seed devices.
6639 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6640 u64 devid, u8 *uuid, u8 *fsid,
6643 struct btrfs_device *device;
6645 while (fs_devices) {
6647 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6648 list_for_each_entry(device, &fs_devices->devices,
6650 if (device->devid == devid &&
6651 (!uuid || memcmp(device->uuid, uuid,
6652 BTRFS_UUID_SIZE) == 0))
6657 fs_devices = fs_devices->seed;
6664 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6665 u64 devid, u8 *dev_uuid)
6667 struct btrfs_device *device;
6669 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6673 list_add(&device->dev_list, &fs_devices->devices);
6674 device->fs_devices = fs_devices;
6675 fs_devices->num_devices++;
6677 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6678 fs_devices->missing_devices++;
6684 * btrfs_alloc_device - allocate struct btrfs_device
6685 * @fs_info: used only for generating a new devid, can be NULL if
6686 * devid is provided (i.e. @devid != NULL).
6687 * @devid: a pointer to devid for this device. If NULL a new devid
6689 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6692 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6693 * on error. Returned struct is not linked onto any lists and must be
6694 * destroyed with btrfs_free_device.
6696 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6700 struct btrfs_device *dev;
6703 if (WARN_ON(!devid && !fs_info))
6704 return ERR_PTR(-EINVAL);
6706 dev = __alloc_device();
6715 ret = find_next_devid(fs_info, &tmp);
6717 btrfs_free_device(dev);
6718 return ERR_PTR(ret);
6724 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6726 generate_random_uuid(dev->uuid);
6728 btrfs_init_work(&dev->work, pending_bios_fn, NULL, NULL);
6733 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6734 u64 devid, u8 *uuid, bool error)
6737 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6740 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6744 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6746 int index = btrfs_bg_flags_to_raid_index(type);
6747 int ncopies = btrfs_raid_array[index].ncopies;
6750 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6751 case BTRFS_BLOCK_GROUP_RAID5:
6752 data_stripes = num_stripes - 1;
6754 case BTRFS_BLOCK_GROUP_RAID6:
6755 data_stripes = num_stripes - 2;
6758 data_stripes = num_stripes / ncopies;
6761 return div_u64(chunk_len, data_stripes);
6764 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6765 struct btrfs_chunk *chunk)
6767 struct btrfs_fs_info *fs_info = leaf->fs_info;
6768 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6769 struct map_lookup *map;
6770 struct extent_map *em;
6774 u8 uuid[BTRFS_UUID_SIZE];
6779 logical = key->offset;
6780 length = btrfs_chunk_length(leaf, chunk);
6781 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6784 * Only need to verify chunk item if we're reading from sys chunk array,
6785 * as chunk item in tree block is already verified by tree-checker.
6787 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6788 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6793 read_lock(&map_tree->lock);
6794 em = lookup_extent_mapping(map_tree, logical, 1);
6795 read_unlock(&map_tree->lock);
6797 /* already mapped? */
6798 if (em && em->start <= logical && em->start + em->len > logical) {
6799 free_extent_map(em);
6802 free_extent_map(em);
6805 em = alloc_extent_map();
6808 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6810 free_extent_map(em);
6814 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6815 em->map_lookup = map;
6816 em->start = logical;
6819 em->block_start = 0;
6820 em->block_len = em->len;
6822 map->num_stripes = num_stripes;
6823 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6824 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6825 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6826 map->type = btrfs_chunk_type(leaf, chunk);
6827 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6828 map->verified_stripes = 0;
6829 em->orig_block_len = calc_stripe_length(map->type, em->len,
6831 for (i = 0; i < num_stripes; i++) {
6832 map->stripes[i].physical =
6833 btrfs_stripe_offset_nr(leaf, chunk, i);
6834 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6835 read_extent_buffer(leaf, uuid, (unsigned long)
6836 btrfs_stripe_dev_uuid_nr(chunk, i),
6838 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6839 devid, uuid, NULL, true);
6840 if (!map->stripes[i].dev &&
6841 !btrfs_test_opt(fs_info, DEGRADED)) {
6842 free_extent_map(em);
6843 btrfs_report_missing_device(fs_info, devid, uuid, true);
6846 if (!map->stripes[i].dev) {
6847 map->stripes[i].dev =
6848 add_missing_dev(fs_info->fs_devices, devid,
6850 if (IS_ERR(map->stripes[i].dev)) {
6851 free_extent_map(em);
6853 "failed to init missing dev %llu: %ld",
6854 devid, PTR_ERR(map->stripes[i].dev));
6855 return PTR_ERR(map->stripes[i].dev);
6857 btrfs_report_missing_device(fs_info, devid, uuid, false);
6859 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6860 &(map->stripes[i].dev->dev_state));
6864 write_lock(&map_tree->lock);
6865 ret = add_extent_mapping(map_tree, em, 0);
6866 write_unlock(&map_tree->lock);
6869 "failed to add chunk map, start=%llu len=%llu: %d",
6870 em->start, em->len, ret);
6872 free_extent_map(em);
6877 static void fill_device_from_item(struct extent_buffer *leaf,
6878 struct btrfs_dev_item *dev_item,
6879 struct btrfs_device *device)
6883 device->devid = btrfs_device_id(leaf, dev_item);
6884 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6885 device->total_bytes = device->disk_total_bytes;
6886 device->commit_total_bytes = device->disk_total_bytes;
6887 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6888 device->commit_bytes_used = device->bytes_used;
6889 device->type = btrfs_device_type(leaf, dev_item);
6890 device->io_align = btrfs_device_io_align(leaf, dev_item);
6891 device->io_width = btrfs_device_io_width(leaf, dev_item);
6892 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6893 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6894 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6896 ptr = btrfs_device_uuid(dev_item);
6897 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6900 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6903 struct btrfs_fs_devices *fs_devices;
6906 lockdep_assert_held(&uuid_mutex);
6909 fs_devices = fs_info->fs_devices->seed;
6910 while (fs_devices) {
6911 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6914 fs_devices = fs_devices->seed;
6917 fs_devices = find_fsid(fsid, NULL);
6919 if (!btrfs_test_opt(fs_info, DEGRADED))
6920 return ERR_PTR(-ENOENT);
6922 fs_devices = alloc_fs_devices(fsid, NULL);
6923 if (IS_ERR(fs_devices))
6926 fs_devices->seeding = 1;
6927 fs_devices->opened = 1;
6931 fs_devices = clone_fs_devices(fs_devices);
6932 if (IS_ERR(fs_devices))
6935 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6937 free_fs_devices(fs_devices);
6938 fs_devices = ERR_PTR(ret);
6942 if (!fs_devices->seeding) {
6943 close_fs_devices(fs_devices);
6944 free_fs_devices(fs_devices);
6945 fs_devices = ERR_PTR(-EINVAL);
6949 fs_devices->seed = fs_info->fs_devices->seed;
6950 fs_info->fs_devices->seed = fs_devices;
6955 static int read_one_dev(struct extent_buffer *leaf,
6956 struct btrfs_dev_item *dev_item)
6958 struct btrfs_fs_info *fs_info = leaf->fs_info;
6959 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6960 struct btrfs_device *device;
6963 u8 fs_uuid[BTRFS_FSID_SIZE];
6964 u8 dev_uuid[BTRFS_UUID_SIZE];
6966 devid = btrfs_device_id(leaf, dev_item);
6967 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6969 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6972 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6973 fs_devices = open_seed_devices(fs_info, fs_uuid);
6974 if (IS_ERR(fs_devices))
6975 return PTR_ERR(fs_devices);
6978 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6981 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6982 btrfs_report_missing_device(fs_info, devid,
6987 device = add_missing_dev(fs_devices, devid, dev_uuid);
6988 if (IS_ERR(device)) {
6990 "failed to add missing dev %llu: %ld",
6991 devid, PTR_ERR(device));
6992 return PTR_ERR(device);
6994 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6996 if (!device->bdev) {
6997 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6998 btrfs_report_missing_device(fs_info,
6999 devid, dev_uuid, true);
7002 btrfs_report_missing_device(fs_info, devid,
7006 if (!device->bdev &&
7007 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7009 * this happens when a device that was properly setup
7010 * in the device info lists suddenly goes bad.
7011 * device->bdev is NULL, and so we have to set
7012 * device->missing to one here
7014 device->fs_devices->missing_devices++;
7015 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7018 /* Move the device to its own fs_devices */
7019 if (device->fs_devices != fs_devices) {
7020 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7021 &device->dev_state));
7023 list_move(&device->dev_list, &fs_devices->devices);
7024 device->fs_devices->num_devices--;
7025 fs_devices->num_devices++;
7027 device->fs_devices->missing_devices--;
7028 fs_devices->missing_devices++;
7030 device->fs_devices = fs_devices;
7034 if (device->fs_devices != fs_info->fs_devices) {
7035 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7036 if (device->generation !=
7037 btrfs_device_generation(leaf, dev_item))
7041 fill_device_from_item(leaf, dev_item, device);
7042 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7043 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7044 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7045 device->fs_devices->total_rw_bytes += device->total_bytes;
7046 atomic64_add(device->total_bytes - device->bytes_used,
7047 &fs_info->free_chunk_space);
7053 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7055 struct btrfs_root *root = fs_info->tree_root;
7056 struct btrfs_super_block *super_copy = fs_info->super_copy;
7057 struct extent_buffer *sb;
7058 struct btrfs_disk_key *disk_key;
7059 struct btrfs_chunk *chunk;
7061 unsigned long sb_array_offset;
7068 struct btrfs_key key;
7070 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7072 * This will create extent buffer of nodesize, superblock size is
7073 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7074 * overallocate but we can keep it as-is, only the first page is used.
7076 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
7079 set_extent_buffer_uptodate(sb);
7080 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
7082 * The sb extent buffer is artificial and just used to read the system array.
7083 * set_extent_buffer_uptodate() call does not properly mark all it's
7084 * pages up-to-date when the page is larger: extent does not cover the
7085 * whole page and consequently check_page_uptodate does not find all
7086 * the page's extents up-to-date (the hole beyond sb),
7087 * write_extent_buffer then triggers a WARN_ON.
7089 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7090 * but sb spans only this function. Add an explicit SetPageUptodate call
7091 * to silence the warning eg. on PowerPC 64.
7093 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
7094 SetPageUptodate(sb->pages[0]);
7096 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7097 array_size = btrfs_super_sys_array_size(super_copy);
7099 array_ptr = super_copy->sys_chunk_array;
7100 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7103 while (cur_offset < array_size) {
7104 disk_key = (struct btrfs_disk_key *)array_ptr;
7105 len = sizeof(*disk_key);
7106 if (cur_offset + len > array_size)
7107 goto out_short_read;
7109 btrfs_disk_key_to_cpu(&key, disk_key);
7112 sb_array_offset += len;
7115 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
7116 chunk = (struct btrfs_chunk *)sb_array_offset;
7118 * At least one btrfs_chunk with one stripe must be
7119 * present, exact stripe count check comes afterwards
7121 len = btrfs_chunk_item_size(1);
7122 if (cur_offset + len > array_size)
7123 goto out_short_read;
7125 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7128 "invalid number of stripes %u in sys_array at offset %u",
7129 num_stripes, cur_offset);
7134 type = btrfs_chunk_type(sb, chunk);
7135 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7137 "invalid chunk type %llu in sys_array at offset %u",
7143 len = btrfs_chunk_item_size(num_stripes);
7144 if (cur_offset + len > array_size)
7145 goto out_short_read;
7147 ret = read_one_chunk(&key, sb, chunk);
7152 "unexpected item type %u in sys_array at offset %u",
7153 (u32)key.type, cur_offset);
7158 sb_array_offset += len;
7161 clear_extent_buffer_uptodate(sb);
7162 free_extent_buffer_stale(sb);
7166 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7168 clear_extent_buffer_uptodate(sb);
7169 free_extent_buffer_stale(sb);
7174 * Check if all chunks in the fs are OK for read-write degraded mount
7176 * If the @failing_dev is specified, it's accounted as missing.
7178 * Return true if all chunks meet the minimal RW mount requirements.
7179 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7181 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7182 struct btrfs_device *failing_dev)
7184 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7185 struct extent_map *em;
7189 read_lock(&map_tree->lock);
7190 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7191 read_unlock(&map_tree->lock);
7192 /* No chunk at all? Return false anyway */
7198 struct map_lookup *map;
7203 map = em->map_lookup;
7205 btrfs_get_num_tolerated_disk_barrier_failures(
7207 for (i = 0; i < map->num_stripes; i++) {
7208 struct btrfs_device *dev = map->stripes[i].dev;
7210 if (!dev || !dev->bdev ||
7211 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7212 dev->last_flush_error)
7214 else if (failing_dev && failing_dev == dev)
7217 if (missing > max_tolerated) {
7220 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7221 em->start, missing, max_tolerated);
7222 free_extent_map(em);
7226 next_start = extent_map_end(em);
7227 free_extent_map(em);
7229 read_lock(&map_tree->lock);
7230 em = lookup_extent_mapping(map_tree, next_start,
7231 (u64)(-1) - next_start);
7232 read_unlock(&map_tree->lock);
7238 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7240 struct btrfs_root *root = fs_info->chunk_root;
7241 struct btrfs_path *path;
7242 struct extent_buffer *leaf;
7243 struct btrfs_key key;
7244 struct btrfs_key found_key;
7249 path = btrfs_alloc_path();
7254 * uuid_mutex is needed only if we are mounting a sprout FS
7255 * otherwise we don't need it.
7257 mutex_lock(&uuid_mutex);
7258 mutex_lock(&fs_info->chunk_mutex);
7261 * Read all device items, and then all the chunk items. All
7262 * device items are found before any chunk item (their object id
7263 * is smaller than the lowest possible object id for a chunk
7264 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7266 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7269 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7273 leaf = path->nodes[0];
7274 slot = path->slots[0];
7275 if (slot >= btrfs_header_nritems(leaf)) {
7276 ret = btrfs_next_leaf(root, path);
7283 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7284 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7285 struct btrfs_dev_item *dev_item;
7286 dev_item = btrfs_item_ptr(leaf, slot,
7287 struct btrfs_dev_item);
7288 ret = read_one_dev(leaf, dev_item);
7292 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7293 struct btrfs_chunk *chunk;
7294 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7295 ret = read_one_chunk(&found_key, leaf, chunk);
7303 * After loading chunk tree, we've got all device information,
7304 * do another round of validation checks.
7306 if (total_dev != fs_info->fs_devices->total_devices) {
7308 "super_num_devices %llu mismatch with num_devices %llu found here",
7309 btrfs_super_num_devices(fs_info->super_copy),
7314 if (btrfs_super_total_bytes(fs_info->super_copy) <
7315 fs_info->fs_devices->total_rw_bytes) {
7317 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7318 btrfs_super_total_bytes(fs_info->super_copy),
7319 fs_info->fs_devices->total_rw_bytes);
7325 mutex_unlock(&fs_info->chunk_mutex);
7326 mutex_unlock(&uuid_mutex);
7328 btrfs_free_path(path);
7332 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7334 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7335 struct btrfs_device *device;
7337 while (fs_devices) {
7338 mutex_lock(&fs_devices->device_list_mutex);
7339 list_for_each_entry(device, &fs_devices->devices, dev_list)
7340 device->fs_info = fs_info;
7341 mutex_unlock(&fs_devices->device_list_mutex);
7343 fs_devices = fs_devices->seed;
7347 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7348 const struct btrfs_dev_stats_item *ptr,
7353 read_extent_buffer(eb, &val,
7354 offsetof(struct btrfs_dev_stats_item, values) +
7355 ((unsigned long)ptr) + (index * sizeof(u64)),
7360 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7361 struct btrfs_dev_stats_item *ptr,
7364 write_extent_buffer(eb, &val,
7365 offsetof(struct btrfs_dev_stats_item, values) +
7366 ((unsigned long)ptr) + (index * sizeof(u64)),
7370 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7372 struct btrfs_key key;
7373 struct btrfs_root *dev_root = fs_info->dev_root;
7374 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7375 struct extent_buffer *eb;
7378 struct btrfs_device *device;
7379 struct btrfs_path *path = NULL;
7382 path = btrfs_alloc_path();
7386 mutex_lock(&fs_devices->device_list_mutex);
7387 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7389 struct btrfs_dev_stats_item *ptr;
7391 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7392 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7393 key.offset = device->devid;
7394 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7396 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7397 btrfs_dev_stat_set(device, i, 0);
7398 device->dev_stats_valid = 1;
7399 btrfs_release_path(path);
7402 slot = path->slots[0];
7403 eb = path->nodes[0];
7404 item_size = btrfs_item_size_nr(eb, slot);
7406 ptr = btrfs_item_ptr(eb, slot,
7407 struct btrfs_dev_stats_item);
7409 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7410 if (item_size >= (1 + i) * sizeof(__le64))
7411 btrfs_dev_stat_set(device, i,
7412 btrfs_dev_stats_value(eb, ptr, i));
7414 btrfs_dev_stat_set(device, i, 0);
7417 device->dev_stats_valid = 1;
7418 btrfs_dev_stat_print_on_load(device);
7419 btrfs_release_path(path);
7421 mutex_unlock(&fs_devices->device_list_mutex);
7423 btrfs_free_path(path);
7424 return ret < 0 ? ret : 0;
7427 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7428 struct btrfs_device *device)
7430 struct btrfs_fs_info *fs_info = trans->fs_info;
7431 struct btrfs_root *dev_root = fs_info->dev_root;
7432 struct btrfs_path *path;
7433 struct btrfs_key key;
7434 struct extent_buffer *eb;
7435 struct btrfs_dev_stats_item *ptr;
7439 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7440 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7441 key.offset = device->devid;
7443 path = btrfs_alloc_path();
7446 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7448 btrfs_warn_in_rcu(fs_info,
7449 "error %d while searching for dev_stats item for device %s",
7450 ret, rcu_str_deref(device->name));
7455 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7456 /* need to delete old one and insert a new one */
7457 ret = btrfs_del_item(trans, dev_root, path);
7459 btrfs_warn_in_rcu(fs_info,
7460 "delete too small dev_stats item for device %s failed %d",
7461 rcu_str_deref(device->name), ret);
7468 /* need to insert a new item */
7469 btrfs_release_path(path);
7470 ret = btrfs_insert_empty_item(trans, dev_root, path,
7471 &key, sizeof(*ptr));
7473 btrfs_warn_in_rcu(fs_info,
7474 "insert dev_stats item for device %s failed %d",
7475 rcu_str_deref(device->name), ret);
7480 eb = path->nodes[0];
7481 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7482 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7483 btrfs_set_dev_stats_value(eb, ptr, i,
7484 btrfs_dev_stat_read(device, i));
7485 btrfs_mark_buffer_dirty(eb);
7488 btrfs_free_path(path);
7493 * called from commit_transaction. Writes all changed device stats to disk.
7495 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7497 struct btrfs_fs_info *fs_info = trans->fs_info;
7498 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7499 struct btrfs_device *device;
7503 mutex_lock(&fs_devices->device_list_mutex);
7504 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7505 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7506 if (!device->dev_stats_valid || stats_cnt == 0)
7511 * There is a LOAD-LOAD control dependency between the value of
7512 * dev_stats_ccnt and updating the on-disk values which requires
7513 * reading the in-memory counters. Such control dependencies
7514 * require explicit read memory barriers.
7516 * This memory barriers pairs with smp_mb__before_atomic in
7517 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7518 * barrier implied by atomic_xchg in
7519 * btrfs_dev_stats_read_and_reset
7523 ret = update_dev_stat_item(trans, device);
7525 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7527 mutex_unlock(&fs_devices->device_list_mutex);
7532 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7534 btrfs_dev_stat_inc(dev, index);
7535 btrfs_dev_stat_print_on_error(dev);
7538 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7540 if (!dev->dev_stats_valid)
7542 btrfs_err_rl_in_rcu(dev->fs_info,
7543 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7544 rcu_str_deref(dev->name),
7545 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7546 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7547 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7548 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7549 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7552 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7556 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7557 if (btrfs_dev_stat_read(dev, i) != 0)
7559 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7560 return; /* all values == 0, suppress message */
7562 btrfs_info_in_rcu(dev->fs_info,
7563 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7564 rcu_str_deref(dev->name),
7565 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7566 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7567 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7568 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7569 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7572 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7573 struct btrfs_ioctl_get_dev_stats *stats)
7575 struct btrfs_device *dev;
7576 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7579 mutex_lock(&fs_devices->device_list_mutex);
7580 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7582 mutex_unlock(&fs_devices->device_list_mutex);
7585 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7587 } else if (!dev->dev_stats_valid) {
7588 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7590 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7591 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7592 if (stats->nr_items > i)
7594 btrfs_dev_stat_read_and_reset(dev, i);
7596 btrfs_dev_stat_set(dev, i, 0);
7598 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7599 current->comm, task_pid_nr(current));
7601 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7602 if (stats->nr_items > i)
7603 stats->values[i] = btrfs_dev_stat_read(dev, i);
7605 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7606 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7610 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7612 struct buffer_head *bh;
7613 struct btrfs_super_block *disk_super;
7619 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7622 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7625 disk_super = (struct btrfs_super_block *)bh->b_data;
7627 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7628 set_buffer_dirty(bh);
7629 sync_dirty_buffer(bh);
7633 /* Notify udev that device has changed */
7634 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7636 /* Update ctime/mtime for device path for libblkid */
7637 update_dev_time(device_path);
7641 * Update the size and bytes used for each device where it changed. This is
7642 * delayed since we would otherwise get errors while writing out the
7645 * Must be invoked during transaction commit.
7647 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7649 struct btrfs_device *curr, *next;
7651 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7653 if (list_empty(&trans->dev_update_list))
7657 * We don't need the device_list_mutex here. This list is owned by the
7658 * transaction and the transaction must complete before the device is
7661 mutex_lock(&trans->fs_info->chunk_mutex);
7662 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7664 list_del_init(&curr->post_commit_list);
7665 curr->commit_total_bytes = curr->disk_total_bytes;
7666 curr->commit_bytes_used = curr->bytes_used;
7668 mutex_unlock(&trans->fs_info->chunk_mutex);
7671 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7673 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7674 while (fs_devices) {
7675 fs_devices->fs_info = fs_info;
7676 fs_devices = fs_devices->seed;
7680 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7682 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7683 while (fs_devices) {
7684 fs_devices->fs_info = NULL;
7685 fs_devices = fs_devices->seed;
7690 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7692 int btrfs_bg_type_to_factor(u64 flags)
7694 const int index = btrfs_bg_flags_to_raid_index(flags);
7696 return btrfs_raid_array[index].ncopies;
7701 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7702 u64 chunk_offset, u64 devid,
7703 u64 physical_offset, u64 physical_len)
7705 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7706 struct extent_map *em;
7707 struct map_lookup *map;
7708 struct btrfs_device *dev;
7714 read_lock(&em_tree->lock);
7715 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7716 read_unlock(&em_tree->lock);
7720 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7721 physical_offset, devid);
7726 map = em->map_lookup;
7727 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7728 if (physical_len != stripe_len) {
7730 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7731 physical_offset, devid, em->start, physical_len,
7737 for (i = 0; i < map->num_stripes; i++) {
7738 if (map->stripes[i].dev->devid == devid &&
7739 map->stripes[i].physical == physical_offset) {
7741 if (map->verified_stripes >= map->num_stripes) {
7743 "too many dev extents for chunk %llu found",
7748 map->verified_stripes++;
7754 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7755 physical_offset, devid);
7759 /* Make sure no dev extent is beyond device bondary */
7760 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7762 btrfs_err(fs_info, "failed to find devid %llu", devid);
7767 /* It's possible this device is a dummy for seed device */
7768 if (dev->disk_total_bytes == 0) {
7769 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7772 btrfs_err(fs_info, "failed to find seed devid %llu",
7779 if (physical_offset + physical_len > dev->disk_total_bytes) {
7781 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7782 devid, physical_offset, physical_len,
7783 dev->disk_total_bytes);
7788 free_extent_map(em);
7792 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7794 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7795 struct extent_map *em;
7796 struct rb_node *node;
7799 read_lock(&em_tree->lock);
7800 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7801 em = rb_entry(node, struct extent_map, rb_node);
7802 if (em->map_lookup->num_stripes !=
7803 em->map_lookup->verified_stripes) {
7805 "chunk %llu has missing dev extent, have %d expect %d",
7806 em->start, em->map_lookup->verified_stripes,
7807 em->map_lookup->num_stripes);
7813 read_unlock(&em_tree->lock);
7818 * Ensure that all dev extents are mapped to correct chunk, otherwise
7819 * later chunk allocation/free would cause unexpected behavior.
7821 * NOTE: This will iterate through the whole device tree, which should be of
7822 * the same size level as the chunk tree. This slightly increases mount time.
7824 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7826 struct btrfs_path *path;
7827 struct btrfs_root *root = fs_info->dev_root;
7828 struct btrfs_key key;
7830 u64 prev_dev_ext_end = 0;
7834 key.type = BTRFS_DEV_EXTENT_KEY;
7837 path = btrfs_alloc_path();
7841 path->reada = READA_FORWARD;
7842 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7846 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7847 ret = btrfs_next_item(root, path);
7850 /* No dev extents at all? Not good */
7857 struct extent_buffer *leaf = path->nodes[0];
7858 struct btrfs_dev_extent *dext;
7859 int slot = path->slots[0];
7861 u64 physical_offset;
7865 btrfs_item_key_to_cpu(leaf, &key, slot);
7866 if (key.type != BTRFS_DEV_EXTENT_KEY)
7868 devid = key.objectid;
7869 physical_offset = key.offset;
7871 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7872 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7873 physical_len = btrfs_dev_extent_length(leaf, dext);
7875 /* Check if this dev extent overlaps with the previous one */
7876 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7878 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7879 devid, physical_offset, prev_dev_ext_end);
7884 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7885 physical_offset, physical_len);
7889 prev_dev_ext_end = physical_offset + physical_len;
7891 ret = btrfs_next_item(root, path);
7900 /* Ensure all chunks have corresponding dev extents */
7901 ret = verify_chunk_dev_extent_mapping(fs_info);
7903 btrfs_free_path(path);
7908 * Check whether the given block group or device is pinned by any inode being
7909 * used as a swapfile.
7911 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7913 struct btrfs_swapfile_pin *sp;
7914 struct rb_node *node;
7916 spin_lock(&fs_info->swapfile_pins_lock);
7917 node = fs_info->swapfile_pins.rb_node;
7919 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7921 node = node->rb_left;
7922 else if (ptr > sp->ptr)
7923 node = node->rb_right;
7927 spin_unlock(&fs_info->swapfile_pins_lock);
7928 return node != NULL;