1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/mm.h>
9 #include <linux/slab.h>
10 #include <linux/buffer_head.h>
11 #include <linux/blkdev.h>
12 #include <linux/ratelimit.h>
13 #include <linux/kthread.h>
14 #include <linux/raid/pq.h>
15 #include <linux/semaphore.h>
16 #include <linux/uuid.h>
17 #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"
29 #include "dev-replace.h"
31 #include "tree-checker.h"
33 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
34 [BTRFS_RAID_RAID10] = {
37 .devs_max = 0, /* 0 == as many as possible */
39 .tolerated_failures = 1,
42 .raid_name = "raid10",
43 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
44 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
46 [BTRFS_RAID_RAID1] = {
51 .tolerated_failures = 1,
55 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
56 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
63 .tolerated_failures = 0,
67 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
70 [BTRFS_RAID_RAID0] = {
75 .tolerated_failures = 0,
79 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
82 [BTRFS_RAID_SINGLE] = {
87 .tolerated_failures = 0,
90 .raid_name = "single",
94 [BTRFS_RAID_RAID5] = {
99 .tolerated_failures = 1,
102 .raid_name = "raid5",
103 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
104 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
106 [BTRFS_RAID_RAID6] = {
111 .tolerated_failures = 2,
114 .raid_name = "raid6",
115 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
116 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
120 const char *get_raid_name(enum btrfs_raid_types type)
122 if (type >= BTRFS_NR_RAID_TYPES)
125 return btrfs_raid_array[type].raid_name;
128 static int init_first_rw_device(struct btrfs_trans_handle *trans,
129 struct btrfs_fs_info *fs_info);
130 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
131 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
132 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
133 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
134 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
135 enum btrfs_map_op op,
136 u64 logical, u64 *length,
137 struct btrfs_bio **bbio_ret,
138 int mirror_num, int need_raid_map);
144 * There are several mutexes that protect manipulation of devices and low-level
145 * structures like chunks but not block groups, extents or files
147 * uuid_mutex (global lock)
148 * ------------------------
149 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
150 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
151 * device) or requested by the device= mount option
153 * the mutex can be very coarse and can cover long-running operations
155 * protects: updates to fs_devices counters like missing devices, rw devices,
156 * seeding, structure cloning, openning/closing devices at mount/umount time
158 * global::fs_devs - add, remove, updates to the global list
160 * does not protect: manipulation of the fs_devices::devices list in general
161 * but in mount context it could be used to exclude list modifications by eg.
164 * btrfs_device::name - renames (write side), read is RCU
166 * fs_devices::device_list_mutex (per-fs, with RCU)
167 * ------------------------------------------------
168 * protects updates to fs_devices::devices, ie. adding and deleting
170 * simple list traversal with read-only actions can be done with RCU protection
172 * may be used to exclude some operations from running concurrently without any
173 * modifications to the list (see write_all_supers)
175 * Is not required at mount and close times, because our device list is
176 * protected by the uuid_mutex at that point.
180 * protects balance structures (status, state) and context accessed from
181 * several places (internally, ioctl)
185 * protects chunks, adding or removing during allocation, trim or when a new
186 * device is added/removed
190 * a big lock that is held by the cleaner thread and prevents running subvolume
191 * cleaning together with relocation or delayed iputs
204 * Exclusive operations, BTRFS_FS_EXCL_OP
205 * ======================================
207 * Maintains the exclusivity of the following operations that apply to the
208 * whole filesystem and cannot run in parallel.
213 * - Device replace (*)
216 * The device operations (as above) can be in one of the following states:
222 * Only device operations marked with (*) can go into the Paused state for the
225 * - ioctl (only Balance can be Paused through ioctl)
226 * - filesystem remounted as read-only
227 * - filesystem unmounted and mounted as read-only
228 * - system power-cycle and filesystem mounted as read-only
229 * - filesystem or device errors leading to forced read-only
231 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
232 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
233 * A device operation in Paused or Running state can be canceled or resumed
234 * either by ioctl (Balance only) or when remounted as read-write.
235 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
239 DEFINE_MUTEX(uuid_mutex);
240 static LIST_HEAD(fs_uuids);
241 struct list_head *btrfs_get_fs_uuids(void)
247 * alloc_fs_devices - allocate struct btrfs_fs_devices
248 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
250 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
251 * The returned struct is not linked onto any lists and can be destroyed with
252 * kfree() right away.
254 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
256 struct btrfs_fs_devices *fs_devs;
258 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
260 return ERR_PTR(-ENOMEM);
262 mutex_init(&fs_devs->device_list_mutex);
264 INIT_LIST_HEAD(&fs_devs->devices);
265 INIT_LIST_HEAD(&fs_devs->resized_devices);
266 INIT_LIST_HEAD(&fs_devs->alloc_list);
267 INIT_LIST_HEAD(&fs_devs->fs_list);
269 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
274 void btrfs_free_device(struct btrfs_device *device)
276 rcu_string_free(device->name);
277 bio_put(device->flush_bio);
281 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
283 struct btrfs_device *device;
284 WARN_ON(fs_devices->opened);
285 while (!list_empty(&fs_devices->devices)) {
286 device = list_entry(fs_devices->devices.next,
287 struct btrfs_device, dev_list);
288 list_del(&device->dev_list);
289 btrfs_free_device(device);
294 static void btrfs_kobject_uevent(struct block_device *bdev,
295 enum kobject_action action)
299 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
301 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
303 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
304 &disk_to_dev(bdev->bd_disk)->kobj);
307 void __exit btrfs_cleanup_fs_uuids(void)
309 struct btrfs_fs_devices *fs_devices;
311 while (!list_empty(&fs_uuids)) {
312 fs_devices = list_entry(fs_uuids.next,
313 struct btrfs_fs_devices, fs_list);
314 list_del(&fs_devices->fs_list);
315 free_fs_devices(fs_devices);
320 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
321 * Returned struct is not linked onto any lists and must be destroyed using
324 static struct btrfs_device *__alloc_device(void)
326 struct btrfs_device *dev;
328 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
330 return ERR_PTR(-ENOMEM);
333 * Preallocate a bio that's always going to be used for flushing device
334 * barriers and matches the device lifespan
336 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
337 if (!dev->flush_bio) {
339 return ERR_PTR(-ENOMEM);
342 INIT_LIST_HEAD(&dev->dev_list);
343 INIT_LIST_HEAD(&dev->dev_alloc_list);
344 INIT_LIST_HEAD(&dev->resized_list);
346 spin_lock_init(&dev->io_lock);
348 atomic_set(&dev->reada_in_flight, 0);
349 atomic_set(&dev->dev_stats_ccnt, 0);
350 btrfs_device_data_ordered_init(dev);
351 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
352 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
357 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
359 struct btrfs_fs_devices *fs_devices;
361 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
362 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
369 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
370 int flush, struct block_device **bdev,
371 struct buffer_head **bh)
375 *bdev = blkdev_get_by_path(device_path, flags, holder);
378 ret = PTR_ERR(*bdev);
383 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
384 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
386 blkdev_put(*bdev, flags);
389 invalidate_bdev(*bdev);
390 *bh = btrfs_read_dev_super(*bdev);
393 blkdev_put(*bdev, flags);
405 static void requeue_list(struct btrfs_pending_bios *pending_bios,
406 struct bio *head, struct bio *tail)
409 struct bio *old_head;
411 old_head = pending_bios->head;
412 pending_bios->head = head;
413 if (pending_bios->tail)
414 tail->bi_next = old_head;
416 pending_bios->tail = tail;
420 * we try to collect pending bios for a device so we don't get a large
421 * number of procs sending bios down to the same device. This greatly
422 * improves the schedulers ability to collect and merge the bios.
424 * But, it also turns into a long list of bios to process and that is sure
425 * to eventually make the worker thread block. The solution here is to
426 * make some progress and then put this work struct back at the end of
427 * the list if the block device is congested. This way, multiple devices
428 * can make progress from a single worker thread.
430 static noinline void run_scheduled_bios(struct btrfs_device *device)
432 struct btrfs_fs_info *fs_info = device->fs_info;
434 struct backing_dev_info *bdi;
435 struct btrfs_pending_bios *pending_bios;
439 unsigned long num_run;
440 unsigned long batch_run = 0;
441 unsigned long last_waited = 0;
443 int sync_pending = 0;
444 struct blk_plug plug;
447 * this function runs all the bios we've collected for
448 * a particular device. We don't want to wander off to
449 * another device without first sending all of these down.
450 * So, setup a plug here and finish it off before we return
452 blk_start_plug(&plug);
454 bdi = device->bdev->bd_bdi;
457 spin_lock(&device->io_lock);
462 /* take all the bios off the list at once and process them
463 * later on (without the lock held). But, remember the
464 * tail and other pointers so the bios can be properly reinserted
465 * into the list if we hit congestion
467 if (!force_reg && device->pending_sync_bios.head) {
468 pending_bios = &device->pending_sync_bios;
471 pending_bios = &device->pending_bios;
475 pending = pending_bios->head;
476 tail = pending_bios->tail;
477 WARN_ON(pending && !tail);
480 * if pending was null this time around, no bios need processing
481 * at all and we can stop. Otherwise it'll loop back up again
482 * and do an additional check so no bios are missed.
484 * device->running_pending is used to synchronize with the
487 if (device->pending_sync_bios.head == NULL &&
488 device->pending_bios.head == NULL) {
490 device->running_pending = 0;
493 device->running_pending = 1;
496 pending_bios->head = NULL;
497 pending_bios->tail = NULL;
499 spin_unlock(&device->io_lock);
504 /* we want to work on both lists, but do more bios on the
505 * sync list than the regular list
508 pending_bios != &device->pending_sync_bios &&
509 device->pending_sync_bios.head) ||
510 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
511 device->pending_bios.head)) {
512 spin_lock(&device->io_lock);
513 requeue_list(pending_bios, pending, tail);
518 pending = pending->bi_next;
521 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
524 * if we're doing the sync list, record that our
525 * plug has some sync requests on it
527 * If we're doing the regular list and there are
528 * sync requests sitting around, unplug before
531 if (pending_bios == &device->pending_sync_bios) {
533 } else if (sync_pending) {
534 blk_finish_plug(&plug);
535 blk_start_plug(&plug);
539 btrfsic_submit_bio(cur);
546 * we made progress, there is more work to do and the bdi
547 * is now congested. Back off and let other work structs
550 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
551 fs_info->fs_devices->open_devices > 1) {
552 struct io_context *ioc;
554 ioc = current->io_context;
557 * the main goal here is that we don't want to
558 * block if we're going to be able to submit
559 * more requests without blocking.
561 * This code does two great things, it pokes into
562 * the elevator code from a filesystem _and_
563 * it makes assumptions about how batching works.
565 if (ioc && ioc->nr_batch_requests > 0 &&
566 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
568 ioc->last_waited == last_waited)) {
570 * we want to go through our batch of
571 * requests and stop. So, we copy out
572 * the ioc->last_waited time and test
573 * against it before looping
575 last_waited = ioc->last_waited;
579 spin_lock(&device->io_lock);
580 requeue_list(pending_bios, pending, tail);
581 device->running_pending = 1;
583 spin_unlock(&device->io_lock);
584 btrfs_queue_work(fs_info->submit_workers,
594 spin_lock(&device->io_lock);
595 if (device->pending_bios.head || device->pending_sync_bios.head)
597 spin_unlock(&device->io_lock);
600 blk_finish_plug(&plug);
603 static void pending_bios_fn(struct btrfs_work *work)
605 struct btrfs_device *device;
607 device = container_of(work, struct btrfs_device, work);
608 run_scheduled_bios(device);
612 * Search and remove all stale (devices which are not mounted) devices.
613 * When both inputs are NULL, it will search and release all stale devices.
614 * path: Optional. When provided will it release all unmounted devices
615 * matching this path only.
616 * skip_dev: Optional. Will skip this device when searching for the stale
619 static void btrfs_free_stale_devices(const char *path,
620 struct btrfs_device *skip_device)
622 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
623 struct btrfs_device *device, *tmp_device;
625 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
626 mutex_lock(&fs_devices->device_list_mutex);
627 if (fs_devices->opened) {
628 mutex_unlock(&fs_devices->device_list_mutex);
632 list_for_each_entry_safe(device, tmp_device,
633 &fs_devices->devices, dev_list) {
636 if (skip_device && skip_device == device)
638 if (path && !device->name)
643 not_found = strcmp(rcu_str_deref(device->name),
649 /* delete the stale device */
650 fs_devices->num_devices--;
651 list_del(&device->dev_list);
652 btrfs_free_device(device);
654 if (fs_devices->num_devices == 0)
657 mutex_unlock(&fs_devices->device_list_mutex);
658 if (fs_devices->num_devices == 0) {
659 btrfs_sysfs_remove_fsid(fs_devices);
660 list_del(&fs_devices->fs_list);
661 free_fs_devices(fs_devices);
667 * This is only used on mount, and we are protected from competing things
668 * messing with our fs_devices by the uuid_mutex, thus we do not need the
669 * fs_devices->device_list_mutex here.
671 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
672 struct btrfs_device *device, fmode_t flags,
675 struct request_queue *q;
676 struct block_device *bdev;
677 struct buffer_head *bh;
678 struct btrfs_super_block *disk_super;
687 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
692 disk_super = (struct btrfs_super_block *)bh->b_data;
693 devid = btrfs_stack_device_id(&disk_super->dev_item);
694 if (devid != device->devid)
697 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
700 device->generation = btrfs_super_generation(disk_super);
702 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
703 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
704 fs_devices->seeding = 1;
706 if (bdev_read_only(bdev))
707 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
709 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
712 q = bdev_get_queue(bdev);
713 if (!blk_queue_nonrot(q))
714 fs_devices->rotating = 1;
717 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
718 device->mode = flags;
720 fs_devices->open_devices++;
721 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
722 device->devid != BTRFS_DEV_REPLACE_DEVID) {
723 fs_devices->rw_devices++;
724 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
732 blkdev_put(bdev, flags);
738 * Add new device to list of registered devices
741 * device pointer which was just added or updated when successful
742 * error pointer when failed
744 static noinline struct btrfs_device *device_list_add(const char *path,
745 struct btrfs_super_block *disk_super,
746 bool *new_device_added)
748 struct btrfs_device *device;
749 struct btrfs_fs_devices *fs_devices;
750 struct rcu_string *name;
751 u64 found_transid = btrfs_super_generation(disk_super);
752 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
754 fs_devices = find_fsid(disk_super->fsid);
756 fs_devices = alloc_fs_devices(disk_super->fsid);
757 if (IS_ERR(fs_devices))
758 return ERR_CAST(fs_devices);
760 mutex_lock(&fs_devices->device_list_mutex);
761 list_add(&fs_devices->fs_list, &fs_uuids);
765 mutex_lock(&fs_devices->device_list_mutex);
766 device = btrfs_find_device(fs_devices, devid,
767 disk_super->dev_item.uuid, NULL, false);
771 if (fs_devices->opened) {
772 mutex_unlock(&fs_devices->device_list_mutex);
773 return ERR_PTR(-EBUSY);
776 device = btrfs_alloc_device(NULL, &devid,
777 disk_super->dev_item.uuid);
778 if (IS_ERR(device)) {
779 mutex_unlock(&fs_devices->device_list_mutex);
780 /* we can safely leave the fs_devices entry around */
784 name = rcu_string_strdup(path, GFP_NOFS);
786 btrfs_free_device(device);
787 mutex_unlock(&fs_devices->device_list_mutex);
788 return ERR_PTR(-ENOMEM);
790 rcu_assign_pointer(device->name, name);
792 list_add_rcu(&device->dev_list, &fs_devices->devices);
793 fs_devices->num_devices++;
795 device->fs_devices = fs_devices;
796 *new_device_added = true;
798 if (disk_super->label[0])
799 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
800 disk_super->label, devid, found_transid, path);
802 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
803 disk_super->fsid, devid, found_transid, path);
805 } else if (!device->name || strcmp(device->name->str, path)) {
807 * When FS is already mounted.
808 * 1. If you are here and if the device->name is NULL that
809 * means this device was missing at time of FS mount.
810 * 2. If you are here and if the device->name is different
811 * from 'path' that means either
812 * a. The same device disappeared and reappeared with
814 * b. The missing-disk-which-was-replaced, has
817 * We must allow 1 and 2a above. But 2b would be a spurious
820 * Further in case of 1 and 2a above, the disk at 'path'
821 * would have missed some transaction when it was away and
822 * in case of 2a the stale bdev has to be updated as well.
823 * 2b must not be allowed at all time.
827 * For now, we do allow update to btrfs_fs_device through the
828 * btrfs dev scan cli after FS has been mounted. We're still
829 * tracking a problem where systems fail mount by subvolume id
830 * when we reject replacement on a mounted FS.
832 if (!fs_devices->opened && found_transid < device->generation) {
834 * That is if the FS is _not_ mounted and if you
835 * are here, that means there is more than one
836 * disk with same uuid and devid.We keep the one
837 * with larger generation number or the last-in if
838 * generation are equal.
840 mutex_unlock(&fs_devices->device_list_mutex);
841 return ERR_PTR(-EEXIST);
845 * We are going to replace the device path for a given devid,
846 * make sure it's the same device if the device is mounted
849 struct block_device *path_bdev;
851 path_bdev = lookup_bdev(path);
852 if (IS_ERR(path_bdev)) {
853 mutex_unlock(&fs_devices->device_list_mutex);
854 return ERR_CAST(path_bdev);
857 if (device->bdev != path_bdev) {
859 mutex_unlock(&fs_devices->device_list_mutex);
861 * device->fs_info may not be reliable here, so
862 * pass in a NULL instead. This avoids a
863 * possible use-after-free when the fs_info and
864 * fs_info->sb are already torn down.
866 btrfs_warn_in_rcu(NULL,
867 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
868 path, devid, found_transid,
870 task_pid_nr(current));
871 return ERR_PTR(-EEXIST);
874 btrfs_info_in_rcu(device->fs_info,
875 "devid %llu device path %s changed to %s scanned by %s (%d)",
876 devid, rcu_str_deref(device->name),
878 task_pid_nr(current));
881 name = rcu_string_strdup(path, GFP_NOFS);
883 mutex_unlock(&fs_devices->device_list_mutex);
884 return ERR_PTR(-ENOMEM);
886 rcu_string_free(device->name);
887 rcu_assign_pointer(device->name, name);
888 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
889 fs_devices->missing_devices--;
890 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
895 * Unmount does not free the btrfs_device struct but would zero
896 * generation along with most of the other members. So just update
897 * it back. We need it to pick the disk with largest generation
900 if (!fs_devices->opened)
901 device->generation = found_transid;
903 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
905 mutex_unlock(&fs_devices->device_list_mutex);
909 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
911 struct btrfs_fs_devices *fs_devices;
912 struct btrfs_device *device;
913 struct btrfs_device *orig_dev;
915 fs_devices = alloc_fs_devices(orig->fsid);
916 if (IS_ERR(fs_devices))
919 mutex_lock(&orig->device_list_mutex);
920 fs_devices->total_devices = orig->total_devices;
922 /* We have held the volume lock, it is safe to get the devices. */
923 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
924 struct rcu_string *name;
926 device = btrfs_alloc_device(NULL, &orig_dev->devid,
932 * This is ok to do without rcu read locked because we hold the
933 * uuid mutex so nothing we touch in here is going to disappear.
935 if (orig_dev->name) {
936 name = rcu_string_strdup(orig_dev->name->str,
939 btrfs_free_device(device);
942 rcu_assign_pointer(device->name, name);
945 list_add(&device->dev_list, &fs_devices->devices);
946 device->fs_devices = fs_devices;
947 fs_devices->num_devices++;
949 mutex_unlock(&orig->device_list_mutex);
952 mutex_unlock(&orig->device_list_mutex);
953 free_fs_devices(fs_devices);
954 return ERR_PTR(-ENOMEM);
958 * After we have read the system tree and know devids belonging to
959 * this filesystem, remove the device which does not belong there.
961 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
963 struct btrfs_device *device, *next;
964 struct btrfs_device *latest_dev = NULL;
966 mutex_lock(&uuid_mutex);
968 /* This is the initialized path, it is safe to release the devices. */
969 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
970 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
971 &device->dev_state)) {
972 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
973 &device->dev_state) &&
974 !test_bit(BTRFS_DEV_STATE_MISSING,
975 &device->dev_state) &&
977 device->generation > latest_dev->generation)) {
984 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
985 * in btrfs_init_dev_replace() so just continue.
987 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
991 blkdev_put(device->bdev, device->mode);
993 fs_devices->open_devices--;
995 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
996 list_del_init(&device->dev_alloc_list);
997 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
998 fs_devices->rw_devices--;
1000 list_del_init(&device->dev_list);
1001 fs_devices->num_devices--;
1002 btrfs_free_device(device);
1005 if (fs_devices->seed) {
1006 fs_devices = fs_devices->seed;
1010 fs_devices->latest_bdev = latest_dev->bdev;
1012 mutex_unlock(&uuid_mutex);
1015 static void free_device_rcu(struct rcu_head *head)
1017 struct btrfs_device *device;
1019 device = container_of(head, struct btrfs_device, rcu);
1020 btrfs_free_device(device);
1023 static void btrfs_close_bdev(struct btrfs_device *device)
1028 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1029 sync_blockdev(device->bdev);
1030 invalidate_bdev(device->bdev);
1033 blkdev_put(device->bdev, device->mode);
1036 static void btrfs_close_one_device(struct btrfs_device *device)
1038 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1039 struct btrfs_device *new_device;
1040 struct rcu_string *name;
1043 fs_devices->open_devices--;
1045 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1046 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1047 list_del_init(&device->dev_alloc_list);
1048 fs_devices->rw_devices--;
1051 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1052 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
1054 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1055 fs_devices->missing_devices--;
1057 btrfs_close_bdev(device);
1059 new_device = btrfs_alloc_device(NULL, &device->devid,
1061 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1063 /* Safe because we are under uuid_mutex */
1065 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1066 BUG_ON(!name); /* -ENOMEM */
1067 rcu_assign_pointer(new_device->name, name);
1070 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1071 new_device->fs_devices = device->fs_devices;
1073 call_rcu(&device->rcu, free_device_rcu);
1076 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1078 struct btrfs_device *device, *tmp;
1080 if (--fs_devices->opened > 0)
1083 mutex_lock(&fs_devices->device_list_mutex);
1084 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1085 btrfs_close_one_device(device);
1087 mutex_unlock(&fs_devices->device_list_mutex);
1089 WARN_ON(fs_devices->open_devices);
1090 WARN_ON(fs_devices->rw_devices);
1091 fs_devices->opened = 0;
1092 fs_devices->seeding = 0;
1097 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1099 struct btrfs_fs_devices *seed_devices = NULL;
1102 mutex_lock(&uuid_mutex);
1103 ret = close_fs_devices(fs_devices);
1104 if (!fs_devices->opened) {
1105 seed_devices = fs_devices->seed;
1106 fs_devices->seed = NULL;
1108 mutex_unlock(&uuid_mutex);
1110 while (seed_devices) {
1111 fs_devices = seed_devices;
1112 seed_devices = fs_devices->seed;
1113 close_fs_devices(fs_devices);
1114 free_fs_devices(fs_devices);
1119 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1120 fmode_t flags, void *holder)
1122 struct btrfs_device *device;
1123 struct btrfs_device *latest_dev = NULL;
1126 flags |= FMODE_EXCL;
1128 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1129 /* Just open everything we can; ignore failures here */
1130 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1134 device->generation > latest_dev->generation)
1135 latest_dev = device;
1137 if (fs_devices->open_devices == 0) {
1141 fs_devices->opened = 1;
1142 fs_devices->latest_bdev = latest_dev->bdev;
1143 fs_devices->total_rw_bytes = 0;
1148 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1150 struct btrfs_device *dev1, *dev2;
1152 dev1 = list_entry(a, struct btrfs_device, dev_list);
1153 dev2 = list_entry(b, struct btrfs_device, dev_list);
1155 if (dev1->devid < dev2->devid)
1157 else if (dev1->devid > dev2->devid)
1162 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1163 fmode_t flags, void *holder)
1167 lockdep_assert_held(&uuid_mutex);
1169 * The device_list_mutex cannot be taken here in case opening the
1170 * underlying device takes further locks like bd_mutex.
1172 * We also don't need the lock here as this is called during mount and
1173 * exclusion is provided by uuid_mutex
1176 if (fs_devices->opened) {
1177 fs_devices->opened++;
1180 list_sort(NULL, &fs_devices->devices, devid_cmp);
1181 ret = open_fs_devices(fs_devices, flags, holder);
1187 static void btrfs_release_disk_super(struct page *page)
1193 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1195 struct btrfs_super_block **disk_super)
1200 /* make sure our super fits in the device */
1201 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1204 /* make sure our super fits in the page */
1205 if (sizeof(**disk_super) > PAGE_SIZE)
1208 /* make sure our super doesn't straddle pages on disk */
1209 index = bytenr >> PAGE_SHIFT;
1210 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1213 /* pull in the page with our super */
1214 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1217 if (IS_ERR_OR_NULL(*page))
1222 /* align our pointer to the offset of the super block */
1223 *disk_super = p + (bytenr & ~PAGE_MASK);
1225 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1226 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1227 btrfs_release_disk_super(*page);
1231 if ((*disk_super)->label[0] &&
1232 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1233 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1239 * Look for a btrfs signature on a device. This may be called out of the mount path
1240 * and we are not allowed to call set_blocksize during the scan. The superblock
1241 * is read via pagecache
1243 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1246 struct btrfs_super_block *disk_super;
1247 bool new_device_added = false;
1248 struct btrfs_device *device = NULL;
1249 struct block_device *bdev;
1253 lockdep_assert_held(&uuid_mutex);
1256 * we would like to check all the supers, but that would make
1257 * a btrfs mount succeed after a mkfs from a different FS.
1258 * So, we need to add a special mount option to scan for
1259 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1261 bytenr = btrfs_sb_offset(0);
1262 flags |= FMODE_EXCL;
1264 bdev = blkdev_get_by_path(path, flags, holder);
1266 return ERR_CAST(bdev);
1268 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1269 device = ERR_PTR(-EINVAL);
1270 goto error_bdev_put;
1273 device = device_list_add(path, disk_super, &new_device_added);
1274 if (!IS_ERR(device)) {
1275 if (new_device_added)
1276 btrfs_free_stale_devices(path, device);
1279 btrfs_release_disk_super(page);
1282 blkdev_put(bdev, flags);
1287 static int contains_pending_extent(struct btrfs_transaction *transaction,
1288 struct btrfs_device *device,
1289 u64 *start, u64 len)
1291 struct btrfs_fs_info *fs_info = device->fs_info;
1292 struct extent_map *em;
1293 struct list_head *search_list = &fs_info->pinned_chunks;
1295 u64 physical_start = *start;
1298 search_list = &transaction->pending_chunks;
1300 list_for_each_entry(em, search_list, list) {
1301 struct map_lookup *map;
1304 map = em->map_lookup;
1305 for (i = 0; i < map->num_stripes; i++) {
1308 if (map->stripes[i].dev != device)
1310 if (map->stripes[i].physical >= physical_start + len ||
1311 map->stripes[i].physical + em->orig_block_len <=
1315 * Make sure that while processing the pinned list we do
1316 * not override our *start with a lower value, because
1317 * we can have pinned chunks that fall within this
1318 * device hole and that have lower physical addresses
1319 * than the pending chunks we processed before. If we
1320 * do not take this special care we can end up getting
1321 * 2 pending chunks that start at the same physical
1322 * device offsets because the end offset of a pinned
1323 * chunk can be equal to the start offset of some
1326 end = map->stripes[i].physical + em->orig_block_len;
1333 if (search_list != &fs_info->pinned_chunks) {
1334 search_list = &fs_info->pinned_chunks;
1343 * find_free_dev_extent_start - find free space in the specified device
1344 * @device: the device which we search the free space in
1345 * @num_bytes: the size of the free space that we need
1346 * @search_start: the position from which to begin the search
1347 * @start: store the start of the free space.
1348 * @len: the size of the free space. that we find, or the size
1349 * of the max free space if we don't find suitable free space
1351 * this uses a pretty simple search, the expectation is that it is
1352 * called very infrequently and that a given device has a small number
1355 * @start is used to store the start of the free space if we find. But if we
1356 * don't find suitable free space, it will be used to store the start position
1357 * of the max free space.
1359 * @len is used to store the size of the free space that we find.
1360 * But if we don't find suitable free space, it is used to store the size of
1361 * the max free space.
1363 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1364 struct btrfs_device *device, u64 num_bytes,
1365 u64 search_start, u64 *start, u64 *len)
1367 struct btrfs_fs_info *fs_info = device->fs_info;
1368 struct btrfs_root *root = fs_info->dev_root;
1369 struct btrfs_key key;
1370 struct btrfs_dev_extent *dev_extent;
1371 struct btrfs_path *path;
1376 u64 search_end = device->total_bytes;
1379 struct extent_buffer *l;
1382 * We don't want to overwrite the superblock on the drive nor any area
1383 * used by the boot loader (grub for example), so we make sure to start
1384 * at an offset of at least 1MB.
1386 search_start = max_t(u64, search_start, SZ_1M);
1388 path = btrfs_alloc_path();
1392 max_hole_start = search_start;
1396 if (search_start >= search_end ||
1397 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1402 path->reada = READA_FORWARD;
1403 path->search_commit_root = 1;
1404 path->skip_locking = 1;
1406 key.objectid = device->devid;
1407 key.offset = search_start;
1408 key.type = BTRFS_DEV_EXTENT_KEY;
1410 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1414 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1421 slot = path->slots[0];
1422 if (slot >= btrfs_header_nritems(l)) {
1423 ret = btrfs_next_leaf(root, path);
1431 btrfs_item_key_to_cpu(l, &key, slot);
1433 if (key.objectid < device->devid)
1436 if (key.objectid > device->devid)
1439 if (key.type != BTRFS_DEV_EXTENT_KEY)
1442 if (key.offset > search_start) {
1443 hole_size = key.offset - search_start;
1446 * Have to check before we set max_hole_start, otherwise
1447 * we could end up sending back this offset anyway.
1449 if (contains_pending_extent(transaction, device,
1452 if (key.offset >= search_start) {
1453 hole_size = key.offset - search_start;
1460 if (hole_size > max_hole_size) {
1461 max_hole_start = search_start;
1462 max_hole_size = hole_size;
1466 * If this free space is greater than which we need,
1467 * it must be the max free space that we have found
1468 * until now, so max_hole_start must point to the start
1469 * of this free space and the length of this free space
1470 * is stored in max_hole_size. Thus, we return
1471 * max_hole_start and max_hole_size and go back to the
1474 if (hole_size >= num_bytes) {
1480 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1481 extent_end = key.offset + btrfs_dev_extent_length(l,
1483 if (extent_end > search_start)
1484 search_start = extent_end;
1491 * At this point, search_start should be the end of
1492 * allocated dev extents, and when shrinking the device,
1493 * search_end may be smaller than search_start.
1495 if (search_end > search_start) {
1496 hole_size = search_end - search_start;
1498 if (contains_pending_extent(transaction, device, &search_start,
1500 btrfs_release_path(path);
1504 if (hole_size > max_hole_size) {
1505 max_hole_start = search_start;
1506 max_hole_size = hole_size;
1511 if (max_hole_size < num_bytes)
1517 btrfs_free_path(path);
1518 *start = max_hole_start;
1520 *len = max_hole_size;
1524 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1525 struct btrfs_device *device, u64 num_bytes,
1526 u64 *start, u64 *len)
1528 /* FIXME use last free of some kind */
1529 return find_free_dev_extent_start(trans->transaction, device,
1530 num_bytes, 0, start, len);
1533 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1534 struct btrfs_device *device,
1535 u64 start, u64 *dev_extent_len)
1537 struct btrfs_fs_info *fs_info = device->fs_info;
1538 struct btrfs_root *root = fs_info->dev_root;
1540 struct btrfs_path *path;
1541 struct btrfs_key key;
1542 struct btrfs_key found_key;
1543 struct extent_buffer *leaf = NULL;
1544 struct btrfs_dev_extent *extent = NULL;
1546 path = btrfs_alloc_path();
1550 key.objectid = device->devid;
1552 key.type = BTRFS_DEV_EXTENT_KEY;
1554 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1556 ret = btrfs_previous_item(root, path, key.objectid,
1557 BTRFS_DEV_EXTENT_KEY);
1560 leaf = path->nodes[0];
1561 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1562 extent = btrfs_item_ptr(leaf, path->slots[0],
1563 struct btrfs_dev_extent);
1564 BUG_ON(found_key.offset > start || found_key.offset +
1565 btrfs_dev_extent_length(leaf, extent) < start);
1567 btrfs_release_path(path);
1569 } else if (ret == 0) {
1570 leaf = path->nodes[0];
1571 extent = btrfs_item_ptr(leaf, path->slots[0],
1572 struct btrfs_dev_extent);
1574 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1578 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1580 ret = btrfs_del_item(trans, root, path);
1582 btrfs_handle_fs_error(fs_info, ret,
1583 "Failed to remove dev extent item");
1585 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1588 btrfs_free_path(path);
1592 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1593 struct btrfs_device *device,
1594 u64 chunk_offset, u64 start, u64 num_bytes)
1597 struct btrfs_path *path;
1598 struct btrfs_fs_info *fs_info = device->fs_info;
1599 struct btrfs_root *root = fs_info->dev_root;
1600 struct btrfs_dev_extent *extent;
1601 struct extent_buffer *leaf;
1602 struct btrfs_key key;
1604 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1605 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1606 path = btrfs_alloc_path();
1610 key.objectid = device->devid;
1612 key.type = BTRFS_DEV_EXTENT_KEY;
1613 ret = btrfs_insert_empty_item(trans, root, path, &key,
1618 leaf = path->nodes[0];
1619 extent = btrfs_item_ptr(leaf, path->slots[0],
1620 struct btrfs_dev_extent);
1621 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1622 BTRFS_CHUNK_TREE_OBJECTID);
1623 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1624 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1625 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1627 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1628 btrfs_mark_buffer_dirty(leaf);
1630 btrfs_free_path(path);
1634 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1636 struct extent_map_tree *em_tree;
1637 struct extent_map *em;
1641 em_tree = &fs_info->mapping_tree.map_tree;
1642 read_lock(&em_tree->lock);
1643 n = rb_last(&em_tree->map);
1645 em = rb_entry(n, struct extent_map, rb_node);
1646 ret = em->start + em->len;
1648 read_unlock(&em_tree->lock);
1653 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1657 struct btrfs_key key;
1658 struct btrfs_key found_key;
1659 struct btrfs_path *path;
1661 path = btrfs_alloc_path();
1665 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1666 key.type = BTRFS_DEV_ITEM_KEY;
1667 key.offset = (u64)-1;
1669 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1673 BUG_ON(ret == 0); /* Corruption */
1675 ret = btrfs_previous_item(fs_info->chunk_root, path,
1676 BTRFS_DEV_ITEMS_OBJECTID,
1677 BTRFS_DEV_ITEM_KEY);
1681 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1683 *devid_ret = found_key.offset + 1;
1687 btrfs_free_path(path);
1692 * the device information is stored in the chunk root
1693 * the btrfs_device struct should be fully filled in
1695 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1696 struct btrfs_device *device)
1699 struct btrfs_path *path;
1700 struct btrfs_dev_item *dev_item;
1701 struct extent_buffer *leaf;
1702 struct btrfs_key key;
1705 path = btrfs_alloc_path();
1709 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1710 key.type = BTRFS_DEV_ITEM_KEY;
1711 key.offset = device->devid;
1713 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1714 &key, sizeof(*dev_item));
1718 leaf = path->nodes[0];
1719 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1721 btrfs_set_device_id(leaf, dev_item, device->devid);
1722 btrfs_set_device_generation(leaf, dev_item, 0);
1723 btrfs_set_device_type(leaf, dev_item, device->type);
1724 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1725 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1726 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1727 btrfs_set_device_total_bytes(leaf, dev_item,
1728 btrfs_device_get_disk_total_bytes(device));
1729 btrfs_set_device_bytes_used(leaf, dev_item,
1730 btrfs_device_get_bytes_used(device));
1731 btrfs_set_device_group(leaf, dev_item, 0);
1732 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1733 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1734 btrfs_set_device_start_offset(leaf, dev_item, 0);
1736 ptr = btrfs_device_uuid(dev_item);
1737 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1738 ptr = btrfs_device_fsid(dev_item);
1739 write_extent_buffer(leaf, trans->fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1740 btrfs_mark_buffer_dirty(leaf);
1744 btrfs_free_path(path);
1749 * Function to update ctime/mtime for a given device path.
1750 * Mainly used for ctime/mtime based probe like libblkid.
1752 static void update_dev_time(const char *path_name)
1756 filp = filp_open(path_name, O_RDWR, 0);
1759 file_update_time(filp);
1760 filp_close(filp, NULL);
1763 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1764 struct btrfs_device *device)
1766 struct btrfs_root *root = fs_info->chunk_root;
1768 struct btrfs_path *path;
1769 struct btrfs_key key;
1770 struct btrfs_trans_handle *trans;
1772 path = btrfs_alloc_path();
1776 trans = btrfs_start_transaction(root, 0);
1777 if (IS_ERR(trans)) {
1778 btrfs_free_path(path);
1779 return PTR_ERR(trans);
1781 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1782 key.type = BTRFS_DEV_ITEM_KEY;
1783 key.offset = device->devid;
1785 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1789 btrfs_abort_transaction(trans, ret);
1790 btrfs_end_transaction(trans);
1794 ret = btrfs_del_item(trans, root, path);
1796 btrfs_abort_transaction(trans, ret);
1797 btrfs_end_transaction(trans);
1801 btrfs_free_path(path);
1803 ret = btrfs_commit_transaction(trans);
1808 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1809 * filesystem. It's up to the caller to adjust that number regarding eg. device
1812 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1820 seq = read_seqbegin(&fs_info->profiles_lock);
1822 all_avail = fs_info->avail_data_alloc_bits |
1823 fs_info->avail_system_alloc_bits |
1824 fs_info->avail_metadata_alloc_bits;
1825 } while (read_seqretry(&fs_info->profiles_lock, seq));
1827 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1828 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1831 if (num_devices < btrfs_raid_array[i].devs_min) {
1832 int ret = btrfs_raid_array[i].mindev_error;
1842 static struct btrfs_device * btrfs_find_next_active_device(
1843 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1845 struct btrfs_device *next_device;
1847 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1848 if (next_device != device &&
1849 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1850 && next_device->bdev)
1858 * Helper function to check if the given device is part of s_bdev / latest_bdev
1859 * and replace it with the provided or the next active device, in the context
1860 * where this function called, there should be always be another device (or
1861 * this_dev) which is active.
1863 void btrfs_assign_next_active_device(struct btrfs_device *device,
1864 struct btrfs_device *this_dev)
1866 struct btrfs_fs_info *fs_info = device->fs_info;
1867 struct btrfs_device *next_device;
1870 next_device = this_dev;
1872 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1874 ASSERT(next_device);
1876 if (fs_info->sb->s_bdev &&
1877 (fs_info->sb->s_bdev == device->bdev))
1878 fs_info->sb->s_bdev = next_device->bdev;
1880 if (fs_info->fs_devices->latest_bdev == device->bdev)
1881 fs_info->fs_devices->latest_bdev = next_device->bdev;
1884 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1887 struct btrfs_device *device;
1888 struct btrfs_fs_devices *cur_devices;
1889 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1893 mutex_lock(&uuid_mutex);
1895 num_devices = fs_devices->num_devices;
1896 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1897 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1898 WARN_ON(num_devices < 1);
1901 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1903 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1907 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1912 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1913 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1917 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1918 fs_info->fs_devices->rw_devices == 1) {
1919 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1923 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1924 mutex_lock(&fs_info->chunk_mutex);
1925 list_del_init(&device->dev_alloc_list);
1926 device->fs_devices->rw_devices--;
1927 mutex_unlock(&fs_info->chunk_mutex);
1930 mutex_unlock(&uuid_mutex);
1931 ret = btrfs_shrink_device(device, 0);
1932 mutex_lock(&uuid_mutex);
1937 * TODO: the superblock still includes this device in its num_devices
1938 * counter although write_all_supers() is not locked out. This
1939 * could give a filesystem state which requires a degraded mount.
1941 ret = btrfs_rm_dev_item(fs_info, device);
1945 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
1946 btrfs_scrub_cancel_dev(fs_info, device);
1949 * the device list mutex makes sure that we don't change
1950 * the device list while someone else is writing out all
1951 * the device supers. Whoever is writing all supers, should
1952 * lock the device list mutex before getting the number of
1953 * devices in the super block (super_copy). Conversely,
1954 * whoever updates the number of devices in the super block
1955 * (super_copy) should hold the device list mutex.
1959 * In normal cases the cur_devices == fs_devices. But in case
1960 * of deleting a seed device, the cur_devices should point to
1961 * its own fs_devices listed under the fs_devices->seed.
1963 cur_devices = device->fs_devices;
1964 mutex_lock(&fs_devices->device_list_mutex);
1965 list_del_rcu(&device->dev_list);
1967 cur_devices->num_devices--;
1968 cur_devices->total_devices--;
1969 /* Update total_devices of the parent fs_devices if it's seed */
1970 if (cur_devices != fs_devices)
1971 fs_devices->total_devices--;
1973 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1974 cur_devices->missing_devices--;
1976 btrfs_assign_next_active_device(device, NULL);
1979 cur_devices->open_devices--;
1980 /* remove sysfs entry */
1981 btrfs_sysfs_rm_device_link(fs_devices, device);
1984 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1985 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
1986 mutex_unlock(&fs_devices->device_list_mutex);
1989 * at this point, the device is zero sized and detached from
1990 * the devices list. All that's left is to zero out the old
1991 * supers and free the device.
1993 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
1994 btrfs_scratch_superblocks(device->bdev, device->name->str);
1996 btrfs_close_bdev(device);
1997 call_rcu(&device->rcu, free_device_rcu);
1999 if (cur_devices->open_devices == 0) {
2000 while (fs_devices) {
2001 if (fs_devices->seed == cur_devices) {
2002 fs_devices->seed = cur_devices->seed;
2005 fs_devices = fs_devices->seed;
2007 cur_devices->seed = NULL;
2008 close_fs_devices(cur_devices);
2009 free_fs_devices(cur_devices);
2013 mutex_unlock(&uuid_mutex);
2017 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2018 mutex_lock(&fs_info->chunk_mutex);
2019 list_add(&device->dev_alloc_list,
2020 &fs_devices->alloc_list);
2021 device->fs_devices->rw_devices++;
2022 mutex_unlock(&fs_info->chunk_mutex);
2027 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2029 struct btrfs_fs_devices *fs_devices;
2031 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2034 * in case of fs with no seed, srcdev->fs_devices will point
2035 * to fs_devices of fs_info. However when the dev being replaced is
2036 * a seed dev it will point to the seed's local fs_devices. In short
2037 * srcdev will have its correct fs_devices in both the cases.
2039 fs_devices = srcdev->fs_devices;
2041 list_del_rcu(&srcdev->dev_list);
2042 list_del(&srcdev->dev_alloc_list);
2043 fs_devices->num_devices--;
2044 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2045 fs_devices->missing_devices--;
2047 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2048 fs_devices->rw_devices--;
2051 fs_devices->open_devices--;
2054 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2055 struct btrfs_device *srcdev)
2057 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2059 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2060 /* zero out the old super if it is writable */
2061 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2064 btrfs_close_bdev(srcdev);
2065 call_rcu(&srcdev->rcu, free_device_rcu);
2067 /* if this is no devs we rather delete the fs_devices */
2068 if (!fs_devices->num_devices) {
2069 struct btrfs_fs_devices *tmp_fs_devices;
2072 * On a mounted FS, num_devices can't be zero unless it's a
2073 * seed. In case of a seed device being replaced, the replace
2074 * target added to the sprout FS, so there will be no more
2075 * device left under the seed FS.
2077 ASSERT(fs_devices->seeding);
2079 tmp_fs_devices = fs_info->fs_devices;
2080 while (tmp_fs_devices) {
2081 if (tmp_fs_devices->seed == fs_devices) {
2082 tmp_fs_devices->seed = fs_devices->seed;
2085 tmp_fs_devices = tmp_fs_devices->seed;
2087 fs_devices->seed = NULL;
2088 close_fs_devices(fs_devices);
2089 free_fs_devices(fs_devices);
2093 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2095 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2098 mutex_lock(&fs_devices->device_list_mutex);
2100 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2103 fs_devices->open_devices--;
2105 fs_devices->num_devices--;
2107 btrfs_assign_next_active_device(tgtdev, NULL);
2109 list_del_rcu(&tgtdev->dev_list);
2111 mutex_unlock(&fs_devices->device_list_mutex);
2114 * The update_dev_time() with in btrfs_scratch_superblocks()
2115 * may lead to a call to btrfs_show_devname() which will try
2116 * to hold device_list_mutex. And here this device
2117 * is already out of device list, so we don't have to hold
2118 * the device_list_mutex lock.
2120 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2122 btrfs_close_bdev(tgtdev);
2123 call_rcu(&tgtdev->rcu, free_device_rcu);
2126 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2127 const char *device_path,
2128 struct btrfs_device **device)
2131 struct btrfs_super_block *disk_super;
2134 struct block_device *bdev;
2135 struct buffer_head *bh;
2138 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2139 fs_info->bdev_holder, 0, &bdev, &bh);
2142 disk_super = (struct btrfs_super_block *)bh->b_data;
2143 devid = btrfs_stack_device_id(&disk_super->dev_item);
2144 dev_uuid = disk_super->dev_item.uuid;
2145 *device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2146 disk_super->fsid, true);
2150 blkdev_put(bdev, FMODE_READ);
2154 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2155 const char *device_path,
2156 struct btrfs_device **device)
2159 if (strcmp(device_path, "missing") == 0) {
2160 struct list_head *devices;
2161 struct btrfs_device *tmp;
2163 devices = &fs_info->fs_devices->devices;
2164 list_for_each_entry(tmp, devices, dev_list) {
2165 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2166 &tmp->dev_state) && !tmp->bdev) {
2173 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2177 return btrfs_find_device_by_path(fs_info, device_path, device);
2182 * Lookup a device given by device id, or the path if the id is 0.
2184 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2185 const char *devpath,
2186 struct btrfs_device **device)
2192 *device = btrfs_find_device(fs_info->fs_devices, devid,
2197 if (!devpath || !devpath[0])
2200 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2207 * does all the dirty work required for changing file system's UUID.
2209 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2211 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2212 struct btrfs_fs_devices *old_devices;
2213 struct btrfs_fs_devices *seed_devices;
2214 struct btrfs_super_block *disk_super = fs_info->super_copy;
2215 struct btrfs_device *device;
2218 lockdep_assert_held(&uuid_mutex);
2219 if (!fs_devices->seeding)
2222 seed_devices = alloc_fs_devices(NULL);
2223 if (IS_ERR(seed_devices))
2224 return PTR_ERR(seed_devices);
2226 old_devices = clone_fs_devices(fs_devices);
2227 if (IS_ERR(old_devices)) {
2228 kfree(seed_devices);
2229 return PTR_ERR(old_devices);
2232 list_add(&old_devices->fs_list, &fs_uuids);
2234 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2235 seed_devices->opened = 1;
2236 INIT_LIST_HEAD(&seed_devices->devices);
2237 INIT_LIST_HEAD(&seed_devices->alloc_list);
2238 mutex_init(&seed_devices->device_list_mutex);
2240 mutex_lock(&fs_devices->device_list_mutex);
2241 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2243 list_for_each_entry(device, &seed_devices->devices, dev_list)
2244 device->fs_devices = seed_devices;
2246 mutex_lock(&fs_info->chunk_mutex);
2247 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2248 mutex_unlock(&fs_info->chunk_mutex);
2250 fs_devices->seeding = 0;
2251 fs_devices->num_devices = 0;
2252 fs_devices->open_devices = 0;
2253 fs_devices->missing_devices = 0;
2254 fs_devices->rotating = 0;
2255 fs_devices->seed = seed_devices;
2257 generate_random_uuid(fs_devices->fsid);
2258 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2259 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2260 mutex_unlock(&fs_devices->device_list_mutex);
2262 super_flags = btrfs_super_flags(disk_super) &
2263 ~BTRFS_SUPER_FLAG_SEEDING;
2264 btrfs_set_super_flags(disk_super, super_flags);
2270 * Store the expected generation for seed devices in device items.
2272 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2273 struct btrfs_fs_info *fs_info)
2275 struct btrfs_root *root = fs_info->chunk_root;
2276 struct btrfs_path *path;
2277 struct extent_buffer *leaf;
2278 struct btrfs_dev_item *dev_item;
2279 struct btrfs_device *device;
2280 struct btrfs_key key;
2281 u8 fs_uuid[BTRFS_FSID_SIZE];
2282 u8 dev_uuid[BTRFS_UUID_SIZE];
2286 path = btrfs_alloc_path();
2290 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2292 key.type = BTRFS_DEV_ITEM_KEY;
2295 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2299 leaf = path->nodes[0];
2301 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2302 ret = btrfs_next_leaf(root, path);
2307 leaf = path->nodes[0];
2308 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2309 btrfs_release_path(path);
2313 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2314 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2315 key.type != BTRFS_DEV_ITEM_KEY)
2318 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2319 struct btrfs_dev_item);
2320 devid = btrfs_device_id(leaf, dev_item);
2321 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2323 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2325 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2327 BUG_ON(!device); /* Logic error */
2329 if (device->fs_devices->seeding) {
2330 btrfs_set_device_generation(leaf, dev_item,
2331 device->generation);
2332 btrfs_mark_buffer_dirty(leaf);
2340 btrfs_free_path(path);
2344 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2346 struct btrfs_root *root = fs_info->dev_root;
2347 struct request_queue *q;
2348 struct btrfs_trans_handle *trans;
2349 struct btrfs_device *device;
2350 struct block_device *bdev;
2351 struct super_block *sb = fs_info->sb;
2352 struct rcu_string *name;
2353 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2354 u64 orig_super_total_bytes;
2355 u64 orig_super_num_devices;
2356 int seeding_dev = 0;
2358 bool unlocked = false;
2360 if (sb_rdonly(sb) && !fs_devices->seeding)
2363 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2364 fs_info->bdev_holder);
2366 return PTR_ERR(bdev);
2368 if (fs_devices->seeding) {
2370 down_write(&sb->s_umount);
2371 mutex_lock(&uuid_mutex);
2374 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2376 mutex_lock(&fs_devices->device_list_mutex);
2377 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2378 if (device->bdev == bdev) {
2381 &fs_devices->device_list_mutex);
2385 mutex_unlock(&fs_devices->device_list_mutex);
2387 device = btrfs_alloc_device(fs_info, NULL, NULL);
2388 if (IS_ERR(device)) {
2389 /* we can safely leave the fs_devices entry around */
2390 ret = PTR_ERR(device);
2394 name = rcu_string_strdup(device_path, GFP_KERNEL);
2397 goto error_free_device;
2399 rcu_assign_pointer(device->name, name);
2401 trans = btrfs_start_transaction(root, 0);
2402 if (IS_ERR(trans)) {
2403 ret = PTR_ERR(trans);
2404 goto error_free_device;
2407 q = bdev_get_queue(bdev);
2408 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2409 device->generation = trans->transid;
2410 device->io_width = fs_info->sectorsize;
2411 device->io_align = fs_info->sectorsize;
2412 device->sector_size = fs_info->sectorsize;
2413 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2414 fs_info->sectorsize);
2415 device->disk_total_bytes = device->total_bytes;
2416 device->commit_total_bytes = device->total_bytes;
2417 device->fs_info = fs_info;
2418 device->bdev = bdev;
2419 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2420 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2421 device->mode = FMODE_EXCL;
2422 device->dev_stats_valid = 1;
2423 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2426 sb->s_flags &= ~SB_RDONLY;
2427 ret = btrfs_prepare_sprout(fs_info);
2429 btrfs_abort_transaction(trans, ret);
2434 device->fs_devices = fs_devices;
2436 mutex_lock(&fs_devices->device_list_mutex);
2437 mutex_lock(&fs_info->chunk_mutex);
2438 list_add_rcu(&device->dev_list, &fs_devices->devices);
2439 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2440 fs_devices->num_devices++;
2441 fs_devices->open_devices++;
2442 fs_devices->rw_devices++;
2443 fs_devices->total_devices++;
2444 fs_devices->total_rw_bytes += device->total_bytes;
2446 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2448 if (!blk_queue_nonrot(q))
2449 fs_devices->rotating = 1;
2451 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2452 btrfs_set_super_total_bytes(fs_info->super_copy,
2453 round_down(orig_super_total_bytes + device->total_bytes,
2454 fs_info->sectorsize));
2456 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2457 btrfs_set_super_num_devices(fs_info->super_copy,
2458 orig_super_num_devices + 1);
2461 * we've got more storage, clear any full flags on the space
2464 btrfs_clear_space_info_full(fs_info);
2466 mutex_unlock(&fs_info->chunk_mutex);
2468 /* Add sysfs device entry */
2469 btrfs_sysfs_add_device_link(fs_devices, device);
2471 mutex_unlock(&fs_devices->device_list_mutex);
2474 mutex_lock(&fs_info->chunk_mutex);
2475 ret = init_first_rw_device(trans, fs_info);
2476 mutex_unlock(&fs_info->chunk_mutex);
2478 btrfs_abort_transaction(trans, ret);
2483 ret = btrfs_add_dev_item(trans, device);
2485 btrfs_abort_transaction(trans, ret);
2490 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2492 ret = btrfs_finish_sprout(trans, fs_info);
2494 btrfs_abort_transaction(trans, ret);
2498 /* Sprouting would change fsid of the mounted root,
2499 * so rename the fsid on the sysfs
2501 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2503 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2505 "sysfs: failed to create fsid for sprout");
2508 ret = btrfs_commit_transaction(trans);
2511 mutex_unlock(&uuid_mutex);
2512 up_write(&sb->s_umount);
2515 if (ret) /* transaction commit */
2518 ret = btrfs_relocate_sys_chunks(fs_info);
2520 btrfs_handle_fs_error(fs_info, ret,
2521 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2522 trans = btrfs_attach_transaction(root);
2523 if (IS_ERR(trans)) {
2524 if (PTR_ERR(trans) == -ENOENT)
2526 ret = PTR_ERR(trans);
2530 ret = btrfs_commit_transaction(trans);
2533 /* Update ctime/mtime for libblkid */
2534 update_dev_time(device_path);
2538 btrfs_sysfs_rm_device_link(fs_devices, device);
2539 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2540 mutex_lock(&fs_info->chunk_mutex);
2541 list_del_rcu(&device->dev_list);
2542 list_del(&device->dev_alloc_list);
2543 fs_info->fs_devices->num_devices--;
2544 fs_info->fs_devices->open_devices--;
2545 fs_info->fs_devices->rw_devices--;
2546 fs_info->fs_devices->total_devices--;
2547 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2548 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2549 btrfs_set_super_total_bytes(fs_info->super_copy,
2550 orig_super_total_bytes);
2551 btrfs_set_super_num_devices(fs_info->super_copy,
2552 orig_super_num_devices);
2553 mutex_unlock(&fs_info->chunk_mutex);
2554 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2557 sb->s_flags |= SB_RDONLY;
2559 btrfs_end_transaction(trans);
2561 btrfs_free_device(device);
2563 blkdev_put(bdev, FMODE_EXCL);
2564 if (seeding_dev && !unlocked) {
2565 mutex_unlock(&uuid_mutex);
2566 up_write(&sb->s_umount);
2571 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2572 struct btrfs_device *device)
2575 struct btrfs_path *path;
2576 struct btrfs_root *root = device->fs_info->chunk_root;
2577 struct btrfs_dev_item *dev_item;
2578 struct extent_buffer *leaf;
2579 struct btrfs_key key;
2581 path = btrfs_alloc_path();
2585 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2586 key.type = BTRFS_DEV_ITEM_KEY;
2587 key.offset = device->devid;
2589 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2598 leaf = path->nodes[0];
2599 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2601 btrfs_set_device_id(leaf, dev_item, device->devid);
2602 btrfs_set_device_type(leaf, dev_item, device->type);
2603 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2604 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2605 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2606 btrfs_set_device_total_bytes(leaf, dev_item,
2607 btrfs_device_get_disk_total_bytes(device));
2608 btrfs_set_device_bytes_used(leaf, dev_item,
2609 btrfs_device_get_bytes_used(device));
2610 btrfs_mark_buffer_dirty(leaf);
2613 btrfs_free_path(path);
2617 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2618 struct btrfs_device *device, u64 new_size)
2620 struct btrfs_fs_info *fs_info = device->fs_info;
2621 struct btrfs_super_block *super_copy = fs_info->super_copy;
2622 struct btrfs_fs_devices *fs_devices;
2626 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2629 new_size = round_down(new_size, fs_info->sectorsize);
2631 mutex_lock(&fs_info->chunk_mutex);
2632 old_total = btrfs_super_total_bytes(super_copy);
2633 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2635 if (new_size <= device->total_bytes ||
2636 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2637 mutex_unlock(&fs_info->chunk_mutex);
2641 fs_devices = fs_info->fs_devices;
2643 btrfs_set_super_total_bytes(super_copy,
2644 round_down(old_total + diff, fs_info->sectorsize));
2645 device->fs_devices->total_rw_bytes += diff;
2647 btrfs_device_set_total_bytes(device, new_size);
2648 btrfs_device_set_disk_total_bytes(device, new_size);
2649 btrfs_clear_space_info_full(device->fs_info);
2650 if (list_empty(&device->resized_list))
2651 list_add_tail(&device->resized_list,
2652 &fs_devices->resized_devices);
2653 mutex_unlock(&fs_info->chunk_mutex);
2655 return btrfs_update_device(trans, device);
2658 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2660 struct btrfs_fs_info *fs_info = trans->fs_info;
2661 struct btrfs_root *root = fs_info->chunk_root;
2663 struct btrfs_path *path;
2664 struct btrfs_key key;
2666 path = btrfs_alloc_path();
2670 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2671 key.offset = chunk_offset;
2672 key.type = BTRFS_CHUNK_ITEM_KEY;
2674 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2677 else if (ret > 0) { /* Logic error or corruption */
2678 btrfs_handle_fs_error(fs_info, -ENOENT,
2679 "Failed lookup while freeing chunk.");
2684 ret = btrfs_del_item(trans, root, path);
2686 btrfs_handle_fs_error(fs_info, ret,
2687 "Failed to delete chunk item.");
2689 btrfs_free_path(path);
2693 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2695 struct btrfs_super_block *super_copy = fs_info->super_copy;
2696 struct btrfs_disk_key *disk_key;
2697 struct btrfs_chunk *chunk;
2704 struct btrfs_key key;
2706 mutex_lock(&fs_info->chunk_mutex);
2707 array_size = btrfs_super_sys_array_size(super_copy);
2709 ptr = super_copy->sys_chunk_array;
2712 while (cur < array_size) {
2713 disk_key = (struct btrfs_disk_key *)ptr;
2714 btrfs_disk_key_to_cpu(&key, disk_key);
2716 len = sizeof(*disk_key);
2718 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2719 chunk = (struct btrfs_chunk *)(ptr + len);
2720 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2721 len += btrfs_chunk_item_size(num_stripes);
2726 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2727 key.offset == chunk_offset) {
2728 memmove(ptr, ptr + len, array_size - (cur + len));
2730 btrfs_set_super_sys_array_size(super_copy, array_size);
2736 mutex_unlock(&fs_info->chunk_mutex);
2740 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2741 u64 logical, u64 length)
2743 struct extent_map_tree *em_tree;
2744 struct extent_map *em;
2746 em_tree = &fs_info->mapping_tree.map_tree;
2747 read_lock(&em_tree->lock);
2748 em = lookup_extent_mapping(em_tree, logical, length);
2749 read_unlock(&em_tree->lock);
2752 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2754 return ERR_PTR(-EINVAL);
2757 if (em->start > logical || em->start + em->len < logical) {
2759 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2760 logical, length, em->start, em->start + em->len);
2761 free_extent_map(em);
2762 return ERR_PTR(-EINVAL);
2765 /* callers are responsible for dropping em's ref. */
2769 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2771 struct btrfs_fs_info *fs_info = trans->fs_info;
2772 struct extent_map *em;
2773 struct map_lookup *map;
2774 u64 dev_extent_len = 0;
2776 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2778 em = get_chunk_map(fs_info, chunk_offset, 1);
2781 * This is a logic error, but we don't want to just rely on the
2782 * user having built with ASSERT enabled, so if ASSERT doesn't
2783 * do anything we still error out.
2788 map = em->map_lookup;
2789 mutex_lock(&fs_info->chunk_mutex);
2790 check_system_chunk(trans, map->type);
2791 mutex_unlock(&fs_info->chunk_mutex);
2794 * Take the device list mutex to prevent races with the final phase of
2795 * a device replace operation that replaces the device object associated
2796 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2798 mutex_lock(&fs_devices->device_list_mutex);
2799 for (i = 0; i < map->num_stripes; i++) {
2800 struct btrfs_device *device = map->stripes[i].dev;
2801 ret = btrfs_free_dev_extent(trans, device,
2802 map->stripes[i].physical,
2805 mutex_unlock(&fs_devices->device_list_mutex);
2806 btrfs_abort_transaction(trans, ret);
2810 if (device->bytes_used > 0) {
2811 mutex_lock(&fs_info->chunk_mutex);
2812 btrfs_device_set_bytes_used(device,
2813 device->bytes_used - dev_extent_len);
2814 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2815 btrfs_clear_space_info_full(fs_info);
2816 mutex_unlock(&fs_info->chunk_mutex);
2819 if (map->stripes[i].dev) {
2820 ret = btrfs_update_device(trans, map->stripes[i].dev);
2822 mutex_unlock(&fs_devices->device_list_mutex);
2823 btrfs_abort_transaction(trans, ret);
2828 mutex_unlock(&fs_devices->device_list_mutex);
2830 ret = btrfs_free_chunk(trans, chunk_offset);
2832 btrfs_abort_transaction(trans, ret);
2836 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2838 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2839 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2841 btrfs_abort_transaction(trans, ret);
2846 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2848 btrfs_abort_transaction(trans, ret);
2854 free_extent_map(em);
2858 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2860 struct btrfs_root *root = fs_info->chunk_root;
2861 struct btrfs_trans_handle *trans;
2865 * Prevent races with automatic removal of unused block groups.
2866 * After we relocate and before we remove the chunk with offset
2867 * chunk_offset, automatic removal of the block group can kick in,
2868 * resulting in a failure when calling btrfs_remove_chunk() below.
2870 * Make sure to acquire this mutex before doing a tree search (dev
2871 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2872 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2873 * we release the path used to search the chunk/dev tree and before
2874 * the current task acquires this mutex and calls us.
2876 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2878 ret = btrfs_can_relocate(fs_info, chunk_offset);
2882 /* step one, relocate all the extents inside this chunk */
2883 btrfs_scrub_pause(fs_info);
2884 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2885 btrfs_scrub_continue(fs_info);
2890 * We add the kobjects here (and after forcing data chunk creation)
2891 * since relocation is the only place we'll create chunks of a new
2892 * type at runtime. The only place where we'll remove the last
2893 * chunk of a type is the call immediately below this one. Even
2894 * so, we're protected against races with the cleaner thread since
2895 * we're covered by the delete_unused_bgs_mutex.
2897 btrfs_add_raid_kobjects(fs_info);
2899 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2901 if (IS_ERR(trans)) {
2902 ret = PTR_ERR(trans);
2903 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2908 * step two, delete the device extents and the
2909 * chunk tree entries
2911 ret = btrfs_remove_chunk(trans, chunk_offset);
2912 btrfs_end_transaction(trans);
2916 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2918 struct btrfs_root *chunk_root = fs_info->chunk_root;
2919 struct btrfs_path *path;
2920 struct extent_buffer *leaf;
2921 struct btrfs_chunk *chunk;
2922 struct btrfs_key key;
2923 struct btrfs_key found_key;
2925 bool retried = false;
2929 path = btrfs_alloc_path();
2934 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2935 key.offset = (u64)-1;
2936 key.type = BTRFS_CHUNK_ITEM_KEY;
2939 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2940 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2942 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2945 BUG_ON(ret == 0); /* Corruption */
2947 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2950 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2956 leaf = path->nodes[0];
2957 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2959 chunk = btrfs_item_ptr(leaf, path->slots[0],
2960 struct btrfs_chunk);
2961 chunk_type = btrfs_chunk_type(leaf, chunk);
2962 btrfs_release_path(path);
2964 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2965 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
2971 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2973 if (found_key.offset == 0)
2975 key.offset = found_key.offset - 1;
2978 if (failed && !retried) {
2982 } else if (WARN_ON(failed && retried)) {
2986 btrfs_free_path(path);
2991 * return 1 : allocate a data chunk successfully,
2992 * return <0: errors during allocating a data chunk,
2993 * return 0 : no need to allocate a data chunk.
2995 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
2998 struct btrfs_block_group_cache *cache;
3002 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3004 chunk_type = cache->flags;
3005 btrfs_put_block_group(cache);
3007 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3008 spin_lock(&fs_info->data_sinfo->lock);
3009 bytes_used = fs_info->data_sinfo->bytes_used;
3010 spin_unlock(&fs_info->data_sinfo->lock);
3013 struct btrfs_trans_handle *trans;
3016 trans = btrfs_join_transaction(fs_info->tree_root);
3018 return PTR_ERR(trans);
3020 ret = btrfs_force_chunk_alloc(trans,
3021 BTRFS_BLOCK_GROUP_DATA);
3022 btrfs_end_transaction(trans);
3026 btrfs_add_raid_kobjects(fs_info);
3034 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3035 struct btrfs_balance_control *bctl)
3037 struct btrfs_root *root = fs_info->tree_root;
3038 struct btrfs_trans_handle *trans;
3039 struct btrfs_balance_item *item;
3040 struct btrfs_disk_balance_args disk_bargs;
3041 struct btrfs_path *path;
3042 struct extent_buffer *leaf;
3043 struct btrfs_key key;
3046 path = btrfs_alloc_path();
3050 trans = btrfs_start_transaction(root, 0);
3051 if (IS_ERR(trans)) {
3052 btrfs_free_path(path);
3053 return PTR_ERR(trans);
3056 key.objectid = BTRFS_BALANCE_OBJECTID;
3057 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3060 ret = btrfs_insert_empty_item(trans, root, path, &key,
3065 leaf = path->nodes[0];
3066 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3068 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3070 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3071 btrfs_set_balance_data(leaf, item, &disk_bargs);
3072 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3073 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3074 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3075 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3077 btrfs_set_balance_flags(leaf, item, bctl->flags);
3079 btrfs_mark_buffer_dirty(leaf);
3081 btrfs_free_path(path);
3082 err = btrfs_commit_transaction(trans);
3088 static int del_balance_item(struct btrfs_fs_info *fs_info)
3090 struct btrfs_root *root = fs_info->tree_root;
3091 struct btrfs_trans_handle *trans;
3092 struct btrfs_path *path;
3093 struct btrfs_key key;
3096 path = btrfs_alloc_path();
3100 trans = btrfs_start_transaction(root, 0);
3101 if (IS_ERR(trans)) {
3102 btrfs_free_path(path);
3103 return PTR_ERR(trans);
3106 key.objectid = BTRFS_BALANCE_OBJECTID;
3107 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3110 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3118 ret = btrfs_del_item(trans, root, path);
3120 btrfs_free_path(path);
3121 err = btrfs_commit_transaction(trans);
3128 * This is a heuristic used to reduce the number of chunks balanced on
3129 * resume after balance was interrupted.
3131 static void update_balance_args(struct btrfs_balance_control *bctl)
3134 * Turn on soft mode for chunk types that were being converted.
3136 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3137 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3138 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3139 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3140 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3141 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3144 * Turn on usage filter if is not already used. The idea is
3145 * that chunks that we have already balanced should be
3146 * reasonably full. Don't do it for chunks that are being
3147 * converted - that will keep us from relocating unconverted
3148 * (albeit full) chunks.
3150 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3151 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3152 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3153 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3154 bctl->data.usage = 90;
3156 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3157 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3158 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3159 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3160 bctl->sys.usage = 90;
3162 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3163 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3164 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3165 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3166 bctl->meta.usage = 90;
3171 * Clear the balance status in fs_info and delete the balance item from disk.
3173 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3175 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3178 BUG_ON(!fs_info->balance_ctl);
3180 spin_lock(&fs_info->balance_lock);
3181 fs_info->balance_ctl = NULL;
3182 spin_unlock(&fs_info->balance_lock);
3185 ret = del_balance_item(fs_info);
3187 btrfs_handle_fs_error(fs_info, ret, NULL);
3191 * Balance filters. Return 1 if chunk should be filtered out
3192 * (should not be balanced).
3194 static int chunk_profiles_filter(u64 chunk_type,
3195 struct btrfs_balance_args *bargs)
3197 chunk_type = chunk_to_extended(chunk_type) &
3198 BTRFS_EXTENDED_PROFILE_MASK;
3200 if (bargs->profiles & chunk_type)
3206 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3207 struct btrfs_balance_args *bargs)
3209 struct btrfs_block_group_cache *cache;
3211 u64 user_thresh_min;
3212 u64 user_thresh_max;
3215 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3216 chunk_used = btrfs_block_group_used(&cache->item);
3218 if (bargs->usage_min == 0)
3219 user_thresh_min = 0;
3221 user_thresh_min = div_factor_fine(cache->key.offset,
3224 if (bargs->usage_max == 0)
3225 user_thresh_max = 1;
3226 else if (bargs->usage_max > 100)
3227 user_thresh_max = cache->key.offset;
3229 user_thresh_max = div_factor_fine(cache->key.offset,
3232 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3235 btrfs_put_block_group(cache);
3239 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3240 u64 chunk_offset, struct btrfs_balance_args *bargs)
3242 struct btrfs_block_group_cache *cache;
3243 u64 chunk_used, user_thresh;
3246 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3247 chunk_used = btrfs_block_group_used(&cache->item);
3249 if (bargs->usage_min == 0)
3251 else if (bargs->usage > 100)
3252 user_thresh = cache->key.offset;
3254 user_thresh = div_factor_fine(cache->key.offset,
3257 if (chunk_used < user_thresh)
3260 btrfs_put_block_group(cache);
3264 static int chunk_devid_filter(struct extent_buffer *leaf,
3265 struct btrfs_chunk *chunk,
3266 struct btrfs_balance_args *bargs)
3268 struct btrfs_stripe *stripe;
3269 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3272 for (i = 0; i < num_stripes; i++) {
3273 stripe = btrfs_stripe_nr(chunk, i);
3274 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3281 /* [pstart, pend) */
3282 static int chunk_drange_filter(struct extent_buffer *leaf,
3283 struct btrfs_chunk *chunk,
3284 struct btrfs_balance_args *bargs)
3286 struct btrfs_stripe *stripe;
3287 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3293 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3296 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3297 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3298 factor = num_stripes / 2;
3299 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3300 factor = num_stripes - 1;
3301 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3302 factor = num_stripes - 2;
3304 factor = num_stripes;
3307 for (i = 0; i < num_stripes; i++) {
3308 stripe = btrfs_stripe_nr(chunk, i);
3309 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3312 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3313 stripe_length = btrfs_chunk_length(leaf, chunk);
3314 stripe_length = div_u64(stripe_length, factor);
3316 if (stripe_offset < bargs->pend &&
3317 stripe_offset + stripe_length > bargs->pstart)
3324 /* [vstart, vend) */
3325 static int chunk_vrange_filter(struct extent_buffer *leaf,
3326 struct btrfs_chunk *chunk,
3328 struct btrfs_balance_args *bargs)
3330 if (chunk_offset < bargs->vend &&
3331 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3332 /* at least part of the chunk is inside this vrange */
3338 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3339 struct btrfs_chunk *chunk,
3340 struct btrfs_balance_args *bargs)
3342 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3344 if (bargs->stripes_min <= num_stripes
3345 && num_stripes <= bargs->stripes_max)
3351 static int chunk_soft_convert_filter(u64 chunk_type,
3352 struct btrfs_balance_args *bargs)
3354 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3357 chunk_type = chunk_to_extended(chunk_type) &
3358 BTRFS_EXTENDED_PROFILE_MASK;
3360 if (bargs->target == chunk_type)
3366 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3367 struct extent_buffer *leaf,
3368 struct btrfs_chunk *chunk, u64 chunk_offset)
3370 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3371 struct btrfs_balance_args *bargs = NULL;
3372 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3375 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3376 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3380 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3381 bargs = &bctl->data;
3382 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3384 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3385 bargs = &bctl->meta;
3387 /* profiles filter */
3388 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3389 chunk_profiles_filter(chunk_type, bargs)) {
3394 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3395 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3397 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3398 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3403 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3404 chunk_devid_filter(leaf, chunk, bargs)) {
3408 /* drange filter, makes sense only with devid filter */
3409 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3410 chunk_drange_filter(leaf, chunk, bargs)) {
3415 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3416 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3420 /* stripes filter */
3421 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3422 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3426 /* soft profile changing mode */
3427 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3428 chunk_soft_convert_filter(chunk_type, bargs)) {
3433 * limited by count, must be the last filter
3435 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3436 if (bargs->limit == 0)
3440 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3442 * Same logic as the 'limit' filter; the minimum cannot be
3443 * determined here because we do not have the global information
3444 * about the count of all chunks that satisfy the filters.
3446 if (bargs->limit_max == 0)
3455 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3457 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3458 struct btrfs_root *chunk_root = fs_info->chunk_root;
3459 struct btrfs_root *dev_root = fs_info->dev_root;
3460 struct list_head *devices;
3461 struct btrfs_device *device;
3465 struct btrfs_chunk *chunk;
3466 struct btrfs_path *path = NULL;
3467 struct btrfs_key key;
3468 struct btrfs_key found_key;
3469 struct btrfs_trans_handle *trans;
3470 struct extent_buffer *leaf;
3473 int enospc_errors = 0;
3474 bool counting = true;
3475 /* The single value limit and min/max limits use the same bytes in the */
3476 u64 limit_data = bctl->data.limit;
3477 u64 limit_meta = bctl->meta.limit;
3478 u64 limit_sys = bctl->sys.limit;
3482 int chunk_reserved = 0;
3484 /* step one make some room on all the devices */
3485 devices = &fs_info->fs_devices->devices;
3486 list_for_each_entry(device, devices, dev_list) {
3487 old_size = btrfs_device_get_total_bytes(device);
3488 size_to_free = div_factor(old_size, 1);
3489 size_to_free = min_t(u64, size_to_free, SZ_1M);
3490 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3491 btrfs_device_get_total_bytes(device) -
3492 btrfs_device_get_bytes_used(device) > size_to_free ||
3493 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3496 ret = btrfs_shrink_device(device, old_size - size_to_free);
3500 /* btrfs_shrink_device never returns ret > 0 */
3505 trans = btrfs_start_transaction(dev_root, 0);
3506 if (IS_ERR(trans)) {
3507 ret = PTR_ERR(trans);
3508 btrfs_info_in_rcu(fs_info,
3509 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3510 rcu_str_deref(device->name), ret,
3511 old_size, old_size - size_to_free);
3515 ret = btrfs_grow_device(trans, device, old_size);
3517 btrfs_end_transaction(trans);
3518 /* btrfs_grow_device never returns ret > 0 */
3520 btrfs_info_in_rcu(fs_info,
3521 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3522 rcu_str_deref(device->name), ret,
3523 old_size, old_size - size_to_free);
3527 btrfs_end_transaction(trans);
3530 /* step two, relocate all the chunks */
3531 path = btrfs_alloc_path();
3537 /* zero out stat counters */
3538 spin_lock(&fs_info->balance_lock);
3539 memset(&bctl->stat, 0, sizeof(bctl->stat));
3540 spin_unlock(&fs_info->balance_lock);
3544 * The single value limit and min/max limits use the same bytes
3547 bctl->data.limit = limit_data;
3548 bctl->meta.limit = limit_meta;
3549 bctl->sys.limit = limit_sys;
3551 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3552 key.offset = (u64)-1;
3553 key.type = BTRFS_CHUNK_ITEM_KEY;
3556 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3557 atomic_read(&fs_info->balance_cancel_req)) {
3562 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3563 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3565 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3570 * this shouldn't happen, it means the last relocate
3574 BUG(); /* FIXME break ? */
3576 ret = btrfs_previous_item(chunk_root, path, 0,
3577 BTRFS_CHUNK_ITEM_KEY);
3579 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3584 leaf = path->nodes[0];
3585 slot = path->slots[0];
3586 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3588 if (found_key.objectid != key.objectid) {
3589 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3593 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3594 chunk_type = btrfs_chunk_type(leaf, chunk);
3597 spin_lock(&fs_info->balance_lock);
3598 bctl->stat.considered++;
3599 spin_unlock(&fs_info->balance_lock);
3602 ret = should_balance_chunk(fs_info, leaf, chunk,
3605 btrfs_release_path(path);
3607 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3612 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3613 spin_lock(&fs_info->balance_lock);
3614 bctl->stat.expected++;
3615 spin_unlock(&fs_info->balance_lock);
3617 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3619 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3621 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3628 * Apply limit_min filter, no need to check if the LIMITS
3629 * filter is used, limit_min is 0 by default
3631 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3632 count_data < bctl->data.limit_min)
3633 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3634 count_meta < bctl->meta.limit_min)
3635 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3636 count_sys < bctl->sys.limit_min)) {
3637 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3641 if (!chunk_reserved) {
3643 * We may be relocating the only data chunk we have,
3644 * which could potentially end up with losing data's
3645 * raid profile, so lets allocate an empty one in
3648 ret = btrfs_may_alloc_data_chunk(fs_info,
3651 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3653 } else if (ret == 1) {
3658 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3659 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3660 if (ret && ret != -ENOSPC)
3662 if (ret == -ENOSPC) {
3665 spin_lock(&fs_info->balance_lock);
3666 bctl->stat.completed++;
3667 spin_unlock(&fs_info->balance_lock);
3670 if (found_key.offset == 0)
3672 key.offset = found_key.offset - 1;
3676 btrfs_release_path(path);
3681 btrfs_free_path(path);
3682 if (enospc_errors) {
3683 btrfs_info(fs_info, "%d enospc errors during balance",
3693 * alloc_profile_is_valid - see if a given profile is valid and reduced
3694 * @flags: profile to validate
3695 * @extended: if true @flags is treated as an extended profile
3697 static int alloc_profile_is_valid(u64 flags, int extended)
3699 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3700 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3702 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3704 /* 1) check that all other bits are zeroed */
3708 /* 2) see if profile is reduced */
3710 return !extended; /* "0" is valid for usual profiles */
3712 /* true if exactly one bit set */
3713 return (flags & (flags - 1)) == 0;
3716 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3718 /* cancel requested || normal exit path */
3719 return atomic_read(&fs_info->balance_cancel_req) ||
3720 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3721 atomic_read(&fs_info->balance_cancel_req) == 0);
3724 /* Non-zero return value signifies invalidity */
3725 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3728 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3729 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3730 (bctl_arg->target & ~allowed)));
3734 * Should be called with balance mutexe held
3736 int btrfs_balance(struct btrfs_fs_info *fs_info,
3737 struct btrfs_balance_control *bctl,
3738 struct btrfs_ioctl_balance_args *bargs)
3740 u64 meta_target, data_target;
3746 bool reducing_integrity;
3748 if (btrfs_fs_closing(fs_info) ||
3749 atomic_read(&fs_info->balance_pause_req) ||
3750 atomic_read(&fs_info->balance_cancel_req)) {
3755 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3756 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3760 * In case of mixed groups both data and meta should be picked,
3761 * and identical options should be given for both of them.
3763 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3764 if (mixed && (bctl->flags & allowed)) {
3765 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3766 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3767 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3769 "balance: mixed groups data and metadata options must be the same");
3775 num_devices = fs_info->fs_devices->num_devices;
3776 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
3777 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3778 BUG_ON(num_devices < 1);
3781 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
3782 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3783 if (num_devices > 1)
3784 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3785 if (num_devices > 2)
3786 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3787 if (num_devices > 3)
3788 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3789 BTRFS_BLOCK_GROUP_RAID6);
3790 if (validate_convert_profile(&bctl->data, allowed)) {
3791 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
3794 "balance: invalid convert data profile %s",
3795 get_raid_name(index));
3799 if (validate_convert_profile(&bctl->meta, allowed)) {
3800 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
3803 "balance: invalid convert metadata profile %s",
3804 get_raid_name(index));
3808 if (validate_convert_profile(&bctl->sys, allowed)) {
3809 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
3812 "balance: invalid convert system profile %s",
3813 get_raid_name(index));
3818 /* allow to reduce meta or sys integrity only if force set */
3819 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3820 BTRFS_BLOCK_GROUP_RAID10 |
3821 BTRFS_BLOCK_GROUP_RAID5 |
3822 BTRFS_BLOCK_GROUP_RAID6;
3824 seq = read_seqbegin(&fs_info->profiles_lock);
3826 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3827 (fs_info->avail_system_alloc_bits & allowed) &&
3828 !(bctl->sys.target & allowed)) ||
3829 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3830 (fs_info->avail_metadata_alloc_bits & allowed) &&
3831 !(bctl->meta.target & allowed)))
3832 reducing_integrity = true;
3834 reducing_integrity = false;
3836 /* if we're not converting, the target field is uninitialized */
3837 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3838 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3839 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3840 bctl->data.target : fs_info->avail_data_alloc_bits;
3841 } while (read_seqretry(&fs_info->profiles_lock, seq));
3843 if (reducing_integrity) {
3844 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3846 "balance: force reducing metadata integrity");
3849 "balance: reduces metadata integrity, use --force if you want this");
3855 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3856 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3857 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
3858 int data_index = btrfs_bg_flags_to_raid_index(data_target);
3861 "balance: metadata profile %s has lower redundancy than data profile %s",
3862 get_raid_name(meta_index), get_raid_name(data_index));
3865 ret = insert_balance_item(fs_info, bctl);
3866 if (ret && ret != -EEXIST)
3869 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3870 BUG_ON(ret == -EEXIST);
3871 BUG_ON(fs_info->balance_ctl);
3872 spin_lock(&fs_info->balance_lock);
3873 fs_info->balance_ctl = bctl;
3874 spin_unlock(&fs_info->balance_lock);
3876 BUG_ON(ret != -EEXIST);
3877 spin_lock(&fs_info->balance_lock);
3878 update_balance_args(bctl);
3879 spin_unlock(&fs_info->balance_lock);
3882 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
3883 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3884 mutex_unlock(&fs_info->balance_mutex);
3886 ret = __btrfs_balance(fs_info);
3888 mutex_lock(&fs_info->balance_mutex);
3889 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3892 memset(bargs, 0, sizeof(*bargs));
3893 btrfs_update_ioctl_balance_args(fs_info, bargs);
3896 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3897 balance_need_close(fs_info)) {
3898 reset_balance_state(fs_info);
3899 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3902 wake_up(&fs_info->balance_wait_q);
3906 if (bctl->flags & BTRFS_BALANCE_RESUME)
3907 reset_balance_state(fs_info);
3910 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3915 static int balance_kthread(void *data)
3917 struct btrfs_fs_info *fs_info = data;
3920 mutex_lock(&fs_info->balance_mutex);
3921 if (fs_info->balance_ctl) {
3922 btrfs_info(fs_info, "balance: resuming");
3923 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
3925 mutex_unlock(&fs_info->balance_mutex);
3930 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3932 struct task_struct *tsk;
3934 mutex_lock(&fs_info->balance_mutex);
3935 if (!fs_info->balance_ctl) {
3936 mutex_unlock(&fs_info->balance_mutex);
3939 mutex_unlock(&fs_info->balance_mutex);
3941 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
3942 btrfs_info(fs_info, "balance: resume skipped");
3947 * A ro->rw remount sequence should continue with the paused balance
3948 * regardless of who pauses it, system or the user as of now, so set
3951 spin_lock(&fs_info->balance_lock);
3952 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
3953 spin_unlock(&fs_info->balance_lock);
3955 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3956 return PTR_ERR_OR_ZERO(tsk);
3959 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3961 struct btrfs_balance_control *bctl;
3962 struct btrfs_balance_item *item;
3963 struct btrfs_disk_balance_args disk_bargs;
3964 struct btrfs_path *path;
3965 struct extent_buffer *leaf;
3966 struct btrfs_key key;
3969 path = btrfs_alloc_path();
3973 key.objectid = BTRFS_BALANCE_OBJECTID;
3974 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3977 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3980 if (ret > 0) { /* ret = -ENOENT; */
3985 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3991 leaf = path->nodes[0];
3992 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3994 bctl->flags = btrfs_balance_flags(leaf, item);
3995 bctl->flags |= BTRFS_BALANCE_RESUME;
3997 btrfs_balance_data(leaf, item, &disk_bargs);
3998 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3999 btrfs_balance_meta(leaf, item, &disk_bargs);
4000 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4001 btrfs_balance_sys(leaf, item, &disk_bargs);
4002 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4005 * This should never happen, as the paused balance state is recovered
4006 * during mount without any chance of other exclusive ops to collide.
4008 * This gives the exclusive op status to balance and keeps in paused
4009 * state until user intervention (cancel or umount). If the ownership
4010 * cannot be assigned, show a message but do not fail. The balance
4011 * is in a paused state and must have fs_info::balance_ctl properly
4014 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4016 "balance: cannot set exclusive op status, resume manually");
4018 btrfs_release_path(path);
4020 mutex_lock(&fs_info->balance_mutex);
4021 BUG_ON(fs_info->balance_ctl);
4022 spin_lock(&fs_info->balance_lock);
4023 fs_info->balance_ctl = bctl;
4024 spin_unlock(&fs_info->balance_lock);
4025 mutex_unlock(&fs_info->balance_mutex);
4027 btrfs_free_path(path);
4031 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4035 mutex_lock(&fs_info->balance_mutex);
4036 if (!fs_info->balance_ctl) {
4037 mutex_unlock(&fs_info->balance_mutex);
4041 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4042 atomic_inc(&fs_info->balance_pause_req);
4043 mutex_unlock(&fs_info->balance_mutex);
4045 wait_event(fs_info->balance_wait_q,
4046 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4048 mutex_lock(&fs_info->balance_mutex);
4049 /* we are good with balance_ctl ripped off from under us */
4050 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4051 atomic_dec(&fs_info->balance_pause_req);
4056 mutex_unlock(&fs_info->balance_mutex);
4060 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4062 mutex_lock(&fs_info->balance_mutex);
4063 if (!fs_info->balance_ctl) {
4064 mutex_unlock(&fs_info->balance_mutex);
4069 * A paused balance with the item stored on disk can be resumed at
4070 * mount time if the mount is read-write. Otherwise it's still paused
4071 * and we must not allow cancelling as it deletes the item.
4073 if (sb_rdonly(fs_info->sb)) {
4074 mutex_unlock(&fs_info->balance_mutex);
4078 atomic_inc(&fs_info->balance_cancel_req);
4080 * if we are running just wait and return, balance item is
4081 * deleted in btrfs_balance in this case
4083 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4084 mutex_unlock(&fs_info->balance_mutex);
4085 wait_event(fs_info->balance_wait_q,
4086 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4087 mutex_lock(&fs_info->balance_mutex);
4089 mutex_unlock(&fs_info->balance_mutex);
4091 * Lock released to allow other waiters to continue, we'll
4092 * reexamine the status again.
4094 mutex_lock(&fs_info->balance_mutex);
4096 if (fs_info->balance_ctl) {
4097 reset_balance_state(fs_info);
4098 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4099 btrfs_info(fs_info, "balance: canceled");
4103 BUG_ON(fs_info->balance_ctl ||
4104 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4105 atomic_dec(&fs_info->balance_cancel_req);
4106 mutex_unlock(&fs_info->balance_mutex);
4110 static int btrfs_uuid_scan_kthread(void *data)
4112 struct btrfs_fs_info *fs_info = data;
4113 struct btrfs_root *root = fs_info->tree_root;
4114 struct btrfs_key key;
4115 struct btrfs_path *path = NULL;
4117 struct extent_buffer *eb;
4119 struct btrfs_root_item root_item;
4121 struct btrfs_trans_handle *trans = NULL;
4123 path = btrfs_alloc_path();
4130 key.type = BTRFS_ROOT_ITEM_KEY;
4134 ret = btrfs_search_forward(root, &key, path,
4135 BTRFS_OLDEST_GENERATION);
4142 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4143 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4144 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4145 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4148 eb = path->nodes[0];
4149 slot = path->slots[0];
4150 item_size = btrfs_item_size_nr(eb, slot);
4151 if (item_size < sizeof(root_item))
4154 read_extent_buffer(eb, &root_item,
4155 btrfs_item_ptr_offset(eb, slot),
4156 (int)sizeof(root_item));
4157 if (btrfs_root_refs(&root_item) == 0)
4160 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4161 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4165 btrfs_release_path(path);
4167 * 1 - subvol uuid item
4168 * 1 - received_subvol uuid item
4170 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4171 if (IS_ERR(trans)) {
4172 ret = PTR_ERR(trans);
4180 btrfs_release_path(path);
4181 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4182 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4183 BTRFS_UUID_KEY_SUBVOL,
4186 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4192 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4193 ret = btrfs_uuid_tree_add(trans,
4194 root_item.received_uuid,
4195 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4198 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4205 btrfs_release_path(path);
4207 ret = btrfs_end_transaction(trans);
4213 if (key.offset < (u64)-1) {
4215 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4217 key.type = BTRFS_ROOT_ITEM_KEY;
4218 } else if (key.objectid < (u64)-1) {
4220 key.type = BTRFS_ROOT_ITEM_KEY;
4229 btrfs_free_path(path);
4230 if (trans && !IS_ERR(trans))
4231 btrfs_end_transaction(trans);
4233 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4235 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4236 up(&fs_info->uuid_tree_rescan_sem);
4241 * Callback for btrfs_uuid_tree_iterate().
4243 * 0 check succeeded, the entry is not outdated.
4244 * < 0 if an error occurred.
4245 * > 0 if the check failed, which means the caller shall remove the entry.
4247 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4248 u8 *uuid, u8 type, u64 subid)
4250 struct btrfs_key key;
4252 struct btrfs_root *subvol_root;
4254 if (type != BTRFS_UUID_KEY_SUBVOL &&
4255 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4258 key.objectid = subid;
4259 key.type = BTRFS_ROOT_ITEM_KEY;
4260 key.offset = (u64)-1;
4261 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4262 if (IS_ERR(subvol_root)) {
4263 ret = PTR_ERR(subvol_root);
4270 case BTRFS_UUID_KEY_SUBVOL:
4271 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4274 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4275 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4285 static int btrfs_uuid_rescan_kthread(void *data)
4287 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4291 * 1st step is to iterate through the existing UUID tree and
4292 * to delete all entries that contain outdated data.
4293 * 2nd step is to add all missing entries to the UUID tree.
4295 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4297 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4298 up(&fs_info->uuid_tree_rescan_sem);
4301 return btrfs_uuid_scan_kthread(data);
4304 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4306 struct btrfs_trans_handle *trans;
4307 struct btrfs_root *tree_root = fs_info->tree_root;
4308 struct btrfs_root *uuid_root;
4309 struct task_struct *task;
4316 trans = btrfs_start_transaction(tree_root, 2);
4318 return PTR_ERR(trans);
4320 uuid_root = btrfs_create_tree(trans, fs_info,
4321 BTRFS_UUID_TREE_OBJECTID);
4322 if (IS_ERR(uuid_root)) {
4323 ret = PTR_ERR(uuid_root);
4324 btrfs_abort_transaction(trans, ret);
4325 btrfs_end_transaction(trans);
4329 fs_info->uuid_root = uuid_root;
4331 ret = btrfs_commit_transaction(trans);
4335 down(&fs_info->uuid_tree_rescan_sem);
4336 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4338 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4339 btrfs_warn(fs_info, "failed to start uuid_scan task");
4340 up(&fs_info->uuid_tree_rescan_sem);
4341 return PTR_ERR(task);
4347 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4349 struct task_struct *task;
4351 down(&fs_info->uuid_tree_rescan_sem);
4352 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4354 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4355 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4356 up(&fs_info->uuid_tree_rescan_sem);
4357 return PTR_ERR(task);
4364 * shrinking a device means finding all of the device extents past
4365 * the new size, and then following the back refs to the chunks.
4366 * The chunk relocation code actually frees the device extent
4368 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4370 struct btrfs_fs_info *fs_info = device->fs_info;
4371 struct btrfs_root *root = fs_info->dev_root;
4372 struct btrfs_trans_handle *trans;
4373 struct btrfs_dev_extent *dev_extent = NULL;
4374 struct btrfs_path *path;
4380 bool retried = false;
4381 bool checked_pending_chunks = false;
4382 struct extent_buffer *l;
4383 struct btrfs_key key;
4384 struct btrfs_super_block *super_copy = fs_info->super_copy;
4385 u64 old_total = btrfs_super_total_bytes(super_copy);
4386 u64 old_size = btrfs_device_get_total_bytes(device);
4389 new_size = round_down(new_size, fs_info->sectorsize);
4390 diff = round_down(old_size - new_size, fs_info->sectorsize);
4392 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4395 path = btrfs_alloc_path();
4399 path->reada = READA_BACK;
4401 mutex_lock(&fs_info->chunk_mutex);
4403 btrfs_device_set_total_bytes(device, new_size);
4404 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4405 device->fs_devices->total_rw_bytes -= diff;
4406 atomic64_sub(diff, &fs_info->free_chunk_space);
4408 mutex_unlock(&fs_info->chunk_mutex);
4411 key.objectid = device->devid;
4412 key.offset = (u64)-1;
4413 key.type = BTRFS_DEV_EXTENT_KEY;
4416 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4417 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4419 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4423 ret = btrfs_previous_item(root, path, 0, key.type);
4425 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4430 btrfs_release_path(path);
4435 slot = path->slots[0];
4436 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4438 if (key.objectid != device->devid) {
4439 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4440 btrfs_release_path(path);
4444 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4445 length = btrfs_dev_extent_length(l, dev_extent);
4447 if (key.offset + length <= new_size) {
4448 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4449 btrfs_release_path(path);
4453 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4454 btrfs_release_path(path);
4457 * We may be relocating the only data chunk we have,
4458 * which could potentially end up with losing data's
4459 * raid profile, so lets allocate an empty one in
4462 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4464 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4468 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4469 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4470 if (ret && ret != -ENOSPC)
4474 } while (key.offset-- > 0);
4476 if (failed && !retried) {
4480 } else if (failed && retried) {
4485 /* Shrinking succeeded, else we would be at "done". */
4486 trans = btrfs_start_transaction(root, 0);
4487 if (IS_ERR(trans)) {
4488 ret = PTR_ERR(trans);
4492 mutex_lock(&fs_info->chunk_mutex);
4495 * We checked in the above loop all device extents that were already in
4496 * the device tree. However before we have updated the device's
4497 * total_bytes to the new size, we might have had chunk allocations that
4498 * have not complete yet (new block groups attached to transaction
4499 * handles), and therefore their device extents were not yet in the
4500 * device tree and we missed them in the loop above. So if we have any
4501 * pending chunk using a device extent that overlaps the device range
4502 * that we can not use anymore, commit the current transaction and
4503 * repeat the search on the device tree - this way we guarantee we will
4504 * not have chunks using device extents that end beyond 'new_size'.
4506 if (!checked_pending_chunks) {
4507 u64 start = new_size;
4508 u64 len = old_size - new_size;
4510 if (contains_pending_extent(trans->transaction, device,
4512 mutex_unlock(&fs_info->chunk_mutex);
4513 checked_pending_chunks = true;
4516 ret = btrfs_commit_transaction(trans);
4523 btrfs_device_set_disk_total_bytes(device, new_size);
4524 if (list_empty(&device->resized_list))
4525 list_add_tail(&device->resized_list,
4526 &fs_info->fs_devices->resized_devices);
4528 WARN_ON(diff > old_total);
4529 btrfs_set_super_total_bytes(super_copy,
4530 round_down(old_total - diff, fs_info->sectorsize));
4531 mutex_unlock(&fs_info->chunk_mutex);
4533 /* Now btrfs_update_device() will change the on-disk size. */
4534 ret = btrfs_update_device(trans, device);
4536 btrfs_abort_transaction(trans, ret);
4537 btrfs_end_transaction(trans);
4539 ret = btrfs_commit_transaction(trans);
4542 btrfs_free_path(path);
4544 mutex_lock(&fs_info->chunk_mutex);
4545 btrfs_device_set_total_bytes(device, old_size);
4546 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4547 device->fs_devices->total_rw_bytes += diff;
4548 atomic64_add(diff, &fs_info->free_chunk_space);
4549 mutex_unlock(&fs_info->chunk_mutex);
4554 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4555 struct btrfs_key *key,
4556 struct btrfs_chunk *chunk, int item_size)
4558 struct btrfs_super_block *super_copy = fs_info->super_copy;
4559 struct btrfs_disk_key disk_key;
4563 mutex_lock(&fs_info->chunk_mutex);
4564 array_size = btrfs_super_sys_array_size(super_copy);
4565 if (array_size + item_size + sizeof(disk_key)
4566 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4567 mutex_unlock(&fs_info->chunk_mutex);
4571 ptr = super_copy->sys_chunk_array + array_size;
4572 btrfs_cpu_key_to_disk(&disk_key, key);
4573 memcpy(ptr, &disk_key, sizeof(disk_key));
4574 ptr += sizeof(disk_key);
4575 memcpy(ptr, chunk, item_size);
4576 item_size += sizeof(disk_key);
4577 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4578 mutex_unlock(&fs_info->chunk_mutex);
4584 * sort the devices in descending order by max_avail, total_avail
4586 static int btrfs_cmp_device_info(const void *a, const void *b)
4588 const struct btrfs_device_info *di_a = a;
4589 const struct btrfs_device_info *di_b = b;
4591 if (di_a->max_avail > di_b->max_avail)
4593 if (di_a->max_avail < di_b->max_avail)
4595 if (di_a->total_avail > di_b->total_avail)
4597 if (di_a->total_avail < di_b->total_avail)
4602 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4604 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4607 btrfs_set_fs_incompat(info, RAID56);
4610 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4611 u64 start, u64 type)
4613 struct btrfs_fs_info *info = trans->fs_info;
4614 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4615 struct btrfs_device *device;
4616 struct map_lookup *map = NULL;
4617 struct extent_map_tree *em_tree;
4618 struct extent_map *em;
4619 struct btrfs_device_info *devices_info = NULL;
4621 int num_stripes; /* total number of stripes to allocate */
4622 int data_stripes; /* number of stripes that count for
4624 int sub_stripes; /* sub_stripes info for map */
4625 int dev_stripes; /* stripes per dev */
4626 int devs_max; /* max devs to use */
4627 int devs_min; /* min devs needed */
4628 int devs_increment; /* ndevs has to be a multiple of this */
4629 int ncopies; /* how many copies to data has */
4631 u64 max_stripe_size;
4640 BUG_ON(!alloc_profile_is_valid(type, 0));
4642 if (list_empty(&fs_devices->alloc_list)) {
4643 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4644 btrfs_debug(info, "%s: no writable device", __func__);
4648 index = btrfs_bg_flags_to_raid_index(type);
4650 sub_stripes = btrfs_raid_array[index].sub_stripes;
4651 dev_stripes = btrfs_raid_array[index].dev_stripes;
4652 devs_max = btrfs_raid_array[index].devs_max;
4653 devs_min = btrfs_raid_array[index].devs_min;
4654 devs_increment = btrfs_raid_array[index].devs_increment;
4655 ncopies = btrfs_raid_array[index].ncopies;
4657 if (type & BTRFS_BLOCK_GROUP_DATA) {
4658 max_stripe_size = SZ_1G;
4659 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4661 devs_max = BTRFS_MAX_DEVS(info);
4662 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4663 /* for larger filesystems, use larger metadata chunks */
4664 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4665 max_stripe_size = SZ_1G;
4667 max_stripe_size = SZ_256M;
4668 max_chunk_size = max_stripe_size;
4670 devs_max = BTRFS_MAX_DEVS(info);
4671 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4672 max_stripe_size = SZ_32M;
4673 max_chunk_size = 2 * max_stripe_size;
4675 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4677 btrfs_err(info, "invalid chunk type 0x%llx requested",
4682 /* we don't want a chunk larger than 10% of writeable space */
4683 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4686 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4692 * in the first pass through the devices list, we gather information
4693 * about the available holes on each device.
4696 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4700 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4702 "BTRFS: read-only device in alloc_list\n");
4706 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4707 &device->dev_state) ||
4708 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4711 if (device->total_bytes > device->bytes_used)
4712 total_avail = device->total_bytes - device->bytes_used;
4716 /* If there is no space on this device, skip it. */
4717 if (total_avail == 0)
4720 ret = find_free_dev_extent(trans, device,
4721 max_stripe_size * dev_stripes,
4722 &dev_offset, &max_avail);
4723 if (ret && ret != -ENOSPC)
4727 max_avail = max_stripe_size * dev_stripes;
4729 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4730 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4732 "%s: devid %llu has no free space, have=%llu want=%u",
4733 __func__, device->devid, max_avail,
4734 BTRFS_STRIPE_LEN * dev_stripes);
4738 if (ndevs == fs_devices->rw_devices) {
4739 WARN(1, "%s: found more than %llu devices\n",
4740 __func__, fs_devices->rw_devices);
4743 devices_info[ndevs].dev_offset = dev_offset;
4744 devices_info[ndevs].max_avail = max_avail;
4745 devices_info[ndevs].total_avail = total_avail;
4746 devices_info[ndevs].dev = device;
4751 * now sort the devices by hole size / available space
4753 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4754 btrfs_cmp_device_info, NULL);
4756 /* round down to number of usable stripes */
4757 ndevs = round_down(ndevs, devs_increment);
4759 if (ndevs < devs_min) {
4761 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4763 "%s: not enough devices with free space: have=%d minimum required=%d",
4764 __func__, ndevs, devs_min);
4769 ndevs = min(ndevs, devs_max);
4772 * The primary goal is to maximize the number of stripes, so use as
4773 * many devices as possible, even if the stripes are not maximum sized.
4775 * The DUP profile stores more than one stripe per device, the
4776 * max_avail is the total size so we have to adjust.
4778 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4779 num_stripes = ndevs * dev_stripes;
4782 * this will have to be fixed for RAID1 and RAID10 over
4785 data_stripes = num_stripes / ncopies;
4787 if (type & BTRFS_BLOCK_GROUP_RAID5)
4788 data_stripes = num_stripes - 1;
4790 if (type & BTRFS_BLOCK_GROUP_RAID6)
4791 data_stripes = num_stripes - 2;
4794 * Use the number of data stripes to figure out how big this chunk
4795 * is really going to be in terms of logical address space,
4796 * and compare that answer with the max chunk size. If it's higher,
4797 * we try to reduce stripe_size.
4799 if (stripe_size * data_stripes > max_chunk_size) {
4801 * Reduce stripe_size, round it up to a 16MB boundary again and
4802 * then use it, unless it ends up being even bigger than the
4803 * previous value we had already.
4805 stripe_size = min(round_up(div_u64(max_chunk_size,
4806 data_stripes), SZ_16M),
4810 /* align to BTRFS_STRIPE_LEN */
4811 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4813 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4818 map->num_stripes = num_stripes;
4820 for (i = 0; i < ndevs; ++i) {
4821 for (j = 0; j < dev_stripes; ++j) {
4822 int s = i * dev_stripes + j;
4823 map->stripes[s].dev = devices_info[i].dev;
4824 map->stripes[s].physical = devices_info[i].dev_offset +
4828 map->stripe_len = BTRFS_STRIPE_LEN;
4829 map->io_align = BTRFS_STRIPE_LEN;
4830 map->io_width = BTRFS_STRIPE_LEN;
4832 map->sub_stripes = sub_stripes;
4834 num_bytes = stripe_size * data_stripes;
4836 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4838 em = alloc_extent_map();
4844 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4845 em->map_lookup = map;
4847 em->len = num_bytes;
4848 em->block_start = 0;
4849 em->block_len = em->len;
4850 em->orig_block_len = stripe_size;
4852 em_tree = &info->mapping_tree.map_tree;
4853 write_lock(&em_tree->lock);
4854 ret = add_extent_mapping(em_tree, em, 0);
4856 write_unlock(&em_tree->lock);
4857 free_extent_map(em);
4861 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4862 refcount_inc(&em->refs);
4863 write_unlock(&em_tree->lock);
4865 ret = btrfs_make_block_group(trans, 0, type, start, num_bytes);
4867 goto error_del_extent;
4869 for (i = 0; i < map->num_stripes; i++) {
4870 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4871 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4872 map->stripes[i].dev->has_pending_chunks = true;
4875 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4877 free_extent_map(em);
4878 check_raid56_incompat_flag(info, type);
4880 kfree(devices_info);
4884 write_lock(&em_tree->lock);
4885 remove_extent_mapping(em_tree, em);
4886 write_unlock(&em_tree->lock);
4888 /* One for our allocation */
4889 free_extent_map(em);
4890 /* One for the tree reference */
4891 free_extent_map(em);
4892 /* One for the pending_chunks list reference */
4893 free_extent_map(em);
4895 kfree(devices_info);
4899 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4900 u64 chunk_offset, u64 chunk_size)
4902 struct btrfs_fs_info *fs_info = trans->fs_info;
4903 struct btrfs_root *extent_root = fs_info->extent_root;
4904 struct btrfs_root *chunk_root = fs_info->chunk_root;
4905 struct btrfs_key key;
4906 struct btrfs_device *device;
4907 struct btrfs_chunk *chunk;
4908 struct btrfs_stripe *stripe;
4909 struct extent_map *em;
4910 struct map_lookup *map;
4917 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4921 map = em->map_lookup;
4922 item_size = btrfs_chunk_item_size(map->num_stripes);
4923 stripe_size = em->orig_block_len;
4925 chunk = kzalloc(item_size, GFP_NOFS);
4932 * Take the device list mutex to prevent races with the final phase of
4933 * a device replace operation that replaces the device object associated
4934 * with the map's stripes, because the device object's id can change
4935 * at any time during that final phase of the device replace operation
4936 * (dev-replace.c:btrfs_dev_replace_finishing()).
4938 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4939 for (i = 0; i < map->num_stripes; i++) {
4940 device = map->stripes[i].dev;
4941 dev_offset = map->stripes[i].physical;
4943 ret = btrfs_update_device(trans, device);
4946 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
4947 dev_offset, stripe_size);
4952 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4956 stripe = &chunk->stripe;
4957 for (i = 0; i < map->num_stripes; i++) {
4958 device = map->stripes[i].dev;
4959 dev_offset = map->stripes[i].physical;
4961 btrfs_set_stack_stripe_devid(stripe, device->devid);
4962 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4963 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4966 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4968 btrfs_set_stack_chunk_length(chunk, chunk_size);
4969 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4970 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4971 btrfs_set_stack_chunk_type(chunk, map->type);
4972 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4973 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4974 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4975 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
4976 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4978 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4979 key.type = BTRFS_CHUNK_ITEM_KEY;
4980 key.offset = chunk_offset;
4982 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4983 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4985 * TODO: Cleanup of inserted chunk root in case of
4988 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
4993 free_extent_map(em);
4998 * Chunk allocation falls into two parts. The first part does works
4999 * that make the new allocated chunk useable, but not do any operation
5000 * that modifies the chunk tree. The second part does the works that
5001 * require modifying the chunk tree. This division is important for the
5002 * bootstrap process of adding storage to a seed btrfs.
5004 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5008 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5009 chunk_offset = find_next_chunk(trans->fs_info);
5010 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5013 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5014 struct btrfs_fs_info *fs_info)
5017 u64 sys_chunk_offset;
5021 chunk_offset = find_next_chunk(fs_info);
5022 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5023 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5027 sys_chunk_offset = find_next_chunk(fs_info);
5028 alloc_profile = btrfs_system_alloc_profile(fs_info);
5029 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5033 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5037 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5038 BTRFS_BLOCK_GROUP_RAID10 |
5039 BTRFS_BLOCK_GROUP_RAID5)) {
5041 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5050 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5052 struct extent_map *em;
5053 struct map_lookup *map;
5058 em = get_chunk_map(fs_info, chunk_offset, 1);
5062 map = em->map_lookup;
5063 for (i = 0; i < map->num_stripes; i++) {
5064 if (test_bit(BTRFS_DEV_STATE_MISSING,
5065 &map->stripes[i].dev->dev_state)) {
5069 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5070 &map->stripes[i].dev->dev_state)) {
5077 * If the number of missing devices is larger than max errors,
5078 * we can not write the data into that chunk successfully, so
5081 if (miss_ndevs > btrfs_chunk_max_errors(map))
5084 free_extent_map(em);
5088 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5090 extent_map_tree_init(&tree->map_tree);
5093 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5095 struct extent_map *em;
5098 write_lock(&tree->map_tree.lock);
5099 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5101 remove_extent_mapping(&tree->map_tree, em);
5102 write_unlock(&tree->map_tree.lock);
5106 free_extent_map(em);
5107 /* once for the tree */
5108 free_extent_map(em);
5112 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5114 struct extent_map *em;
5115 struct map_lookup *map;
5118 em = get_chunk_map(fs_info, logical, len);
5121 * We could return errors for these cases, but that could get
5122 * ugly and we'd probably do the same thing which is just not do
5123 * anything else and exit, so return 1 so the callers don't try
5124 * to use other copies.
5128 map = em->map_lookup;
5129 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5130 ret = map->num_stripes;
5131 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5132 ret = map->sub_stripes;
5133 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5135 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5137 * There could be two corrupted data stripes, we need
5138 * to loop retry in order to rebuild the correct data.
5140 * Fail a stripe at a time on every retry except the
5141 * stripe under reconstruction.
5143 ret = map->num_stripes;
5146 free_extent_map(em);
5148 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
5149 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5150 fs_info->dev_replace.tgtdev)
5152 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
5157 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5160 struct extent_map *em;
5161 struct map_lookup *map;
5162 unsigned long len = fs_info->sectorsize;
5164 em = get_chunk_map(fs_info, logical, len);
5166 if (!WARN_ON(IS_ERR(em))) {
5167 map = em->map_lookup;
5168 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5169 len = map->stripe_len * nr_data_stripes(map);
5170 free_extent_map(em);
5175 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5177 struct extent_map *em;
5178 struct map_lookup *map;
5181 em = get_chunk_map(fs_info, logical, len);
5183 if(!WARN_ON(IS_ERR(em))) {
5184 map = em->map_lookup;
5185 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5187 free_extent_map(em);
5192 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5193 struct map_lookup *map, int first,
5194 int dev_replace_is_ongoing)
5198 int preferred_mirror;
5200 struct btrfs_device *srcdev;
5203 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5205 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5206 num_stripes = map->sub_stripes;
5208 num_stripes = map->num_stripes;
5210 preferred_mirror = first + current->pid % num_stripes;
5212 if (dev_replace_is_ongoing &&
5213 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5214 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5215 srcdev = fs_info->dev_replace.srcdev;
5220 * try to avoid the drive that is the source drive for a
5221 * dev-replace procedure, only choose it if no other non-missing
5222 * mirror is available
5224 for (tolerance = 0; tolerance < 2; tolerance++) {
5225 if (map->stripes[preferred_mirror].dev->bdev &&
5226 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5227 return preferred_mirror;
5228 for (i = first; i < first + num_stripes; i++) {
5229 if (map->stripes[i].dev->bdev &&
5230 (tolerance || map->stripes[i].dev != srcdev))
5235 /* we couldn't find one that doesn't fail. Just return something
5236 * and the io error handling code will clean up eventually
5238 return preferred_mirror;
5241 static inline int parity_smaller(u64 a, u64 b)
5246 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5247 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5249 struct btrfs_bio_stripe s;
5256 for (i = 0; i < num_stripes - 1; i++) {
5257 if (parity_smaller(bbio->raid_map[i],
5258 bbio->raid_map[i+1])) {
5259 s = bbio->stripes[i];
5260 l = bbio->raid_map[i];
5261 bbio->stripes[i] = bbio->stripes[i+1];
5262 bbio->raid_map[i] = bbio->raid_map[i+1];
5263 bbio->stripes[i+1] = s;
5264 bbio->raid_map[i+1] = l;
5272 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5274 struct btrfs_bio *bbio = kzalloc(
5275 /* the size of the btrfs_bio */
5276 sizeof(struct btrfs_bio) +
5277 /* plus the variable array for the stripes */
5278 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5279 /* plus the variable array for the tgt dev */
5280 sizeof(int) * (real_stripes) +
5282 * plus the raid_map, which includes both the tgt dev
5285 sizeof(u64) * (total_stripes),
5286 GFP_NOFS|__GFP_NOFAIL);
5288 atomic_set(&bbio->error, 0);
5289 refcount_set(&bbio->refs, 1);
5294 void btrfs_get_bbio(struct btrfs_bio *bbio)
5296 WARN_ON(!refcount_read(&bbio->refs));
5297 refcount_inc(&bbio->refs);
5300 void btrfs_put_bbio(struct btrfs_bio *bbio)
5304 if (refcount_dec_and_test(&bbio->refs))
5308 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5310 * Please note that, discard won't be sent to target device of device
5313 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5314 u64 logical, u64 length,
5315 struct btrfs_bio **bbio_ret)
5317 struct extent_map *em;
5318 struct map_lookup *map;
5319 struct btrfs_bio *bbio;
5323 u64 stripe_end_offset;
5330 u32 sub_stripes = 0;
5331 u64 stripes_per_dev = 0;
5332 u32 remaining_stripes = 0;
5333 u32 last_stripe = 0;
5337 /* discard always return a bbio */
5340 em = get_chunk_map(fs_info, logical, length);
5344 map = em->map_lookup;
5345 /* we don't discard raid56 yet */
5346 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5351 offset = logical - em->start;
5352 length = min_t(u64, em->len - offset, length);
5354 stripe_len = map->stripe_len;
5356 * stripe_nr counts the total number of stripes we have to stride
5357 * to get to this block
5359 stripe_nr = div64_u64(offset, stripe_len);
5361 /* stripe_offset is the offset of this block in its stripe */
5362 stripe_offset = offset - stripe_nr * stripe_len;
5364 stripe_nr_end = round_up(offset + length, map->stripe_len);
5365 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5366 stripe_cnt = stripe_nr_end - stripe_nr;
5367 stripe_end_offset = stripe_nr_end * map->stripe_len -
5370 * after this, stripe_nr is the number of stripes on this
5371 * device we have to walk to find the data, and stripe_index is
5372 * the number of our device in the stripe array
5376 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5377 BTRFS_BLOCK_GROUP_RAID10)) {
5378 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5381 sub_stripes = map->sub_stripes;
5383 factor = map->num_stripes / sub_stripes;
5384 num_stripes = min_t(u64, map->num_stripes,
5385 sub_stripes * stripe_cnt);
5386 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5387 stripe_index *= sub_stripes;
5388 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5389 &remaining_stripes);
5390 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5391 last_stripe *= sub_stripes;
5392 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5393 BTRFS_BLOCK_GROUP_DUP)) {
5394 num_stripes = map->num_stripes;
5396 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5400 bbio = alloc_btrfs_bio(num_stripes, 0);
5406 for (i = 0; i < num_stripes; i++) {
5407 bbio->stripes[i].physical =
5408 map->stripes[stripe_index].physical +
5409 stripe_offset + stripe_nr * map->stripe_len;
5410 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5412 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5413 BTRFS_BLOCK_GROUP_RAID10)) {
5414 bbio->stripes[i].length = stripes_per_dev *
5417 if (i / sub_stripes < remaining_stripes)
5418 bbio->stripes[i].length +=
5422 * Special for the first stripe and
5425 * |-------|...|-------|
5429 if (i < sub_stripes)
5430 bbio->stripes[i].length -=
5433 if (stripe_index >= last_stripe &&
5434 stripe_index <= (last_stripe +
5436 bbio->stripes[i].length -=
5439 if (i == sub_stripes - 1)
5442 bbio->stripes[i].length = length;
5446 if (stripe_index == map->num_stripes) {
5453 bbio->map_type = map->type;
5454 bbio->num_stripes = num_stripes;
5456 free_extent_map(em);
5461 * In dev-replace case, for repair case (that's the only case where the mirror
5462 * is selected explicitly when calling btrfs_map_block), blocks left of the
5463 * left cursor can also be read from the target drive.
5465 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5467 * For READ, it also needs to be supported using the same mirror number.
5469 * If the requested block is not left of the left cursor, EIO is returned. This
5470 * can happen because btrfs_num_copies() returns one more in the dev-replace
5473 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5474 u64 logical, u64 length,
5475 u64 srcdev_devid, int *mirror_num,
5478 struct btrfs_bio *bbio = NULL;
5480 int index_srcdev = 0;
5482 u64 physical_of_found = 0;
5486 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5487 logical, &length, &bbio, 0, 0);
5489 ASSERT(bbio == NULL);
5493 num_stripes = bbio->num_stripes;
5494 if (*mirror_num > num_stripes) {
5496 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5497 * that means that the requested area is not left of the left
5500 btrfs_put_bbio(bbio);
5505 * process the rest of the function using the mirror_num of the source
5506 * drive. Therefore look it up first. At the end, patch the device
5507 * pointer to the one of the target drive.
5509 for (i = 0; i < num_stripes; i++) {
5510 if (bbio->stripes[i].dev->devid != srcdev_devid)
5514 * In case of DUP, in order to keep it simple, only add the
5515 * mirror with the lowest physical address
5518 physical_of_found <= bbio->stripes[i].physical)
5523 physical_of_found = bbio->stripes[i].physical;
5526 btrfs_put_bbio(bbio);
5532 *mirror_num = index_srcdev + 1;
5533 *physical = physical_of_found;
5537 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5538 struct btrfs_bio **bbio_ret,
5539 struct btrfs_dev_replace *dev_replace,
5540 int *num_stripes_ret, int *max_errors_ret)
5542 struct btrfs_bio *bbio = *bbio_ret;
5543 u64 srcdev_devid = dev_replace->srcdev->devid;
5544 int tgtdev_indexes = 0;
5545 int num_stripes = *num_stripes_ret;
5546 int max_errors = *max_errors_ret;
5549 if (op == BTRFS_MAP_WRITE) {
5550 int index_where_to_add;
5553 * duplicate the write operations while the dev replace
5554 * procedure is running. Since the copying of the old disk to
5555 * the new disk takes place at run time while the filesystem is
5556 * mounted writable, the regular write operations to the old
5557 * disk have to be duplicated to go to the new disk as well.
5559 * Note that device->missing is handled by the caller, and that
5560 * the write to the old disk is already set up in the stripes
5563 index_where_to_add = num_stripes;
5564 for (i = 0; i < num_stripes; i++) {
5565 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5566 /* write to new disk, too */
5567 struct btrfs_bio_stripe *new =
5568 bbio->stripes + index_where_to_add;
5569 struct btrfs_bio_stripe *old =
5572 new->physical = old->physical;
5573 new->length = old->length;
5574 new->dev = dev_replace->tgtdev;
5575 bbio->tgtdev_map[i] = index_where_to_add;
5576 index_where_to_add++;
5581 num_stripes = index_where_to_add;
5582 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5583 int index_srcdev = 0;
5585 u64 physical_of_found = 0;
5588 * During the dev-replace procedure, the target drive can also
5589 * be used to read data in case it is needed to repair a corrupt
5590 * block elsewhere. This is possible if the requested area is
5591 * left of the left cursor. In this area, the target drive is a
5592 * full copy of the source drive.
5594 for (i = 0; i < num_stripes; i++) {
5595 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5597 * In case of DUP, in order to keep it simple,
5598 * only add the mirror with the lowest physical
5602 physical_of_found <=
5603 bbio->stripes[i].physical)
5607 physical_of_found = bbio->stripes[i].physical;
5611 struct btrfs_bio_stripe *tgtdev_stripe =
5612 bbio->stripes + num_stripes;
5614 tgtdev_stripe->physical = physical_of_found;
5615 tgtdev_stripe->length =
5616 bbio->stripes[index_srcdev].length;
5617 tgtdev_stripe->dev = dev_replace->tgtdev;
5618 bbio->tgtdev_map[index_srcdev] = num_stripes;
5625 *num_stripes_ret = num_stripes;
5626 *max_errors_ret = max_errors;
5627 bbio->num_tgtdevs = tgtdev_indexes;
5631 static bool need_full_stripe(enum btrfs_map_op op)
5633 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5636 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5637 enum btrfs_map_op op,
5638 u64 logical, u64 *length,
5639 struct btrfs_bio **bbio_ret,
5640 int mirror_num, int need_raid_map)
5642 struct extent_map *em;
5643 struct map_lookup *map;
5653 int tgtdev_indexes = 0;
5654 struct btrfs_bio *bbio = NULL;
5655 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5656 int dev_replace_is_ongoing = 0;
5657 int num_alloc_stripes;
5658 int patch_the_first_stripe_for_dev_replace = 0;
5659 u64 physical_to_patch_in_first_stripe = 0;
5660 u64 raid56_full_stripe_start = (u64)-1;
5662 if (op == BTRFS_MAP_DISCARD)
5663 return __btrfs_map_block_for_discard(fs_info, logical,
5666 em = get_chunk_map(fs_info, logical, *length);
5670 map = em->map_lookup;
5671 offset = logical - em->start;
5673 stripe_len = map->stripe_len;
5676 * stripe_nr counts the total number of stripes we have to stride
5677 * to get to this block
5679 stripe_nr = div64_u64(stripe_nr, stripe_len);
5681 stripe_offset = stripe_nr * stripe_len;
5682 if (offset < stripe_offset) {
5684 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5685 stripe_offset, offset, em->start, logical,
5687 free_extent_map(em);
5691 /* stripe_offset is the offset of this block in its stripe*/
5692 stripe_offset = offset - stripe_offset;
5694 /* if we're here for raid56, we need to know the stripe aligned start */
5695 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5696 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5697 raid56_full_stripe_start = offset;
5699 /* allow a write of a full stripe, but make sure we don't
5700 * allow straddling of stripes
5702 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5704 raid56_full_stripe_start *= full_stripe_len;
5707 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5709 /* For writes to RAID[56], allow a full stripeset across all disks.
5710 For other RAID types and for RAID[56] reads, just allow a single
5711 stripe (on a single disk). */
5712 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5713 (op == BTRFS_MAP_WRITE)) {
5714 max_len = stripe_len * nr_data_stripes(map) -
5715 (offset - raid56_full_stripe_start);
5717 /* we limit the length of each bio to what fits in a stripe */
5718 max_len = stripe_len - stripe_offset;
5720 *length = min_t(u64, em->len - offset, max_len);
5722 *length = em->len - offset;
5725 /* This is for when we're called from btrfs_merge_bio_hook() and all
5726 it cares about is the length */
5730 btrfs_dev_replace_read_lock(dev_replace);
5731 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5732 if (!dev_replace_is_ongoing)
5733 btrfs_dev_replace_read_unlock(dev_replace);
5735 btrfs_dev_replace_set_lock_blocking(dev_replace);
5737 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5738 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5739 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5740 dev_replace->srcdev->devid,
5742 &physical_to_patch_in_first_stripe);
5746 patch_the_first_stripe_for_dev_replace = 1;
5747 } else if (mirror_num > map->num_stripes) {
5753 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5754 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5756 if (!need_full_stripe(op))
5758 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5759 if (need_full_stripe(op))
5760 num_stripes = map->num_stripes;
5761 else if (mirror_num)
5762 stripe_index = mirror_num - 1;
5764 stripe_index = find_live_mirror(fs_info, map, 0,
5765 dev_replace_is_ongoing);
5766 mirror_num = stripe_index + 1;
5769 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5770 if (need_full_stripe(op)) {
5771 num_stripes = map->num_stripes;
5772 } else if (mirror_num) {
5773 stripe_index = mirror_num - 1;
5778 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5779 u32 factor = map->num_stripes / map->sub_stripes;
5781 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5782 stripe_index *= map->sub_stripes;
5784 if (need_full_stripe(op))
5785 num_stripes = map->sub_stripes;
5786 else if (mirror_num)
5787 stripe_index += mirror_num - 1;
5789 int old_stripe_index = stripe_index;
5790 stripe_index = find_live_mirror(fs_info, map,
5792 dev_replace_is_ongoing);
5793 mirror_num = stripe_index - old_stripe_index + 1;
5796 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5797 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5798 /* push stripe_nr back to the start of the full stripe */
5799 stripe_nr = div64_u64(raid56_full_stripe_start,
5800 stripe_len * nr_data_stripes(map));
5802 /* RAID[56] write or recovery. Return all stripes */
5803 num_stripes = map->num_stripes;
5804 max_errors = nr_parity_stripes(map);
5806 *length = map->stripe_len;
5811 * Mirror #0 or #1 means the original data block.
5812 * Mirror #2 is RAID5 parity block.
5813 * Mirror #3 is RAID6 Q block.
5815 stripe_nr = div_u64_rem(stripe_nr,
5816 nr_data_stripes(map), &stripe_index);
5818 stripe_index = nr_data_stripes(map) +
5821 /* We distribute the parity blocks across stripes */
5822 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5824 if (!need_full_stripe(op) && mirror_num <= 1)
5829 * after this, stripe_nr is the number of stripes on this
5830 * device we have to walk to find the data, and stripe_index is
5831 * the number of our device in the stripe array
5833 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5835 mirror_num = stripe_index + 1;
5837 if (stripe_index >= map->num_stripes) {
5839 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5840 stripe_index, map->num_stripes);
5845 num_alloc_stripes = num_stripes;
5846 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5847 if (op == BTRFS_MAP_WRITE)
5848 num_alloc_stripes <<= 1;
5849 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5850 num_alloc_stripes++;
5851 tgtdev_indexes = num_stripes;
5854 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5859 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5860 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5862 /* build raid_map */
5863 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5864 (need_full_stripe(op) || mirror_num > 1)) {
5868 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5869 sizeof(struct btrfs_bio_stripe) *
5871 sizeof(int) * tgtdev_indexes);
5873 /* Work out the disk rotation on this stripe-set */
5874 div_u64_rem(stripe_nr, num_stripes, &rot);
5876 /* Fill in the logical address of each stripe */
5877 tmp = stripe_nr * nr_data_stripes(map);
5878 for (i = 0; i < nr_data_stripes(map); i++)
5879 bbio->raid_map[(i+rot) % num_stripes] =
5880 em->start + (tmp + i) * map->stripe_len;
5882 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5883 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5884 bbio->raid_map[(i+rot+1) % num_stripes] =
5889 for (i = 0; i < num_stripes; i++) {
5890 bbio->stripes[i].physical =
5891 map->stripes[stripe_index].physical +
5893 stripe_nr * map->stripe_len;
5894 bbio->stripes[i].dev =
5895 map->stripes[stripe_index].dev;
5899 if (need_full_stripe(op))
5900 max_errors = btrfs_chunk_max_errors(map);
5903 sort_parity_stripes(bbio, num_stripes);
5905 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5906 need_full_stripe(op)) {
5907 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5912 bbio->map_type = map->type;
5913 bbio->num_stripes = num_stripes;
5914 bbio->max_errors = max_errors;
5915 bbio->mirror_num = mirror_num;
5918 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5919 * mirror_num == num_stripes + 1 && dev_replace target drive is
5920 * available as a mirror
5922 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5923 WARN_ON(num_stripes > 1);
5924 bbio->stripes[0].dev = dev_replace->tgtdev;
5925 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5926 bbio->mirror_num = map->num_stripes + 1;
5929 if (dev_replace_is_ongoing) {
5930 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5931 btrfs_dev_replace_read_unlock(dev_replace);
5933 free_extent_map(em);
5937 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5938 u64 logical, u64 *length,
5939 struct btrfs_bio **bbio_ret, int mirror_num)
5941 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
5945 /* For Scrub/replace */
5946 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5947 u64 logical, u64 *length,
5948 struct btrfs_bio **bbio_ret)
5950 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
5953 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
5954 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
5956 struct extent_map *em;
5957 struct map_lookup *map;
5965 em = get_chunk_map(fs_info, chunk_start, 1);
5969 map = em->map_lookup;
5971 rmap_len = map->stripe_len;
5973 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5974 length = div_u64(length, map->num_stripes / map->sub_stripes);
5975 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5976 length = div_u64(length, map->num_stripes);
5977 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5978 length = div_u64(length, nr_data_stripes(map));
5979 rmap_len = map->stripe_len * nr_data_stripes(map);
5982 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5983 BUG_ON(!buf); /* -ENOMEM */
5985 for (i = 0; i < map->num_stripes; i++) {
5986 if (map->stripes[i].physical > physical ||
5987 map->stripes[i].physical + length <= physical)
5990 stripe_nr = physical - map->stripes[i].physical;
5991 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
5993 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5994 stripe_nr = stripe_nr * map->num_stripes + i;
5995 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
5996 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5997 stripe_nr = stripe_nr * map->num_stripes + i;
5998 } /* else if RAID[56], multiply by nr_data_stripes().
5999 * Alternatively, just use rmap_len below instead of
6000 * map->stripe_len */
6002 bytenr = chunk_start + stripe_nr * rmap_len;
6003 WARN_ON(nr >= map->num_stripes);
6004 for (j = 0; j < nr; j++) {
6005 if (buf[j] == bytenr)
6009 WARN_ON(nr >= map->num_stripes);
6016 *stripe_len = rmap_len;
6018 free_extent_map(em);
6022 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6024 bio->bi_private = bbio->private;
6025 bio->bi_end_io = bbio->end_io;
6028 btrfs_put_bbio(bbio);
6031 static void btrfs_end_bio(struct bio *bio)
6033 struct btrfs_bio *bbio = bio->bi_private;
6034 int is_orig_bio = 0;
6036 if (bio->bi_status) {
6037 atomic_inc(&bbio->error);
6038 if (bio->bi_status == BLK_STS_IOERR ||
6039 bio->bi_status == BLK_STS_TARGET) {
6040 unsigned int stripe_index =
6041 btrfs_io_bio(bio)->stripe_index;
6042 struct btrfs_device *dev;
6044 BUG_ON(stripe_index >= bbio->num_stripes);
6045 dev = bbio->stripes[stripe_index].dev;
6047 if (bio_op(bio) == REQ_OP_WRITE)
6048 btrfs_dev_stat_inc_and_print(dev,
6049 BTRFS_DEV_STAT_WRITE_ERRS);
6050 else if (!(bio->bi_opf & REQ_RAHEAD))
6051 btrfs_dev_stat_inc_and_print(dev,
6052 BTRFS_DEV_STAT_READ_ERRS);
6053 if (bio->bi_opf & REQ_PREFLUSH)
6054 btrfs_dev_stat_inc_and_print(dev,
6055 BTRFS_DEV_STAT_FLUSH_ERRS);
6060 if (bio == bbio->orig_bio)
6063 btrfs_bio_counter_dec(bbio->fs_info);
6065 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6068 bio = bbio->orig_bio;
6071 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6072 /* only send an error to the higher layers if it is
6073 * beyond the tolerance of the btrfs bio
6075 if (atomic_read(&bbio->error) > bbio->max_errors) {
6076 bio->bi_status = BLK_STS_IOERR;
6079 * this bio is actually up to date, we didn't
6080 * go over the max number of errors
6082 bio->bi_status = BLK_STS_OK;
6085 btrfs_end_bbio(bbio, bio);
6086 } else if (!is_orig_bio) {
6092 * see run_scheduled_bios for a description of why bios are collected for
6095 * This will add one bio to the pending list for a device and make sure
6096 * the work struct is scheduled.
6098 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6101 struct btrfs_fs_info *fs_info = device->fs_info;
6102 int should_queue = 1;
6103 struct btrfs_pending_bios *pending_bios;
6105 /* don't bother with additional async steps for reads, right now */
6106 if (bio_op(bio) == REQ_OP_READ) {
6107 btrfsic_submit_bio(bio);
6111 WARN_ON(bio->bi_next);
6112 bio->bi_next = NULL;
6114 spin_lock(&device->io_lock);
6115 if (op_is_sync(bio->bi_opf))
6116 pending_bios = &device->pending_sync_bios;
6118 pending_bios = &device->pending_bios;
6120 if (pending_bios->tail)
6121 pending_bios->tail->bi_next = bio;
6123 pending_bios->tail = bio;
6124 if (!pending_bios->head)
6125 pending_bios->head = bio;
6126 if (device->running_pending)
6129 spin_unlock(&device->io_lock);
6132 btrfs_queue_work(fs_info->submit_workers, &device->work);
6135 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6136 u64 physical, int dev_nr, int async)
6138 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6139 struct btrfs_fs_info *fs_info = bbio->fs_info;
6141 bio->bi_private = bbio;
6142 btrfs_io_bio(bio)->stripe_index = dev_nr;
6143 bio->bi_end_io = btrfs_end_bio;
6144 bio->bi_iter.bi_sector = physical >> 9;
6145 btrfs_debug_in_rcu(fs_info,
6146 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6147 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6148 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6149 bio->bi_iter.bi_size);
6150 bio_set_dev(bio, dev->bdev);
6152 btrfs_bio_counter_inc_noblocked(fs_info);
6155 btrfs_schedule_bio(dev, bio);
6157 btrfsic_submit_bio(bio);
6160 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6162 atomic_inc(&bbio->error);
6163 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6164 /* Should be the original bio. */
6165 WARN_ON(bio != bbio->orig_bio);
6167 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6168 bio->bi_iter.bi_sector = logical >> 9;
6169 if (atomic_read(&bbio->error) > bbio->max_errors)
6170 bio->bi_status = BLK_STS_IOERR;
6172 bio->bi_status = BLK_STS_OK;
6173 btrfs_end_bbio(bbio, bio);
6177 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6178 int mirror_num, int async_submit)
6180 struct btrfs_device *dev;
6181 struct bio *first_bio = bio;
6182 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6188 struct btrfs_bio *bbio = NULL;
6190 length = bio->bi_iter.bi_size;
6191 map_length = length;
6193 btrfs_bio_counter_inc_blocked(fs_info);
6194 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6195 &map_length, &bbio, mirror_num, 1);
6197 btrfs_bio_counter_dec(fs_info);
6198 return errno_to_blk_status(ret);
6201 total_devs = bbio->num_stripes;
6202 bbio->orig_bio = first_bio;
6203 bbio->private = first_bio->bi_private;
6204 bbio->end_io = first_bio->bi_end_io;
6205 bbio->fs_info = fs_info;
6206 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6208 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6209 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6210 /* In this case, map_length has been set to the length of
6211 a single stripe; not the whole write */
6212 if (bio_op(bio) == REQ_OP_WRITE) {
6213 ret = raid56_parity_write(fs_info, bio, bbio,
6216 ret = raid56_parity_recover(fs_info, bio, bbio,
6217 map_length, mirror_num, 1);
6220 btrfs_bio_counter_dec(fs_info);
6221 return errno_to_blk_status(ret);
6224 if (map_length < length) {
6226 "mapping failed logical %llu bio len %llu len %llu",
6227 logical, length, map_length);
6231 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6232 dev = bbio->stripes[dev_nr].dev;
6233 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6235 (bio_op(first_bio) == REQ_OP_WRITE &&
6236 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6237 bbio_error(bbio, first_bio, logical);
6241 if (dev_nr < total_devs - 1)
6242 bio = btrfs_bio_clone(first_bio);
6246 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6247 dev_nr, async_submit);
6249 btrfs_bio_counter_dec(fs_info);
6254 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6257 * If devid and uuid are both specified, the match must be exact, otherwise
6258 * only devid is used.
6260 * If @seed is true, traverse through the seed devices.
6262 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6263 u64 devid, u8 *uuid, u8 *fsid,
6266 struct btrfs_device *device;
6268 while (fs_devices) {
6270 !memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6271 list_for_each_entry(device, &fs_devices->devices,
6273 if (device->devid == devid &&
6274 (!uuid || memcmp(device->uuid, uuid,
6275 BTRFS_UUID_SIZE) == 0))
6280 fs_devices = fs_devices->seed;
6287 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6288 u64 devid, u8 *dev_uuid)
6290 struct btrfs_device *device;
6291 unsigned int nofs_flag;
6294 * We call this under the chunk_mutex, so we want to use NOFS for this
6295 * allocation, however we don't want to change btrfs_alloc_device() to
6296 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6299 nofs_flag = memalloc_nofs_save();
6300 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6301 memalloc_nofs_restore(nofs_flag);
6305 list_add(&device->dev_list, &fs_devices->devices);
6306 device->fs_devices = fs_devices;
6307 fs_devices->num_devices++;
6309 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6310 fs_devices->missing_devices++;
6316 * btrfs_alloc_device - allocate struct btrfs_device
6317 * @fs_info: used only for generating a new devid, can be NULL if
6318 * devid is provided (i.e. @devid != NULL).
6319 * @devid: a pointer to devid for this device. If NULL a new devid
6321 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6324 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6325 * on error. Returned struct is not linked onto any lists and must be
6326 * destroyed with btrfs_free_device.
6328 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6332 struct btrfs_device *dev;
6335 if (WARN_ON(!devid && !fs_info))
6336 return ERR_PTR(-EINVAL);
6338 dev = __alloc_device();
6347 ret = find_next_devid(fs_info, &tmp);
6349 btrfs_free_device(dev);
6350 return ERR_PTR(ret);
6356 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6358 generate_random_uuid(dev->uuid);
6360 btrfs_init_work(&dev->work, btrfs_submit_helper,
6361 pending_bios_fn, NULL, NULL);
6366 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6367 u64 devid, u8 *uuid, bool error)
6370 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6373 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6377 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6378 struct extent_buffer *leaf,
6379 struct btrfs_chunk *chunk)
6381 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6382 struct map_lookup *map;
6383 struct extent_map *em;
6387 u8 uuid[BTRFS_UUID_SIZE];
6392 logical = key->offset;
6393 length = btrfs_chunk_length(leaf, chunk);
6394 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6397 * Only need to verify chunk item if we're reading from sys chunk array,
6398 * as chunk item in tree block is already verified by tree-checker.
6400 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6401 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6406 read_lock(&map_tree->map_tree.lock);
6407 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6408 read_unlock(&map_tree->map_tree.lock);
6410 /* already mapped? */
6411 if (em && em->start <= logical && em->start + em->len > logical) {
6412 free_extent_map(em);
6415 free_extent_map(em);
6418 em = alloc_extent_map();
6421 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6423 free_extent_map(em);
6427 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6428 em->map_lookup = map;
6429 em->start = logical;
6432 em->block_start = 0;
6433 em->block_len = em->len;
6435 map->num_stripes = num_stripes;
6436 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6437 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6438 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6439 map->type = btrfs_chunk_type(leaf, chunk);
6440 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6441 map->verified_stripes = 0;
6442 for (i = 0; i < num_stripes; i++) {
6443 map->stripes[i].physical =
6444 btrfs_stripe_offset_nr(leaf, chunk, i);
6445 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6446 read_extent_buffer(leaf, uuid, (unsigned long)
6447 btrfs_stripe_dev_uuid_nr(chunk, i),
6449 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6450 devid, uuid, NULL, true);
6451 if (!map->stripes[i].dev &&
6452 !btrfs_test_opt(fs_info, DEGRADED)) {
6453 free_extent_map(em);
6454 btrfs_report_missing_device(fs_info, devid, uuid, true);
6457 if (!map->stripes[i].dev) {
6458 map->stripes[i].dev =
6459 add_missing_dev(fs_info->fs_devices, devid,
6461 if (IS_ERR(map->stripes[i].dev)) {
6462 free_extent_map(em);
6464 "failed to init missing dev %llu: %ld",
6465 devid, PTR_ERR(map->stripes[i].dev));
6466 return PTR_ERR(map->stripes[i].dev);
6468 btrfs_report_missing_device(fs_info, devid, uuid, false);
6470 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6471 &(map->stripes[i].dev->dev_state));
6475 write_lock(&map_tree->map_tree.lock);
6476 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6477 write_unlock(&map_tree->map_tree.lock);
6480 "failed to add chunk map, start=%llu len=%llu: %d",
6481 em->start, em->len, ret);
6483 free_extent_map(em);
6488 static void fill_device_from_item(struct extent_buffer *leaf,
6489 struct btrfs_dev_item *dev_item,
6490 struct btrfs_device *device)
6494 device->devid = btrfs_device_id(leaf, dev_item);
6495 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6496 device->total_bytes = device->disk_total_bytes;
6497 device->commit_total_bytes = device->disk_total_bytes;
6498 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6499 device->commit_bytes_used = device->bytes_used;
6500 device->type = btrfs_device_type(leaf, dev_item);
6501 device->io_align = btrfs_device_io_align(leaf, dev_item);
6502 device->io_width = btrfs_device_io_width(leaf, dev_item);
6503 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6504 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6505 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6507 ptr = btrfs_device_uuid(dev_item);
6508 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6511 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6514 struct btrfs_fs_devices *fs_devices;
6517 lockdep_assert_held(&uuid_mutex);
6520 fs_devices = fs_info->fs_devices->seed;
6521 while (fs_devices) {
6522 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6525 fs_devices = fs_devices->seed;
6528 fs_devices = find_fsid(fsid);
6530 if (!btrfs_test_opt(fs_info, DEGRADED))
6531 return ERR_PTR(-ENOENT);
6533 fs_devices = alloc_fs_devices(fsid);
6534 if (IS_ERR(fs_devices))
6537 fs_devices->seeding = 1;
6538 fs_devices->opened = 1;
6542 fs_devices = clone_fs_devices(fs_devices);
6543 if (IS_ERR(fs_devices))
6546 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6548 free_fs_devices(fs_devices);
6549 fs_devices = ERR_PTR(ret);
6553 if (!fs_devices->seeding) {
6554 close_fs_devices(fs_devices);
6555 free_fs_devices(fs_devices);
6556 fs_devices = ERR_PTR(-EINVAL);
6560 fs_devices->seed = fs_info->fs_devices->seed;
6561 fs_info->fs_devices->seed = fs_devices;
6566 static int read_one_dev(struct btrfs_fs_info *fs_info,
6567 struct extent_buffer *leaf,
6568 struct btrfs_dev_item *dev_item)
6570 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6571 struct btrfs_device *device;
6574 u8 fs_uuid[BTRFS_FSID_SIZE];
6575 u8 dev_uuid[BTRFS_UUID_SIZE];
6577 devid = btrfs_device_id(leaf, dev_item);
6578 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6580 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6583 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6584 fs_devices = open_seed_devices(fs_info, fs_uuid);
6585 if (IS_ERR(fs_devices))
6586 return PTR_ERR(fs_devices);
6589 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6592 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6593 btrfs_report_missing_device(fs_info, devid,
6598 device = add_missing_dev(fs_devices, devid, dev_uuid);
6599 if (IS_ERR(device)) {
6601 "failed to add missing dev %llu: %ld",
6602 devid, PTR_ERR(device));
6603 return PTR_ERR(device);
6605 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6607 if (!device->bdev) {
6608 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6609 btrfs_report_missing_device(fs_info,
6610 devid, dev_uuid, true);
6613 btrfs_report_missing_device(fs_info, devid,
6617 if (!device->bdev &&
6618 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6620 * this happens when a device that was properly setup
6621 * in the device info lists suddenly goes bad.
6622 * device->bdev is NULL, and so we have to set
6623 * device->missing to one here
6625 device->fs_devices->missing_devices++;
6626 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6629 /* Move the device to its own fs_devices */
6630 if (device->fs_devices != fs_devices) {
6631 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6632 &device->dev_state));
6634 list_move(&device->dev_list, &fs_devices->devices);
6635 device->fs_devices->num_devices--;
6636 fs_devices->num_devices++;
6638 device->fs_devices->missing_devices--;
6639 fs_devices->missing_devices++;
6641 device->fs_devices = fs_devices;
6645 if (device->fs_devices != fs_info->fs_devices) {
6646 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6647 if (device->generation !=
6648 btrfs_device_generation(leaf, dev_item))
6652 fill_device_from_item(leaf, dev_item, device);
6653 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6654 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6655 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6656 device->fs_devices->total_rw_bytes += device->total_bytes;
6657 atomic64_add(device->total_bytes - device->bytes_used,
6658 &fs_info->free_chunk_space);
6664 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6666 struct btrfs_root *root = fs_info->tree_root;
6667 struct btrfs_super_block *super_copy = fs_info->super_copy;
6668 struct extent_buffer *sb;
6669 struct btrfs_disk_key *disk_key;
6670 struct btrfs_chunk *chunk;
6672 unsigned long sb_array_offset;
6679 struct btrfs_key key;
6681 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6683 * This will create extent buffer of nodesize, superblock size is
6684 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6685 * overallocate but we can keep it as-is, only the first page is used.
6687 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6690 set_extent_buffer_uptodate(sb);
6691 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6693 * The sb extent buffer is artificial and just used to read the system array.
6694 * set_extent_buffer_uptodate() call does not properly mark all it's
6695 * pages up-to-date when the page is larger: extent does not cover the
6696 * whole page and consequently check_page_uptodate does not find all
6697 * the page's extents up-to-date (the hole beyond sb),
6698 * write_extent_buffer then triggers a WARN_ON.
6700 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6701 * but sb spans only this function. Add an explicit SetPageUptodate call
6702 * to silence the warning eg. on PowerPC 64.
6704 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6705 SetPageUptodate(sb->pages[0]);
6707 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6708 array_size = btrfs_super_sys_array_size(super_copy);
6710 array_ptr = super_copy->sys_chunk_array;
6711 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6714 while (cur_offset < array_size) {
6715 disk_key = (struct btrfs_disk_key *)array_ptr;
6716 len = sizeof(*disk_key);
6717 if (cur_offset + len > array_size)
6718 goto out_short_read;
6720 btrfs_disk_key_to_cpu(&key, disk_key);
6723 sb_array_offset += len;
6726 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6727 chunk = (struct btrfs_chunk *)sb_array_offset;
6729 * At least one btrfs_chunk with one stripe must be
6730 * present, exact stripe count check comes afterwards
6732 len = btrfs_chunk_item_size(1);
6733 if (cur_offset + len > array_size)
6734 goto out_short_read;
6736 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6739 "invalid number of stripes %u in sys_array at offset %u",
6740 num_stripes, cur_offset);
6745 type = btrfs_chunk_type(sb, chunk);
6746 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6748 "invalid chunk type %llu in sys_array at offset %u",
6754 len = btrfs_chunk_item_size(num_stripes);
6755 if (cur_offset + len > array_size)
6756 goto out_short_read;
6758 ret = read_one_chunk(fs_info, &key, sb, chunk);
6763 "unexpected item type %u in sys_array at offset %u",
6764 (u32)key.type, cur_offset);
6769 sb_array_offset += len;
6772 clear_extent_buffer_uptodate(sb);
6773 free_extent_buffer_stale(sb);
6777 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6779 clear_extent_buffer_uptodate(sb);
6780 free_extent_buffer_stale(sb);
6785 * Check if all chunks in the fs are OK for read-write degraded mount
6787 * If the @failing_dev is specified, it's accounted as missing.
6789 * Return true if all chunks meet the minimal RW mount requirements.
6790 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6792 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6793 struct btrfs_device *failing_dev)
6795 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6796 struct extent_map *em;
6800 read_lock(&map_tree->map_tree.lock);
6801 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6802 read_unlock(&map_tree->map_tree.lock);
6803 /* No chunk at all? Return false anyway */
6809 struct map_lookup *map;
6814 map = em->map_lookup;
6816 btrfs_get_num_tolerated_disk_barrier_failures(
6818 for (i = 0; i < map->num_stripes; i++) {
6819 struct btrfs_device *dev = map->stripes[i].dev;
6821 if (!dev || !dev->bdev ||
6822 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6823 dev->last_flush_error)
6825 else if (failing_dev && failing_dev == dev)
6828 if (missing > max_tolerated) {
6831 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6832 em->start, missing, max_tolerated);
6833 free_extent_map(em);
6837 next_start = extent_map_end(em);
6838 free_extent_map(em);
6840 read_lock(&map_tree->map_tree.lock);
6841 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6842 (u64)(-1) - next_start);
6843 read_unlock(&map_tree->map_tree.lock);
6849 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6851 struct btrfs_root *root = fs_info->chunk_root;
6852 struct btrfs_path *path;
6853 struct extent_buffer *leaf;
6854 struct btrfs_key key;
6855 struct btrfs_key found_key;
6860 path = btrfs_alloc_path();
6865 * uuid_mutex is needed only if we are mounting a sprout FS
6866 * otherwise we don't need it.
6868 mutex_lock(&uuid_mutex);
6869 mutex_lock(&fs_info->chunk_mutex);
6872 * It is possible for mount and umount to race in such a way that
6873 * we execute this code path, but open_fs_devices failed to clear
6874 * total_rw_bytes. We certainly want it cleared before reading the
6875 * device items, so clear it here.
6877 fs_info->fs_devices->total_rw_bytes = 0;
6880 * Read all device items, and then all the chunk items. All
6881 * device items are found before any chunk item (their object id
6882 * is smaller than the lowest possible object id for a chunk
6883 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6885 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6888 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6892 leaf = path->nodes[0];
6893 slot = path->slots[0];
6894 if (slot >= btrfs_header_nritems(leaf)) {
6895 ret = btrfs_next_leaf(root, path);
6902 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6903 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6904 struct btrfs_dev_item *dev_item;
6905 dev_item = btrfs_item_ptr(leaf, slot,
6906 struct btrfs_dev_item);
6907 ret = read_one_dev(fs_info, leaf, dev_item);
6911 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6912 struct btrfs_chunk *chunk;
6913 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6914 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
6922 * After loading chunk tree, we've got all device information,
6923 * do another round of validation checks.
6925 if (total_dev != fs_info->fs_devices->total_devices) {
6927 "super_num_devices %llu mismatch with num_devices %llu found here",
6928 btrfs_super_num_devices(fs_info->super_copy),
6933 if (btrfs_super_total_bytes(fs_info->super_copy) <
6934 fs_info->fs_devices->total_rw_bytes) {
6936 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
6937 btrfs_super_total_bytes(fs_info->super_copy),
6938 fs_info->fs_devices->total_rw_bytes);
6944 mutex_unlock(&fs_info->chunk_mutex);
6945 mutex_unlock(&uuid_mutex);
6947 btrfs_free_path(path);
6951 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6953 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6954 struct btrfs_device *device;
6956 while (fs_devices) {
6957 mutex_lock(&fs_devices->device_list_mutex);
6958 list_for_each_entry(device, &fs_devices->devices, dev_list)
6959 device->fs_info = fs_info;
6960 mutex_unlock(&fs_devices->device_list_mutex);
6962 fs_devices = fs_devices->seed;
6966 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6970 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6971 btrfs_dev_stat_reset(dev, i);
6974 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6976 struct btrfs_key key;
6977 struct btrfs_key found_key;
6978 struct btrfs_root *dev_root = fs_info->dev_root;
6979 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6980 struct extent_buffer *eb;
6983 struct btrfs_device *device;
6984 struct btrfs_path *path = NULL;
6987 path = btrfs_alloc_path();
6993 mutex_lock(&fs_devices->device_list_mutex);
6994 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6996 struct btrfs_dev_stats_item *ptr;
6998 key.objectid = BTRFS_DEV_STATS_OBJECTID;
6999 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7000 key.offset = device->devid;
7001 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7003 __btrfs_reset_dev_stats(device);
7004 device->dev_stats_valid = 1;
7005 btrfs_release_path(path);
7008 slot = path->slots[0];
7009 eb = path->nodes[0];
7010 btrfs_item_key_to_cpu(eb, &found_key, slot);
7011 item_size = btrfs_item_size_nr(eb, slot);
7013 ptr = btrfs_item_ptr(eb, slot,
7014 struct btrfs_dev_stats_item);
7016 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7017 if (item_size >= (1 + i) * sizeof(__le64))
7018 btrfs_dev_stat_set(device, i,
7019 btrfs_dev_stats_value(eb, ptr, i));
7021 btrfs_dev_stat_reset(device, i);
7024 device->dev_stats_valid = 1;
7025 btrfs_dev_stat_print_on_load(device);
7026 btrfs_release_path(path);
7028 mutex_unlock(&fs_devices->device_list_mutex);
7031 btrfs_free_path(path);
7032 return ret < 0 ? ret : 0;
7035 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7036 struct btrfs_device *device)
7038 struct btrfs_fs_info *fs_info = trans->fs_info;
7039 struct btrfs_root *dev_root = fs_info->dev_root;
7040 struct btrfs_path *path;
7041 struct btrfs_key key;
7042 struct extent_buffer *eb;
7043 struct btrfs_dev_stats_item *ptr;
7047 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7048 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7049 key.offset = device->devid;
7051 path = btrfs_alloc_path();
7054 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7056 btrfs_warn_in_rcu(fs_info,
7057 "error %d while searching for dev_stats item for device %s",
7058 ret, rcu_str_deref(device->name));
7063 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7064 /* need to delete old one and insert a new one */
7065 ret = btrfs_del_item(trans, dev_root, path);
7067 btrfs_warn_in_rcu(fs_info,
7068 "delete too small dev_stats item for device %s failed %d",
7069 rcu_str_deref(device->name), ret);
7076 /* need to insert a new item */
7077 btrfs_release_path(path);
7078 ret = btrfs_insert_empty_item(trans, dev_root, path,
7079 &key, sizeof(*ptr));
7081 btrfs_warn_in_rcu(fs_info,
7082 "insert dev_stats item for device %s failed %d",
7083 rcu_str_deref(device->name), ret);
7088 eb = path->nodes[0];
7089 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7090 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7091 btrfs_set_dev_stats_value(eb, ptr, i,
7092 btrfs_dev_stat_read(device, i));
7093 btrfs_mark_buffer_dirty(eb);
7096 btrfs_free_path(path);
7101 * called from commit_transaction. Writes all changed device stats to disk.
7103 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7104 struct btrfs_fs_info *fs_info)
7106 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7107 struct btrfs_device *device;
7111 mutex_lock(&fs_devices->device_list_mutex);
7112 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7113 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7114 if (!device->dev_stats_valid || stats_cnt == 0)
7119 * There is a LOAD-LOAD control dependency between the value of
7120 * dev_stats_ccnt and updating the on-disk values which requires
7121 * reading the in-memory counters. Such control dependencies
7122 * require explicit read memory barriers.
7124 * This memory barriers pairs with smp_mb__before_atomic in
7125 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7126 * barrier implied by atomic_xchg in
7127 * btrfs_dev_stats_read_and_reset
7131 ret = update_dev_stat_item(trans, device);
7133 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7135 mutex_unlock(&fs_devices->device_list_mutex);
7140 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7142 btrfs_dev_stat_inc(dev, index);
7143 btrfs_dev_stat_print_on_error(dev);
7146 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7148 if (!dev->dev_stats_valid)
7150 btrfs_err_rl_in_rcu(dev->fs_info,
7151 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7152 rcu_str_deref(dev->name),
7153 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7154 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7155 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7156 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7157 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7160 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7164 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7165 if (btrfs_dev_stat_read(dev, i) != 0)
7167 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7168 return; /* all values == 0, suppress message */
7170 btrfs_info_in_rcu(dev->fs_info,
7171 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7172 rcu_str_deref(dev->name),
7173 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7174 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7175 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7176 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7177 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7180 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7181 struct btrfs_ioctl_get_dev_stats *stats)
7183 struct btrfs_device *dev;
7184 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7187 mutex_lock(&fs_devices->device_list_mutex);
7188 dev = btrfs_find_device(fs_info->fs_devices, stats->devid,
7190 mutex_unlock(&fs_devices->device_list_mutex);
7193 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7195 } else if (!dev->dev_stats_valid) {
7196 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7198 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7199 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7200 if (stats->nr_items > i)
7202 btrfs_dev_stat_read_and_reset(dev, i);
7204 btrfs_dev_stat_reset(dev, i);
7206 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7207 current->comm, task_pid_nr(current));
7209 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7210 if (stats->nr_items > i)
7211 stats->values[i] = btrfs_dev_stat_read(dev, i);
7213 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7214 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7218 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7220 struct buffer_head *bh;
7221 struct btrfs_super_block *disk_super;
7227 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7230 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7233 disk_super = (struct btrfs_super_block *)bh->b_data;
7235 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7236 set_buffer_dirty(bh);
7237 sync_dirty_buffer(bh);
7241 /* Notify udev that device has changed */
7242 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7244 /* Update ctime/mtime for device path for libblkid */
7245 update_dev_time(device_path);
7249 * Update the size of all devices, which is used for writing out the
7252 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7254 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7255 struct btrfs_device *curr, *next;
7257 if (list_empty(&fs_devices->resized_devices))
7260 mutex_lock(&fs_devices->device_list_mutex);
7261 mutex_lock(&fs_info->chunk_mutex);
7262 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7264 list_del_init(&curr->resized_list);
7265 curr->commit_total_bytes = curr->disk_total_bytes;
7267 mutex_unlock(&fs_info->chunk_mutex);
7268 mutex_unlock(&fs_devices->device_list_mutex);
7271 /* Must be invoked during the transaction commit */
7272 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7274 struct btrfs_fs_info *fs_info = trans->fs_info;
7275 struct extent_map *em;
7276 struct map_lookup *map;
7277 struct btrfs_device *dev;
7280 if (list_empty(&trans->pending_chunks))
7283 /* In order to kick the device replace finish process */
7284 mutex_lock(&fs_info->chunk_mutex);
7285 list_for_each_entry(em, &trans->pending_chunks, list) {
7286 map = em->map_lookup;
7288 for (i = 0; i < map->num_stripes; i++) {
7289 dev = map->stripes[i].dev;
7290 dev->commit_bytes_used = dev->bytes_used;
7291 dev->has_pending_chunks = false;
7294 mutex_unlock(&fs_info->chunk_mutex);
7297 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7299 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7300 while (fs_devices) {
7301 fs_devices->fs_info = fs_info;
7302 fs_devices = fs_devices->seed;
7306 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7308 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7309 while (fs_devices) {
7310 fs_devices->fs_info = NULL;
7311 fs_devices = fs_devices->seed;
7316 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7318 int btrfs_bg_type_to_factor(u64 flags)
7320 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
7321 BTRFS_BLOCK_GROUP_RAID10))
7327 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
7329 int index = btrfs_bg_flags_to_raid_index(type);
7330 int ncopies = btrfs_raid_array[index].ncopies;
7333 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
7334 case BTRFS_BLOCK_GROUP_RAID5:
7335 data_stripes = num_stripes - 1;
7337 case BTRFS_BLOCK_GROUP_RAID6:
7338 data_stripes = num_stripes - 2;
7341 data_stripes = num_stripes / ncopies;
7344 return div_u64(chunk_len, data_stripes);
7347 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7348 u64 chunk_offset, u64 devid,
7349 u64 physical_offset, u64 physical_len)
7351 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7352 struct extent_map *em;
7353 struct map_lookup *map;
7354 struct btrfs_device *dev;
7360 read_lock(&em_tree->lock);
7361 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7362 read_unlock(&em_tree->lock);
7366 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7367 physical_offset, devid);
7372 map = em->map_lookup;
7373 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7374 if (physical_len != stripe_len) {
7376 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7377 physical_offset, devid, em->start, physical_len,
7383 for (i = 0; i < map->num_stripes; i++) {
7384 if (map->stripes[i].dev->devid == devid &&
7385 map->stripes[i].physical == physical_offset) {
7387 if (map->verified_stripes >= map->num_stripes) {
7389 "too many dev extents for chunk %llu found",
7394 map->verified_stripes++;
7400 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7401 physical_offset, devid);
7405 /* Make sure no dev extent is beyond device bondary */
7406 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7408 btrfs_err(fs_info, "failed to find devid %llu", devid);
7413 /* It's possible this device is a dummy for seed device */
7414 if (dev->disk_total_bytes == 0) {
7415 dev = btrfs_find_device(fs_info->fs_devices->seed, devid,
7418 btrfs_err(fs_info, "failed to find seed devid %llu",
7425 if (physical_offset + physical_len > dev->disk_total_bytes) {
7427 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7428 devid, physical_offset, physical_len,
7429 dev->disk_total_bytes);
7434 free_extent_map(em);
7438 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7440 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7441 struct extent_map *em;
7442 struct rb_node *node;
7445 read_lock(&em_tree->lock);
7446 for (node = rb_first(&em_tree->map); node; node = rb_next(node)) {
7447 em = rb_entry(node, struct extent_map, rb_node);
7448 if (em->map_lookup->num_stripes !=
7449 em->map_lookup->verified_stripes) {
7451 "chunk %llu has missing dev extent, have %d expect %d",
7452 em->start, em->map_lookup->verified_stripes,
7453 em->map_lookup->num_stripes);
7459 read_unlock(&em_tree->lock);
7464 * Ensure that all dev extents are mapped to correct chunk, otherwise
7465 * later chunk allocation/free would cause unexpected behavior.
7467 * NOTE: This will iterate through the whole device tree, which should be of
7468 * the same size level as the chunk tree. This slightly increases mount time.
7470 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7472 struct btrfs_path *path;
7473 struct btrfs_root *root = fs_info->dev_root;
7474 struct btrfs_key key;
7476 u64 prev_dev_ext_end = 0;
7480 key.type = BTRFS_DEV_EXTENT_KEY;
7483 path = btrfs_alloc_path();
7487 path->reada = READA_FORWARD;
7488 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7492 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7493 ret = btrfs_next_item(root, path);
7496 /* No dev extents at all? Not good */
7503 struct extent_buffer *leaf = path->nodes[0];
7504 struct btrfs_dev_extent *dext;
7505 int slot = path->slots[0];
7507 u64 physical_offset;
7511 btrfs_item_key_to_cpu(leaf, &key, slot);
7512 if (key.type != BTRFS_DEV_EXTENT_KEY)
7514 devid = key.objectid;
7515 physical_offset = key.offset;
7517 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7518 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7519 physical_len = btrfs_dev_extent_length(leaf, dext);
7521 /* Check if this dev extent overlaps with the previous one */
7522 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7524 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7525 devid, physical_offset, prev_dev_ext_end);
7530 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7531 physical_offset, physical_len);
7535 prev_dev_ext_end = physical_offset + physical_len;
7537 ret = btrfs_next_item(root, path);
7546 /* Ensure all chunks have corresponding dev extents */
7547 ret = verify_chunk_dev_extent_mapping(fs_info);
7549 btrfs_free_path(path);