1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
8 #include <linux/slab.h>
9 #include <linux/buffer_head.h>
10 #include <linux/blkdev.h>
11 #include <linux/ratelimit.h>
12 #include <linux/kthread.h>
13 #include <linux/raid/pq.h>
14 #include <linux/semaphore.h>
15 #include <linux/uuid.h>
16 #include <linux/list_sort.h>
18 #include "extent_map.h"
20 #include "transaction.h"
21 #include "print-tree.h"
24 #include "async-thread.h"
25 #include "check-integrity.h"
26 #include "rcu-string.h"
28 #include "dev-replace.h"
31 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
32 [BTRFS_RAID_RAID10] = {
35 .devs_max = 0, /* 0 == as many as possible */
37 .tolerated_failures = 1,
41 .raid_name = "raid10",
42 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
43 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
45 [BTRFS_RAID_RAID1] = {
50 .tolerated_failures = 1,
55 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
56 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
63 .tolerated_failures = 0,
68 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
71 [BTRFS_RAID_RAID0] = {
76 .tolerated_failures = 0,
81 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
84 [BTRFS_RAID_SINGLE] = {
89 .tolerated_failures = 0,
93 .raid_name = "single",
97 [BTRFS_RAID_RAID5] = {
102 .tolerated_failures = 1,
106 .raid_name = "raid5",
107 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
108 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
110 [BTRFS_RAID_RAID6] = {
115 .tolerated_failures = 2,
119 .raid_name = "raid6",
120 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
121 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
125 const char *get_raid_name(enum btrfs_raid_types type)
127 if (type >= BTRFS_NR_RAID_TYPES)
130 return btrfs_raid_array[type].raid_name;
133 static int init_first_rw_device(struct btrfs_trans_handle *trans,
134 struct btrfs_fs_info *fs_info);
135 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
136 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
137 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
138 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
139 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
140 enum btrfs_map_op op,
141 u64 logical, u64 *length,
142 struct btrfs_bio **bbio_ret,
143 int mirror_num, int need_raid_map);
149 * There are several mutexes that protect manipulation of devices and low-level
150 * structures like chunks but not block groups, extents or files
152 * uuid_mutex (global lock)
153 * ------------------------
154 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
155 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
156 * device) or requested by the device= mount option
158 * the mutex can be very coarse and can cover long-running operations
160 * protects: updates to fs_devices counters like missing devices, rw devices,
161 * seeding, structure cloning, openning/closing devices at mount/umount time
163 * global::fs_devs - add, remove, updates to the global list
165 * does not protect: manipulation of the fs_devices::devices list!
167 * btrfs_device::name - renames (write side), read is RCU
169 * fs_devices::device_list_mutex (per-fs, with RCU)
170 * ------------------------------------------------
171 * protects updates to fs_devices::devices, ie. adding and deleting
173 * simple list traversal with read-only actions can be done with RCU protection
175 * may be used to exclude some operations from running concurrently without any
176 * modifications to the list (see write_all_supers)
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);
358 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
361 * If devid and uuid are both specified, the match must be exact, otherwise
362 * only devid is used.
364 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
365 u64 devid, const u8 *uuid)
367 struct btrfs_device *dev;
369 list_for_each_entry(dev, &fs_devices->devices, dev_list) {
370 if (dev->devid == devid &&
371 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
378 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
380 struct btrfs_fs_devices *fs_devices;
382 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
383 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
390 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
391 int flush, struct block_device **bdev,
392 struct buffer_head **bh)
396 *bdev = blkdev_get_by_path(device_path, flags, holder);
399 ret = PTR_ERR(*bdev);
404 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
405 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
407 blkdev_put(*bdev, flags);
410 invalidate_bdev(*bdev);
411 *bh = btrfs_read_dev_super(*bdev);
414 blkdev_put(*bdev, flags);
426 static void requeue_list(struct btrfs_pending_bios *pending_bios,
427 struct bio *head, struct bio *tail)
430 struct bio *old_head;
432 old_head = pending_bios->head;
433 pending_bios->head = head;
434 if (pending_bios->tail)
435 tail->bi_next = old_head;
437 pending_bios->tail = tail;
441 * we try to collect pending bios for a device so we don't get a large
442 * number of procs sending bios down to the same device. This greatly
443 * improves the schedulers ability to collect and merge the bios.
445 * But, it also turns into a long list of bios to process and that is sure
446 * to eventually make the worker thread block. The solution here is to
447 * make some progress and then put this work struct back at the end of
448 * the list if the block device is congested. This way, multiple devices
449 * can make progress from a single worker thread.
451 static noinline void run_scheduled_bios(struct btrfs_device *device)
453 struct btrfs_fs_info *fs_info = device->fs_info;
455 struct backing_dev_info *bdi;
456 struct btrfs_pending_bios *pending_bios;
460 unsigned long num_run;
461 unsigned long batch_run = 0;
462 unsigned long last_waited = 0;
464 int sync_pending = 0;
465 struct blk_plug plug;
468 * this function runs all the bios we've collected for
469 * a particular device. We don't want to wander off to
470 * another device without first sending all of these down.
471 * So, setup a plug here and finish it off before we return
473 blk_start_plug(&plug);
475 bdi = device->bdev->bd_bdi;
478 spin_lock(&device->io_lock);
483 /* take all the bios off the list at once and process them
484 * later on (without the lock held). But, remember the
485 * tail and other pointers so the bios can be properly reinserted
486 * into the list if we hit congestion
488 if (!force_reg && device->pending_sync_bios.head) {
489 pending_bios = &device->pending_sync_bios;
492 pending_bios = &device->pending_bios;
496 pending = pending_bios->head;
497 tail = pending_bios->tail;
498 WARN_ON(pending && !tail);
501 * if pending was null this time around, no bios need processing
502 * at all and we can stop. Otherwise it'll loop back up again
503 * and do an additional check so no bios are missed.
505 * device->running_pending is used to synchronize with the
508 if (device->pending_sync_bios.head == NULL &&
509 device->pending_bios.head == NULL) {
511 device->running_pending = 0;
514 device->running_pending = 1;
517 pending_bios->head = NULL;
518 pending_bios->tail = NULL;
520 spin_unlock(&device->io_lock);
525 /* we want to work on both lists, but do more bios on the
526 * sync list than the regular list
529 pending_bios != &device->pending_sync_bios &&
530 device->pending_sync_bios.head) ||
531 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
532 device->pending_bios.head)) {
533 spin_lock(&device->io_lock);
534 requeue_list(pending_bios, pending, tail);
539 pending = pending->bi_next;
542 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
545 * if we're doing the sync list, record that our
546 * plug has some sync requests on it
548 * If we're doing the regular list and there are
549 * sync requests sitting around, unplug before
552 if (pending_bios == &device->pending_sync_bios) {
554 } else if (sync_pending) {
555 blk_finish_plug(&plug);
556 blk_start_plug(&plug);
560 btrfsic_submit_bio(cur);
567 * we made progress, there is more work to do and the bdi
568 * is now congested. Back off and let other work structs
571 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
572 fs_info->fs_devices->open_devices > 1) {
573 struct io_context *ioc;
575 ioc = current->io_context;
578 * the main goal here is that we don't want to
579 * block if we're going to be able to submit
580 * more requests without blocking.
582 * This code does two great things, it pokes into
583 * the elevator code from a filesystem _and_
584 * it makes assumptions about how batching works.
586 if (ioc && ioc->nr_batch_requests > 0 &&
587 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
589 ioc->last_waited == last_waited)) {
591 * we want to go through our batch of
592 * requests and stop. So, we copy out
593 * the ioc->last_waited time and test
594 * against it before looping
596 last_waited = ioc->last_waited;
600 spin_lock(&device->io_lock);
601 requeue_list(pending_bios, pending, tail);
602 device->running_pending = 1;
604 spin_unlock(&device->io_lock);
605 btrfs_queue_work(fs_info->submit_workers,
615 spin_lock(&device->io_lock);
616 if (device->pending_bios.head || device->pending_sync_bios.head)
618 spin_unlock(&device->io_lock);
621 blk_finish_plug(&plug);
624 static void pending_bios_fn(struct btrfs_work *work)
626 struct btrfs_device *device;
628 device = container_of(work, struct btrfs_device, work);
629 run_scheduled_bios(device);
633 * Search and remove all stale (devices which are not mounted) devices.
634 * When both inputs are NULL, it will search and release all stale devices.
635 * path: Optional. When provided will it release all unmounted devices
636 * matching this path only.
637 * skip_dev: Optional. Will skip this device when searching for the stale
640 static void btrfs_free_stale_devices(const char *path,
641 struct btrfs_device *skip_device)
643 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
644 struct btrfs_device *device, *tmp_device;
646 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
647 mutex_lock(&fs_devices->device_list_mutex);
648 if (fs_devices->opened) {
649 mutex_unlock(&fs_devices->device_list_mutex);
653 list_for_each_entry_safe(device, tmp_device,
654 &fs_devices->devices, dev_list) {
657 if (skip_device && skip_device == device)
659 if (path && !device->name)
664 not_found = strcmp(rcu_str_deref(device->name),
670 /* delete the stale device */
671 fs_devices->num_devices--;
672 list_del(&device->dev_list);
673 btrfs_free_device(device);
675 if (fs_devices->num_devices == 0)
678 mutex_unlock(&fs_devices->device_list_mutex);
679 if (fs_devices->num_devices == 0) {
680 btrfs_sysfs_remove_fsid(fs_devices);
681 list_del(&fs_devices->fs_list);
682 free_fs_devices(fs_devices);
687 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
688 struct btrfs_device *device, fmode_t flags,
691 struct request_queue *q;
692 struct block_device *bdev;
693 struct buffer_head *bh;
694 struct btrfs_super_block *disk_super;
703 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
708 disk_super = (struct btrfs_super_block *)bh->b_data;
709 devid = btrfs_stack_device_id(&disk_super->dev_item);
710 if (devid != device->devid)
713 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
716 device->generation = btrfs_super_generation(disk_super);
718 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
719 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
720 fs_devices->seeding = 1;
722 if (bdev_read_only(bdev))
723 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
725 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
728 q = bdev_get_queue(bdev);
729 if (!blk_queue_nonrot(q))
730 fs_devices->rotating = 1;
733 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
734 device->mode = flags;
736 fs_devices->open_devices++;
737 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
738 device->devid != BTRFS_DEV_REPLACE_DEVID) {
739 fs_devices->rw_devices++;
740 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
748 blkdev_put(bdev, flags);
754 * Add new device to list of registered devices
757 * device pointer which was just added or updated when successful
758 * error pointer when failed
760 static noinline struct btrfs_device *device_list_add(const char *path,
761 struct btrfs_super_block *disk_super,
762 bool *new_device_added)
764 struct btrfs_device *device;
765 struct btrfs_fs_devices *fs_devices;
766 struct rcu_string *name;
767 u64 found_transid = btrfs_super_generation(disk_super);
768 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
770 fs_devices = find_fsid(disk_super->fsid);
772 fs_devices = alloc_fs_devices(disk_super->fsid);
773 if (IS_ERR(fs_devices))
774 return ERR_CAST(fs_devices);
776 mutex_lock(&fs_devices->device_list_mutex);
777 list_add(&fs_devices->fs_list, &fs_uuids);
781 mutex_lock(&fs_devices->device_list_mutex);
782 device = find_device(fs_devices, devid,
783 disk_super->dev_item.uuid);
787 if (fs_devices->opened) {
788 mutex_unlock(&fs_devices->device_list_mutex);
789 return ERR_PTR(-EBUSY);
792 device = btrfs_alloc_device(NULL, &devid,
793 disk_super->dev_item.uuid);
794 if (IS_ERR(device)) {
795 mutex_unlock(&fs_devices->device_list_mutex);
796 /* we can safely leave the fs_devices entry around */
800 name = rcu_string_strdup(path, GFP_NOFS);
802 btrfs_free_device(device);
803 mutex_unlock(&fs_devices->device_list_mutex);
804 return ERR_PTR(-ENOMEM);
806 rcu_assign_pointer(device->name, name);
808 list_add_rcu(&device->dev_list, &fs_devices->devices);
809 fs_devices->num_devices++;
811 device->fs_devices = fs_devices;
812 *new_device_added = true;
814 if (disk_super->label[0])
815 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
816 disk_super->label, devid, found_transid, path);
818 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
819 disk_super->fsid, devid, found_transid, path);
821 } else if (!device->name || strcmp(device->name->str, path)) {
823 * When FS is already mounted.
824 * 1. If you are here and if the device->name is NULL that
825 * means this device was missing at time of FS mount.
826 * 2. If you are here and if the device->name is different
827 * from 'path' that means either
828 * a. The same device disappeared and reappeared with
830 * b. The missing-disk-which-was-replaced, has
833 * We must allow 1 and 2a above. But 2b would be a spurious
836 * Further in case of 1 and 2a above, the disk at 'path'
837 * would have missed some transaction when it was away and
838 * in case of 2a the stale bdev has to be updated as well.
839 * 2b must not be allowed at all time.
843 * For now, we do allow update to btrfs_fs_device through the
844 * btrfs dev scan cli after FS has been mounted. We're still
845 * tracking a problem where systems fail mount by subvolume id
846 * when we reject replacement on a mounted FS.
848 if (!fs_devices->opened && found_transid < device->generation) {
850 * That is if the FS is _not_ mounted and if you
851 * are here, that means there is more than one
852 * disk with same uuid and devid.We keep the one
853 * with larger generation number or the last-in if
854 * generation are equal.
856 mutex_unlock(&fs_devices->device_list_mutex);
857 return ERR_PTR(-EEXIST);
860 name = rcu_string_strdup(path, GFP_NOFS);
862 mutex_unlock(&fs_devices->device_list_mutex);
863 return ERR_PTR(-ENOMEM);
865 rcu_string_free(device->name);
866 rcu_assign_pointer(device->name, name);
867 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
868 fs_devices->missing_devices--;
869 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
874 * Unmount does not free the btrfs_device struct but would zero
875 * generation along with most of the other members. So just update
876 * it back. We need it to pick the disk with largest generation
879 if (!fs_devices->opened)
880 device->generation = found_transid;
882 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
884 mutex_unlock(&fs_devices->device_list_mutex);
888 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
890 struct btrfs_fs_devices *fs_devices;
891 struct btrfs_device *device;
892 struct btrfs_device *orig_dev;
894 fs_devices = alloc_fs_devices(orig->fsid);
895 if (IS_ERR(fs_devices))
898 mutex_lock(&orig->device_list_mutex);
899 fs_devices->total_devices = orig->total_devices;
901 /* We have held the volume lock, it is safe to get the devices. */
902 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
903 struct rcu_string *name;
905 device = btrfs_alloc_device(NULL, &orig_dev->devid,
911 * This is ok to do without rcu read locked because we hold the
912 * uuid mutex so nothing we touch in here is going to disappear.
914 if (orig_dev->name) {
915 name = rcu_string_strdup(orig_dev->name->str,
918 btrfs_free_device(device);
921 rcu_assign_pointer(device->name, name);
924 list_add(&device->dev_list, &fs_devices->devices);
925 device->fs_devices = fs_devices;
926 fs_devices->num_devices++;
928 mutex_unlock(&orig->device_list_mutex);
931 mutex_unlock(&orig->device_list_mutex);
932 free_fs_devices(fs_devices);
933 return ERR_PTR(-ENOMEM);
937 * After we have read the system tree and know devids belonging to
938 * this filesystem, remove the device which does not belong there.
940 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
942 struct btrfs_device *device, *next;
943 struct btrfs_device *latest_dev = NULL;
945 mutex_lock(&uuid_mutex);
947 /* This is the initialized path, it is safe to release the devices. */
948 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
949 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
950 &device->dev_state)) {
951 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
952 &device->dev_state) &&
954 device->generation > latest_dev->generation)) {
960 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
962 * In the first step, keep the device which has
963 * the correct fsid and the devid that is used
964 * for the dev_replace procedure.
965 * In the second step, the dev_replace state is
966 * read from the device tree and it is known
967 * whether the procedure is really active or
968 * not, which means whether this device is
969 * used or whether it should be removed.
971 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
972 &device->dev_state)) {
977 blkdev_put(device->bdev, device->mode);
979 fs_devices->open_devices--;
981 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
982 list_del_init(&device->dev_alloc_list);
983 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
984 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
986 fs_devices->rw_devices--;
988 list_del_init(&device->dev_list);
989 fs_devices->num_devices--;
990 btrfs_free_device(device);
993 if (fs_devices->seed) {
994 fs_devices = fs_devices->seed;
998 fs_devices->latest_bdev = latest_dev->bdev;
1000 mutex_unlock(&uuid_mutex);
1003 static void free_device_rcu(struct rcu_head *head)
1005 struct btrfs_device *device;
1007 device = container_of(head, struct btrfs_device, rcu);
1008 btrfs_free_device(device);
1011 static void btrfs_close_bdev(struct btrfs_device *device)
1016 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1017 sync_blockdev(device->bdev);
1018 invalidate_bdev(device->bdev);
1021 blkdev_put(device->bdev, device->mode);
1024 static void btrfs_close_one_device(struct btrfs_device *device)
1026 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1027 struct btrfs_device *new_device;
1028 struct rcu_string *name;
1031 fs_devices->open_devices--;
1033 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1034 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1035 list_del_init(&device->dev_alloc_list);
1036 fs_devices->rw_devices--;
1039 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1040 fs_devices->missing_devices--;
1042 btrfs_close_bdev(device);
1044 new_device = btrfs_alloc_device(NULL, &device->devid,
1046 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1048 /* Safe because we are under uuid_mutex */
1050 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1051 BUG_ON(!name); /* -ENOMEM */
1052 rcu_assign_pointer(new_device->name, name);
1055 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1056 new_device->fs_devices = device->fs_devices;
1058 call_rcu(&device->rcu, free_device_rcu);
1061 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1063 struct btrfs_device *device, *tmp;
1065 if (--fs_devices->opened > 0)
1068 mutex_lock(&fs_devices->device_list_mutex);
1069 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1070 btrfs_close_one_device(device);
1072 mutex_unlock(&fs_devices->device_list_mutex);
1074 WARN_ON(fs_devices->open_devices);
1075 WARN_ON(fs_devices->rw_devices);
1076 fs_devices->opened = 0;
1077 fs_devices->seeding = 0;
1082 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1084 struct btrfs_fs_devices *seed_devices = NULL;
1087 mutex_lock(&uuid_mutex);
1088 ret = close_fs_devices(fs_devices);
1089 if (!fs_devices->opened) {
1090 seed_devices = fs_devices->seed;
1091 fs_devices->seed = NULL;
1093 mutex_unlock(&uuid_mutex);
1095 while (seed_devices) {
1096 fs_devices = seed_devices;
1097 seed_devices = fs_devices->seed;
1098 close_fs_devices(fs_devices);
1099 free_fs_devices(fs_devices);
1104 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1105 fmode_t flags, void *holder)
1107 struct btrfs_device *device;
1108 struct btrfs_device *latest_dev = NULL;
1111 flags |= FMODE_EXCL;
1113 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1114 /* Just open everything we can; ignore failures here */
1115 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1119 device->generation > latest_dev->generation)
1120 latest_dev = device;
1122 if (fs_devices->open_devices == 0) {
1126 fs_devices->opened = 1;
1127 fs_devices->latest_bdev = latest_dev->bdev;
1128 fs_devices->total_rw_bytes = 0;
1133 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1135 struct btrfs_device *dev1, *dev2;
1137 dev1 = list_entry(a, struct btrfs_device, dev_list);
1138 dev2 = list_entry(b, struct btrfs_device, dev_list);
1140 if (dev1->devid < dev2->devid)
1142 else if (dev1->devid > dev2->devid)
1147 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1148 fmode_t flags, void *holder)
1152 lockdep_assert_held(&uuid_mutex);
1154 mutex_lock(&fs_devices->device_list_mutex);
1155 if (fs_devices->opened) {
1156 fs_devices->opened++;
1159 list_sort(NULL, &fs_devices->devices, devid_cmp);
1160 ret = open_fs_devices(fs_devices, flags, holder);
1162 mutex_unlock(&fs_devices->device_list_mutex);
1167 static void btrfs_release_disk_super(struct page *page)
1173 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1175 struct btrfs_super_block **disk_super)
1180 /* make sure our super fits in the device */
1181 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1184 /* make sure our super fits in the page */
1185 if (sizeof(**disk_super) > PAGE_SIZE)
1188 /* make sure our super doesn't straddle pages on disk */
1189 index = bytenr >> PAGE_SHIFT;
1190 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1193 /* pull in the page with our super */
1194 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1197 if (IS_ERR_OR_NULL(*page))
1202 /* align our pointer to the offset of the super block */
1203 *disk_super = p + (bytenr & ~PAGE_MASK);
1205 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1206 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1207 btrfs_release_disk_super(*page);
1211 if ((*disk_super)->label[0] &&
1212 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1213 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1219 * Look for a btrfs signature on a device. This may be called out of the mount path
1220 * and we are not allowed to call set_blocksize during the scan. The superblock
1221 * is read via pagecache
1223 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1226 struct btrfs_super_block *disk_super;
1227 bool new_device_added = false;
1228 struct btrfs_device *device = NULL;
1229 struct block_device *bdev;
1233 lockdep_assert_held(&uuid_mutex);
1236 * we would like to check all the supers, but that would make
1237 * a btrfs mount succeed after a mkfs from a different FS.
1238 * So, we need to add a special mount option to scan for
1239 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1241 bytenr = btrfs_sb_offset(0);
1242 flags |= FMODE_EXCL;
1244 bdev = blkdev_get_by_path(path, flags, holder);
1246 return ERR_CAST(bdev);
1248 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1249 device = ERR_PTR(-EINVAL);
1250 goto error_bdev_put;
1253 device = device_list_add(path, disk_super, &new_device_added);
1254 if (!IS_ERR(device)) {
1255 if (new_device_added)
1256 btrfs_free_stale_devices(path, device);
1259 btrfs_release_disk_super(page);
1262 blkdev_put(bdev, flags);
1267 static int contains_pending_extent(struct btrfs_transaction *transaction,
1268 struct btrfs_device *device,
1269 u64 *start, u64 len)
1271 struct btrfs_fs_info *fs_info = device->fs_info;
1272 struct extent_map *em;
1273 struct list_head *search_list = &fs_info->pinned_chunks;
1275 u64 physical_start = *start;
1278 search_list = &transaction->pending_chunks;
1280 list_for_each_entry(em, search_list, list) {
1281 struct map_lookup *map;
1284 map = em->map_lookup;
1285 for (i = 0; i < map->num_stripes; i++) {
1288 if (map->stripes[i].dev != device)
1290 if (map->stripes[i].physical >= physical_start + len ||
1291 map->stripes[i].physical + em->orig_block_len <=
1295 * Make sure that while processing the pinned list we do
1296 * not override our *start with a lower value, because
1297 * we can have pinned chunks that fall within this
1298 * device hole and that have lower physical addresses
1299 * than the pending chunks we processed before. If we
1300 * do not take this special care we can end up getting
1301 * 2 pending chunks that start at the same physical
1302 * device offsets because the end offset of a pinned
1303 * chunk can be equal to the start offset of some
1306 end = map->stripes[i].physical + em->orig_block_len;
1313 if (search_list != &fs_info->pinned_chunks) {
1314 search_list = &fs_info->pinned_chunks;
1323 * find_free_dev_extent_start - find free space in the specified device
1324 * @device: the device which we search the free space in
1325 * @num_bytes: the size of the free space that we need
1326 * @search_start: the position from which to begin the search
1327 * @start: store the start of the free space.
1328 * @len: the size of the free space. that we find, or the size
1329 * of the max free space if we don't find suitable free space
1331 * this uses a pretty simple search, the expectation is that it is
1332 * called very infrequently and that a given device has a small number
1335 * @start is used to store the start of the free space if we find. But if we
1336 * don't find suitable free space, it will be used to store the start position
1337 * of the max free space.
1339 * @len is used to store the size of the free space that we find.
1340 * But if we don't find suitable free space, it is used to store the size of
1341 * the max free space.
1343 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1344 struct btrfs_device *device, u64 num_bytes,
1345 u64 search_start, u64 *start, u64 *len)
1347 struct btrfs_fs_info *fs_info = device->fs_info;
1348 struct btrfs_root *root = fs_info->dev_root;
1349 struct btrfs_key key;
1350 struct btrfs_dev_extent *dev_extent;
1351 struct btrfs_path *path;
1356 u64 search_end = device->total_bytes;
1359 struct extent_buffer *l;
1362 * We don't want to overwrite the superblock on the drive nor any area
1363 * used by the boot loader (grub for example), so we make sure to start
1364 * at an offset of at least 1MB.
1366 search_start = max_t(u64, search_start, SZ_1M);
1368 path = btrfs_alloc_path();
1372 max_hole_start = search_start;
1376 if (search_start >= search_end ||
1377 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1382 path->reada = READA_FORWARD;
1383 path->search_commit_root = 1;
1384 path->skip_locking = 1;
1386 key.objectid = device->devid;
1387 key.offset = search_start;
1388 key.type = BTRFS_DEV_EXTENT_KEY;
1390 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1394 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1401 slot = path->slots[0];
1402 if (slot >= btrfs_header_nritems(l)) {
1403 ret = btrfs_next_leaf(root, path);
1411 btrfs_item_key_to_cpu(l, &key, slot);
1413 if (key.objectid < device->devid)
1416 if (key.objectid > device->devid)
1419 if (key.type != BTRFS_DEV_EXTENT_KEY)
1422 if (key.offset > search_start) {
1423 hole_size = key.offset - search_start;
1426 * Have to check before we set max_hole_start, otherwise
1427 * we could end up sending back this offset anyway.
1429 if (contains_pending_extent(transaction, device,
1432 if (key.offset >= search_start) {
1433 hole_size = key.offset - search_start;
1440 if (hole_size > max_hole_size) {
1441 max_hole_start = search_start;
1442 max_hole_size = hole_size;
1446 * If this free space is greater than which we need,
1447 * it must be the max free space that we have found
1448 * until now, so max_hole_start must point to the start
1449 * of this free space and the length of this free space
1450 * is stored in max_hole_size. Thus, we return
1451 * max_hole_start and max_hole_size and go back to the
1454 if (hole_size >= num_bytes) {
1460 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1461 extent_end = key.offset + btrfs_dev_extent_length(l,
1463 if (extent_end > search_start)
1464 search_start = extent_end;
1471 * At this point, search_start should be the end of
1472 * allocated dev extents, and when shrinking the device,
1473 * search_end may be smaller than search_start.
1475 if (search_end > search_start) {
1476 hole_size = search_end - search_start;
1478 if (contains_pending_extent(transaction, device, &search_start,
1480 btrfs_release_path(path);
1484 if (hole_size > max_hole_size) {
1485 max_hole_start = search_start;
1486 max_hole_size = hole_size;
1491 if (max_hole_size < num_bytes)
1497 btrfs_free_path(path);
1498 *start = max_hole_start;
1500 *len = max_hole_size;
1504 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1505 struct btrfs_device *device, u64 num_bytes,
1506 u64 *start, u64 *len)
1508 /* FIXME use last free of some kind */
1509 return find_free_dev_extent_start(trans->transaction, device,
1510 num_bytes, 0, start, len);
1513 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1514 struct btrfs_device *device,
1515 u64 start, u64 *dev_extent_len)
1517 struct btrfs_fs_info *fs_info = device->fs_info;
1518 struct btrfs_root *root = fs_info->dev_root;
1520 struct btrfs_path *path;
1521 struct btrfs_key key;
1522 struct btrfs_key found_key;
1523 struct extent_buffer *leaf = NULL;
1524 struct btrfs_dev_extent *extent = NULL;
1526 path = btrfs_alloc_path();
1530 key.objectid = device->devid;
1532 key.type = BTRFS_DEV_EXTENT_KEY;
1534 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1536 ret = btrfs_previous_item(root, path, key.objectid,
1537 BTRFS_DEV_EXTENT_KEY);
1540 leaf = path->nodes[0];
1541 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1542 extent = btrfs_item_ptr(leaf, path->slots[0],
1543 struct btrfs_dev_extent);
1544 BUG_ON(found_key.offset > start || found_key.offset +
1545 btrfs_dev_extent_length(leaf, extent) < start);
1547 btrfs_release_path(path);
1549 } else if (ret == 0) {
1550 leaf = path->nodes[0];
1551 extent = btrfs_item_ptr(leaf, path->slots[0],
1552 struct btrfs_dev_extent);
1554 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1558 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1560 ret = btrfs_del_item(trans, root, path);
1562 btrfs_handle_fs_error(fs_info, ret,
1563 "Failed to remove dev extent item");
1565 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1568 btrfs_free_path(path);
1572 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1573 struct btrfs_device *device,
1574 u64 chunk_offset, u64 start, u64 num_bytes)
1577 struct btrfs_path *path;
1578 struct btrfs_fs_info *fs_info = device->fs_info;
1579 struct btrfs_root *root = fs_info->dev_root;
1580 struct btrfs_dev_extent *extent;
1581 struct extent_buffer *leaf;
1582 struct btrfs_key key;
1584 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1585 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1586 path = btrfs_alloc_path();
1590 key.objectid = device->devid;
1592 key.type = BTRFS_DEV_EXTENT_KEY;
1593 ret = btrfs_insert_empty_item(trans, root, path, &key,
1598 leaf = path->nodes[0];
1599 extent = btrfs_item_ptr(leaf, path->slots[0],
1600 struct btrfs_dev_extent);
1601 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1602 BTRFS_CHUNK_TREE_OBJECTID);
1603 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1604 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1605 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1607 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1608 btrfs_mark_buffer_dirty(leaf);
1610 btrfs_free_path(path);
1614 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1616 struct extent_map_tree *em_tree;
1617 struct extent_map *em;
1621 em_tree = &fs_info->mapping_tree.map_tree;
1622 read_lock(&em_tree->lock);
1623 n = rb_last(&em_tree->map.rb_root);
1625 em = rb_entry(n, struct extent_map, rb_node);
1626 ret = em->start + em->len;
1628 read_unlock(&em_tree->lock);
1633 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1637 struct btrfs_key key;
1638 struct btrfs_key found_key;
1639 struct btrfs_path *path;
1641 path = btrfs_alloc_path();
1645 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1646 key.type = BTRFS_DEV_ITEM_KEY;
1647 key.offset = (u64)-1;
1649 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1653 BUG_ON(ret == 0); /* Corruption */
1655 ret = btrfs_previous_item(fs_info->chunk_root, path,
1656 BTRFS_DEV_ITEMS_OBJECTID,
1657 BTRFS_DEV_ITEM_KEY);
1661 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1663 *devid_ret = found_key.offset + 1;
1667 btrfs_free_path(path);
1672 * the device information is stored in the chunk root
1673 * the btrfs_device struct should be fully filled in
1675 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1676 struct btrfs_device *device)
1679 struct btrfs_path *path;
1680 struct btrfs_dev_item *dev_item;
1681 struct extent_buffer *leaf;
1682 struct btrfs_key key;
1685 path = btrfs_alloc_path();
1689 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1690 key.type = BTRFS_DEV_ITEM_KEY;
1691 key.offset = device->devid;
1693 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1694 &key, sizeof(*dev_item));
1698 leaf = path->nodes[0];
1699 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1701 btrfs_set_device_id(leaf, dev_item, device->devid);
1702 btrfs_set_device_generation(leaf, dev_item, 0);
1703 btrfs_set_device_type(leaf, dev_item, device->type);
1704 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1705 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1706 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1707 btrfs_set_device_total_bytes(leaf, dev_item,
1708 btrfs_device_get_disk_total_bytes(device));
1709 btrfs_set_device_bytes_used(leaf, dev_item,
1710 btrfs_device_get_bytes_used(device));
1711 btrfs_set_device_group(leaf, dev_item, 0);
1712 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1713 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1714 btrfs_set_device_start_offset(leaf, dev_item, 0);
1716 ptr = btrfs_device_uuid(dev_item);
1717 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1718 ptr = btrfs_device_fsid(dev_item);
1719 write_extent_buffer(leaf, trans->fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1720 btrfs_mark_buffer_dirty(leaf);
1724 btrfs_free_path(path);
1729 * Function to update ctime/mtime for a given device path.
1730 * Mainly used for ctime/mtime based probe like libblkid.
1732 static void update_dev_time(const char *path_name)
1736 filp = filp_open(path_name, O_RDWR, 0);
1739 file_update_time(filp);
1740 filp_close(filp, NULL);
1743 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1744 struct btrfs_device *device)
1746 struct btrfs_root *root = fs_info->chunk_root;
1748 struct btrfs_path *path;
1749 struct btrfs_key key;
1750 struct btrfs_trans_handle *trans;
1752 path = btrfs_alloc_path();
1756 trans = btrfs_start_transaction(root, 0);
1757 if (IS_ERR(trans)) {
1758 btrfs_free_path(path);
1759 return PTR_ERR(trans);
1761 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1762 key.type = BTRFS_DEV_ITEM_KEY;
1763 key.offset = device->devid;
1765 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1769 btrfs_abort_transaction(trans, ret);
1770 btrfs_end_transaction(trans);
1774 ret = btrfs_del_item(trans, root, path);
1776 btrfs_abort_transaction(trans, ret);
1777 btrfs_end_transaction(trans);
1781 btrfs_free_path(path);
1783 ret = btrfs_commit_transaction(trans);
1788 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1789 * filesystem. It's up to the caller to adjust that number regarding eg. device
1792 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1800 seq = read_seqbegin(&fs_info->profiles_lock);
1802 all_avail = fs_info->avail_data_alloc_bits |
1803 fs_info->avail_system_alloc_bits |
1804 fs_info->avail_metadata_alloc_bits;
1805 } while (read_seqretry(&fs_info->profiles_lock, seq));
1807 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1808 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1811 if (num_devices < btrfs_raid_array[i].devs_min) {
1812 int ret = btrfs_raid_array[i].mindev_error;
1822 static struct btrfs_device * btrfs_find_next_active_device(
1823 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1825 struct btrfs_device *next_device;
1827 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1828 if (next_device != device &&
1829 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1830 && next_device->bdev)
1838 * Helper function to check if the given device is part of s_bdev / latest_bdev
1839 * and replace it with the provided or the next active device, in the context
1840 * where this function called, there should be always be another device (or
1841 * this_dev) which is active.
1843 void btrfs_assign_next_active_device(struct btrfs_device *device,
1844 struct btrfs_device *this_dev)
1846 struct btrfs_fs_info *fs_info = device->fs_info;
1847 struct btrfs_device *next_device;
1850 next_device = this_dev;
1852 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1854 ASSERT(next_device);
1856 if (fs_info->sb->s_bdev &&
1857 (fs_info->sb->s_bdev == device->bdev))
1858 fs_info->sb->s_bdev = next_device->bdev;
1860 if (fs_info->fs_devices->latest_bdev == device->bdev)
1861 fs_info->fs_devices->latest_bdev = next_device->bdev;
1865 * Return btrfs_fs_devices::num_devices excluding the device that's being
1866 * currently replaced.
1868 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1870 u64 num_devices = fs_info->fs_devices->num_devices;
1872 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1873 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1874 ASSERT(num_devices > 1);
1877 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1882 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1885 struct btrfs_device *device;
1886 struct btrfs_fs_devices *cur_devices;
1887 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1891 mutex_lock(&uuid_mutex);
1893 num_devices = btrfs_num_devices(fs_info);
1895 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1899 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
1901 if (IS_ERR(device)) {
1902 if (PTR_ERR(device) == -ENOENT &&
1903 strcmp(device_path, "missing") == 0)
1904 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1906 ret = PTR_ERR(device);
1910 if (btrfs_pinned_by_swapfile(fs_info, device)) {
1911 btrfs_warn_in_rcu(fs_info,
1912 "cannot remove device %s (devid %llu) due to active swapfile",
1913 rcu_str_deref(device->name), device->devid);
1918 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1919 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1923 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1924 fs_info->fs_devices->rw_devices == 1) {
1925 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1929 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1930 mutex_lock(&fs_info->chunk_mutex);
1931 list_del_init(&device->dev_alloc_list);
1932 device->fs_devices->rw_devices--;
1933 mutex_unlock(&fs_info->chunk_mutex);
1936 mutex_unlock(&uuid_mutex);
1937 ret = btrfs_shrink_device(device, 0);
1938 mutex_lock(&uuid_mutex);
1943 * TODO: the superblock still includes this device in its num_devices
1944 * counter although write_all_supers() is not locked out. This
1945 * could give a filesystem state which requires a degraded mount.
1947 ret = btrfs_rm_dev_item(fs_info, device);
1951 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
1952 btrfs_scrub_cancel_dev(fs_info, device);
1955 * the device list mutex makes sure that we don't change
1956 * the device list while someone else is writing out all
1957 * the device supers. Whoever is writing all supers, should
1958 * lock the device list mutex before getting the number of
1959 * devices in the super block (super_copy). Conversely,
1960 * whoever updates the number of devices in the super block
1961 * (super_copy) should hold the device list mutex.
1965 * In normal cases the cur_devices == fs_devices. But in case
1966 * of deleting a seed device, the cur_devices should point to
1967 * its own fs_devices listed under the fs_devices->seed.
1969 cur_devices = device->fs_devices;
1970 mutex_lock(&fs_devices->device_list_mutex);
1971 list_del_rcu(&device->dev_list);
1973 cur_devices->num_devices--;
1974 cur_devices->total_devices--;
1975 /* Update total_devices of the parent fs_devices if it's seed */
1976 if (cur_devices != fs_devices)
1977 fs_devices->total_devices--;
1979 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1980 cur_devices->missing_devices--;
1982 btrfs_assign_next_active_device(device, NULL);
1985 cur_devices->open_devices--;
1986 /* remove sysfs entry */
1987 btrfs_sysfs_rm_device_link(fs_devices, device);
1990 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1991 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
1992 mutex_unlock(&fs_devices->device_list_mutex);
1995 * at this point, the device is zero sized and detached from
1996 * the devices list. All that's left is to zero out the old
1997 * supers and free the device.
1999 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2000 btrfs_scratch_superblocks(device->bdev, device->name->str);
2002 btrfs_close_bdev(device);
2003 call_rcu(&device->rcu, free_device_rcu);
2005 if (cur_devices->open_devices == 0) {
2006 while (fs_devices) {
2007 if (fs_devices->seed == cur_devices) {
2008 fs_devices->seed = cur_devices->seed;
2011 fs_devices = fs_devices->seed;
2013 cur_devices->seed = NULL;
2014 close_fs_devices(cur_devices);
2015 free_fs_devices(cur_devices);
2019 mutex_unlock(&uuid_mutex);
2023 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2024 mutex_lock(&fs_info->chunk_mutex);
2025 list_add(&device->dev_alloc_list,
2026 &fs_devices->alloc_list);
2027 device->fs_devices->rw_devices++;
2028 mutex_unlock(&fs_info->chunk_mutex);
2033 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2035 struct btrfs_fs_devices *fs_devices;
2037 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2040 * in case of fs with no seed, srcdev->fs_devices will point
2041 * to fs_devices of fs_info. However when the dev being replaced is
2042 * a seed dev it will point to the seed's local fs_devices. In short
2043 * srcdev will have its correct fs_devices in both the cases.
2045 fs_devices = srcdev->fs_devices;
2047 list_del_rcu(&srcdev->dev_list);
2048 list_del(&srcdev->dev_alloc_list);
2049 fs_devices->num_devices--;
2050 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2051 fs_devices->missing_devices--;
2053 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2054 fs_devices->rw_devices--;
2057 fs_devices->open_devices--;
2060 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2061 struct btrfs_device *srcdev)
2063 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2065 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2066 /* zero out the old super if it is writable */
2067 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2070 btrfs_close_bdev(srcdev);
2071 call_rcu(&srcdev->rcu, free_device_rcu);
2073 /* if this is no devs we rather delete the fs_devices */
2074 if (!fs_devices->num_devices) {
2075 struct btrfs_fs_devices *tmp_fs_devices;
2078 * On a mounted FS, num_devices can't be zero unless it's a
2079 * seed. In case of a seed device being replaced, the replace
2080 * target added to the sprout FS, so there will be no more
2081 * device left under the seed FS.
2083 ASSERT(fs_devices->seeding);
2085 tmp_fs_devices = fs_info->fs_devices;
2086 while (tmp_fs_devices) {
2087 if (tmp_fs_devices->seed == fs_devices) {
2088 tmp_fs_devices->seed = fs_devices->seed;
2091 tmp_fs_devices = tmp_fs_devices->seed;
2093 fs_devices->seed = NULL;
2094 close_fs_devices(fs_devices);
2095 free_fs_devices(fs_devices);
2099 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2101 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2104 mutex_lock(&fs_devices->device_list_mutex);
2106 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2109 fs_devices->open_devices--;
2111 fs_devices->num_devices--;
2113 btrfs_assign_next_active_device(tgtdev, NULL);
2115 list_del_rcu(&tgtdev->dev_list);
2117 mutex_unlock(&fs_devices->device_list_mutex);
2120 * The update_dev_time() with in btrfs_scratch_superblocks()
2121 * may lead to a call to btrfs_show_devname() which will try
2122 * to hold device_list_mutex. And here this device
2123 * is already out of device list, so we don't have to hold
2124 * the device_list_mutex lock.
2126 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2128 btrfs_close_bdev(tgtdev);
2129 call_rcu(&tgtdev->rcu, free_device_rcu);
2132 static struct btrfs_device *btrfs_find_device_by_path(
2133 struct btrfs_fs_info *fs_info, const char *device_path)
2136 struct btrfs_super_block *disk_super;
2139 struct block_device *bdev;
2140 struct buffer_head *bh;
2141 struct btrfs_device *device;
2143 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2144 fs_info->bdev_holder, 0, &bdev, &bh);
2146 return ERR_PTR(ret);
2147 disk_super = (struct btrfs_super_block *)bh->b_data;
2148 devid = btrfs_stack_device_id(&disk_super->dev_item);
2149 dev_uuid = disk_super->dev_item.uuid;
2150 device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2153 device = ERR_PTR(-ENOENT);
2154 blkdev_put(bdev, FMODE_READ);
2158 static struct btrfs_device *btrfs_find_device_missing_or_by_path(
2159 struct btrfs_fs_info *fs_info, const char *device_path)
2161 struct btrfs_device *device = NULL;
2162 if (strcmp(device_path, "missing") == 0) {
2163 struct list_head *devices;
2164 struct btrfs_device *tmp;
2166 devices = &fs_info->fs_devices->devices;
2167 list_for_each_entry(tmp, devices, dev_list) {
2168 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2169 &tmp->dev_state) && !tmp->bdev) {
2176 return ERR_PTR(-ENOENT);
2178 device = btrfs_find_device_by_path(fs_info, device_path);
2185 * Lookup a device given by device id, or the path if the id is 0.
2187 struct btrfs_device *btrfs_find_device_by_devspec(
2188 struct btrfs_fs_info *fs_info, u64 devid, const char *devpath)
2190 struct btrfs_device *device;
2193 device = btrfs_find_device(fs_info, devid, NULL, NULL);
2195 return ERR_PTR(-ENOENT);
2197 if (!devpath || !devpath[0])
2198 return ERR_PTR(-EINVAL);
2199 device = btrfs_find_device_missing_or_by_path(fs_info, devpath);
2205 * does all the dirty work required for changing file system's UUID.
2207 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2209 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2210 struct btrfs_fs_devices *old_devices;
2211 struct btrfs_fs_devices *seed_devices;
2212 struct btrfs_super_block *disk_super = fs_info->super_copy;
2213 struct btrfs_device *device;
2216 lockdep_assert_held(&uuid_mutex);
2217 if (!fs_devices->seeding)
2220 seed_devices = alloc_fs_devices(NULL);
2221 if (IS_ERR(seed_devices))
2222 return PTR_ERR(seed_devices);
2224 old_devices = clone_fs_devices(fs_devices);
2225 if (IS_ERR(old_devices)) {
2226 kfree(seed_devices);
2227 return PTR_ERR(old_devices);
2230 list_add(&old_devices->fs_list, &fs_uuids);
2232 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2233 seed_devices->opened = 1;
2234 INIT_LIST_HEAD(&seed_devices->devices);
2235 INIT_LIST_HEAD(&seed_devices->alloc_list);
2236 mutex_init(&seed_devices->device_list_mutex);
2238 mutex_lock(&fs_devices->device_list_mutex);
2239 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2241 list_for_each_entry(device, &seed_devices->devices, dev_list)
2242 device->fs_devices = seed_devices;
2244 mutex_lock(&fs_info->chunk_mutex);
2245 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2246 mutex_unlock(&fs_info->chunk_mutex);
2248 fs_devices->seeding = 0;
2249 fs_devices->num_devices = 0;
2250 fs_devices->open_devices = 0;
2251 fs_devices->missing_devices = 0;
2252 fs_devices->rotating = 0;
2253 fs_devices->seed = seed_devices;
2255 generate_random_uuid(fs_devices->fsid);
2256 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2257 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2258 mutex_unlock(&fs_devices->device_list_mutex);
2260 super_flags = btrfs_super_flags(disk_super) &
2261 ~BTRFS_SUPER_FLAG_SEEDING;
2262 btrfs_set_super_flags(disk_super, super_flags);
2268 * Store the expected generation for seed devices in device items.
2270 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2271 struct btrfs_fs_info *fs_info)
2273 struct btrfs_root *root = fs_info->chunk_root;
2274 struct btrfs_path *path;
2275 struct extent_buffer *leaf;
2276 struct btrfs_dev_item *dev_item;
2277 struct btrfs_device *device;
2278 struct btrfs_key key;
2279 u8 fs_uuid[BTRFS_FSID_SIZE];
2280 u8 dev_uuid[BTRFS_UUID_SIZE];
2284 path = btrfs_alloc_path();
2288 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2290 key.type = BTRFS_DEV_ITEM_KEY;
2293 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2297 leaf = path->nodes[0];
2299 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2300 ret = btrfs_next_leaf(root, path);
2305 leaf = path->nodes[0];
2306 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2307 btrfs_release_path(path);
2311 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2312 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2313 key.type != BTRFS_DEV_ITEM_KEY)
2316 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2317 struct btrfs_dev_item);
2318 devid = btrfs_device_id(leaf, dev_item);
2319 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2321 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2323 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2324 BUG_ON(!device); /* Logic error */
2326 if (device->fs_devices->seeding) {
2327 btrfs_set_device_generation(leaf, dev_item,
2328 device->generation);
2329 btrfs_mark_buffer_dirty(leaf);
2337 btrfs_free_path(path);
2341 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2343 struct btrfs_root *root = fs_info->dev_root;
2344 struct request_queue *q;
2345 struct btrfs_trans_handle *trans;
2346 struct btrfs_device *device;
2347 struct block_device *bdev;
2348 struct super_block *sb = fs_info->sb;
2349 struct rcu_string *name;
2350 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2351 u64 orig_super_total_bytes;
2352 u64 orig_super_num_devices;
2353 int seeding_dev = 0;
2355 bool unlocked = false;
2357 if (sb_rdonly(sb) && !fs_devices->seeding)
2360 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2361 fs_info->bdev_holder);
2363 return PTR_ERR(bdev);
2365 if (fs_devices->seeding) {
2367 down_write(&sb->s_umount);
2368 mutex_lock(&uuid_mutex);
2371 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2373 mutex_lock(&fs_devices->device_list_mutex);
2374 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2375 if (device->bdev == bdev) {
2378 &fs_devices->device_list_mutex);
2382 mutex_unlock(&fs_devices->device_list_mutex);
2384 device = btrfs_alloc_device(fs_info, NULL, NULL);
2385 if (IS_ERR(device)) {
2386 /* we can safely leave the fs_devices entry around */
2387 ret = PTR_ERR(device);
2391 name = rcu_string_strdup(device_path, GFP_KERNEL);
2394 goto error_free_device;
2396 rcu_assign_pointer(device->name, name);
2398 trans = btrfs_start_transaction(root, 0);
2399 if (IS_ERR(trans)) {
2400 ret = PTR_ERR(trans);
2401 goto error_free_device;
2404 q = bdev_get_queue(bdev);
2405 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2406 device->generation = trans->transid;
2407 device->io_width = fs_info->sectorsize;
2408 device->io_align = fs_info->sectorsize;
2409 device->sector_size = fs_info->sectorsize;
2410 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2411 fs_info->sectorsize);
2412 device->disk_total_bytes = device->total_bytes;
2413 device->commit_total_bytes = device->total_bytes;
2414 device->fs_info = fs_info;
2415 device->bdev = bdev;
2416 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2417 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2418 device->mode = FMODE_EXCL;
2419 device->dev_stats_valid = 1;
2420 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2423 sb->s_flags &= ~SB_RDONLY;
2424 ret = btrfs_prepare_sprout(fs_info);
2426 btrfs_abort_transaction(trans, ret);
2431 device->fs_devices = fs_devices;
2433 mutex_lock(&fs_devices->device_list_mutex);
2434 mutex_lock(&fs_info->chunk_mutex);
2435 list_add_rcu(&device->dev_list, &fs_devices->devices);
2436 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2437 fs_devices->num_devices++;
2438 fs_devices->open_devices++;
2439 fs_devices->rw_devices++;
2440 fs_devices->total_devices++;
2441 fs_devices->total_rw_bytes += device->total_bytes;
2443 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2445 if (!blk_queue_nonrot(q))
2446 fs_devices->rotating = 1;
2448 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2449 btrfs_set_super_total_bytes(fs_info->super_copy,
2450 round_down(orig_super_total_bytes + device->total_bytes,
2451 fs_info->sectorsize));
2453 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2454 btrfs_set_super_num_devices(fs_info->super_copy,
2455 orig_super_num_devices + 1);
2457 /* add sysfs device entry */
2458 btrfs_sysfs_add_device_link(fs_devices, device);
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);
2467 mutex_unlock(&fs_devices->device_list_mutex);
2470 mutex_lock(&fs_info->chunk_mutex);
2471 ret = init_first_rw_device(trans, fs_info);
2472 mutex_unlock(&fs_info->chunk_mutex);
2474 btrfs_abort_transaction(trans, ret);
2479 ret = btrfs_add_dev_item(trans, device);
2481 btrfs_abort_transaction(trans, ret);
2486 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2488 ret = btrfs_finish_sprout(trans, fs_info);
2490 btrfs_abort_transaction(trans, ret);
2494 /* Sprouting would change fsid of the mounted root,
2495 * so rename the fsid on the sysfs
2497 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2499 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2501 "sysfs: failed to create fsid for sprout");
2504 ret = btrfs_commit_transaction(trans);
2507 mutex_unlock(&uuid_mutex);
2508 up_write(&sb->s_umount);
2511 if (ret) /* transaction commit */
2514 ret = btrfs_relocate_sys_chunks(fs_info);
2516 btrfs_handle_fs_error(fs_info, ret,
2517 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2518 trans = btrfs_attach_transaction(root);
2519 if (IS_ERR(trans)) {
2520 if (PTR_ERR(trans) == -ENOENT)
2522 ret = PTR_ERR(trans);
2526 ret = btrfs_commit_transaction(trans);
2529 /* Update ctime/mtime for libblkid */
2530 update_dev_time(device_path);
2534 btrfs_sysfs_rm_device_link(fs_devices, device);
2535 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2536 mutex_lock(&fs_info->chunk_mutex);
2537 list_del_rcu(&device->dev_list);
2538 list_del(&device->dev_alloc_list);
2539 fs_info->fs_devices->num_devices--;
2540 fs_info->fs_devices->open_devices--;
2541 fs_info->fs_devices->rw_devices--;
2542 fs_info->fs_devices->total_devices--;
2543 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2544 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2545 btrfs_set_super_total_bytes(fs_info->super_copy,
2546 orig_super_total_bytes);
2547 btrfs_set_super_num_devices(fs_info->super_copy,
2548 orig_super_num_devices);
2549 mutex_unlock(&fs_info->chunk_mutex);
2550 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2553 sb->s_flags |= SB_RDONLY;
2555 btrfs_end_transaction(trans);
2557 btrfs_free_device(device);
2559 blkdev_put(bdev, FMODE_EXCL);
2560 if (seeding_dev && !unlocked) {
2561 mutex_unlock(&uuid_mutex);
2562 up_write(&sb->s_umount);
2567 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2568 struct btrfs_device *device)
2571 struct btrfs_path *path;
2572 struct btrfs_root *root = device->fs_info->chunk_root;
2573 struct btrfs_dev_item *dev_item;
2574 struct extent_buffer *leaf;
2575 struct btrfs_key key;
2577 path = btrfs_alloc_path();
2581 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2582 key.type = BTRFS_DEV_ITEM_KEY;
2583 key.offset = device->devid;
2585 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2594 leaf = path->nodes[0];
2595 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2597 btrfs_set_device_id(leaf, dev_item, device->devid);
2598 btrfs_set_device_type(leaf, dev_item, device->type);
2599 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2600 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2601 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2602 btrfs_set_device_total_bytes(leaf, dev_item,
2603 btrfs_device_get_disk_total_bytes(device));
2604 btrfs_set_device_bytes_used(leaf, dev_item,
2605 btrfs_device_get_bytes_used(device));
2606 btrfs_mark_buffer_dirty(leaf);
2609 btrfs_free_path(path);
2613 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2614 struct btrfs_device *device, u64 new_size)
2616 struct btrfs_fs_info *fs_info = device->fs_info;
2617 struct btrfs_super_block *super_copy = fs_info->super_copy;
2618 struct btrfs_fs_devices *fs_devices;
2622 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2625 new_size = round_down(new_size, fs_info->sectorsize);
2627 mutex_lock(&fs_info->chunk_mutex);
2628 old_total = btrfs_super_total_bytes(super_copy);
2629 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2631 if (new_size <= device->total_bytes ||
2632 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2633 mutex_unlock(&fs_info->chunk_mutex);
2637 fs_devices = fs_info->fs_devices;
2639 btrfs_set_super_total_bytes(super_copy,
2640 round_down(old_total + diff, fs_info->sectorsize));
2641 device->fs_devices->total_rw_bytes += diff;
2643 btrfs_device_set_total_bytes(device, new_size);
2644 btrfs_device_set_disk_total_bytes(device, new_size);
2645 btrfs_clear_space_info_full(device->fs_info);
2646 if (list_empty(&device->resized_list))
2647 list_add_tail(&device->resized_list,
2648 &fs_devices->resized_devices);
2649 mutex_unlock(&fs_info->chunk_mutex);
2651 return btrfs_update_device(trans, device);
2654 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2656 struct btrfs_fs_info *fs_info = trans->fs_info;
2657 struct btrfs_root *root = fs_info->chunk_root;
2659 struct btrfs_path *path;
2660 struct btrfs_key key;
2662 path = btrfs_alloc_path();
2666 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2667 key.offset = chunk_offset;
2668 key.type = BTRFS_CHUNK_ITEM_KEY;
2670 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2673 else if (ret > 0) { /* Logic error or corruption */
2674 btrfs_handle_fs_error(fs_info, -ENOENT,
2675 "Failed lookup while freeing chunk.");
2680 ret = btrfs_del_item(trans, root, path);
2682 btrfs_handle_fs_error(fs_info, ret,
2683 "Failed to delete chunk item.");
2685 btrfs_free_path(path);
2689 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2691 struct btrfs_super_block *super_copy = fs_info->super_copy;
2692 struct btrfs_disk_key *disk_key;
2693 struct btrfs_chunk *chunk;
2700 struct btrfs_key key;
2702 mutex_lock(&fs_info->chunk_mutex);
2703 array_size = btrfs_super_sys_array_size(super_copy);
2705 ptr = super_copy->sys_chunk_array;
2708 while (cur < array_size) {
2709 disk_key = (struct btrfs_disk_key *)ptr;
2710 btrfs_disk_key_to_cpu(&key, disk_key);
2712 len = sizeof(*disk_key);
2714 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2715 chunk = (struct btrfs_chunk *)(ptr + len);
2716 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2717 len += btrfs_chunk_item_size(num_stripes);
2722 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2723 key.offset == chunk_offset) {
2724 memmove(ptr, ptr + len, array_size - (cur + len));
2726 btrfs_set_super_sys_array_size(super_copy, array_size);
2732 mutex_unlock(&fs_info->chunk_mutex);
2737 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2738 * @logical: Logical block offset in bytes.
2739 * @length: Length of extent in bytes.
2741 * Return: Chunk mapping or ERR_PTR.
2743 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2744 u64 logical, u64 length)
2746 struct extent_map_tree *em_tree;
2747 struct extent_map *em;
2749 em_tree = &fs_info->mapping_tree.map_tree;
2750 read_lock(&em_tree->lock);
2751 em = lookup_extent_mapping(em_tree, logical, length);
2752 read_unlock(&em_tree->lock);
2755 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2757 return ERR_PTR(-EINVAL);
2760 if (em->start > logical || em->start + em->len < logical) {
2762 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2763 logical, length, em->start, em->start + em->len);
2764 free_extent_map(em);
2765 return ERR_PTR(-EINVAL);
2768 /* callers are responsible for dropping em's ref. */
2772 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2774 struct btrfs_fs_info *fs_info = trans->fs_info;
2775 struct extent_map *em;
2776 struct map_lookup *map;
2777 u64 dev_extent_len = 0;
2779 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2781 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2784 * This is a logic error, but we don't want to just rely on the
2785 * user having built with ASSERT enabled, so if ASSERT doesn't
2786 * do anything we still error out.
2791 map = em->map_lookup;
2792 mutex_lock(&fs_info->chunk_mutex);
2793 check_system_chunk(trans, map->type);
2794 mutex_unlock(&fs_info->chunk_mutex);
2797 * Take the device list mutex to prevent races with the final phase of
2798 * a device replace operation that replaces the device object associated
2799 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2801 mutex_lock(&fs_devices->device_list_mutex);
2802 for (i = 0; i < map->num_stripes; i++) {
2803 struct btrfs_device *device = map->stripes[i].dev;
2804 ret = btrfs_free_dev_extent(trans, device,
2805 map->stripes[i].physical,
2808 mutex_unlock(&fs_devices->device_list_mutex);
2809 btrfs_abort_transaction(trans, ret);
2813 if (device->bytes_used > 0) {
2814 mutex_lock(&fs_info->chunk_mutex);
2815 btrfs_device_set_bytes_used(device,
2816 device->bytes_used - dev_extent_len);
2817 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2818 btrfs_clear_space_info_full(fs_info);
2819 mutex_unlock(&fs_info->chunk_mutex);
2822 if (map->stripes[i].dev) {
2823 ret = btrfs_update_device(trans, map->stripes[i].dev);
2825 mutex_unlock(&fs_devices->device_list_mutex);
2826 btrfs_abort_transaction(trans, ret);
2831 mutex_unlock(&fs_devices->device_list_mutex);
2833 ret = btrfs_free_chunk(trans, chunk_offset);
2835 btrfs_abort_transaction(trans, ret);
2839 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2841 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2842 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2844 btrfs_abort_transaction(trans, ret);
2849 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2851 btrfs_abort_transaction(trans, ret);
2857 free_extent_map(em);
2861 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2863 struct btrfs_root *root = fs_info->chunk_root;
2864 struct btrfs_trans_handle *trans;
2868 * Prevent races with automatic removal of unused block groups.
2869 * After we relocate and before we remove the chunk with offset
2870 * chunk_offset, automatic removal of the block group can kick in,
2871 * resulting in a failure when calling btrfs_remove_chunk() below.
2873 * Make sure to acquire this mutex before doing a tree search (dev
2874 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2875 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2876 * we release the path used to search the chunk/dev tree and before
2877 * the current task acquires this mutex and calls us.
2879 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2881 ret = btrfs_can_relocate(fs_info, chunk_offset);
2885 /* step one, relocate all the extents inside this chunk */
2886 btrfs_scrub_pause(fs_info);
2887 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2888 btrfs_scrub_continue(fs_info);
2893 * We add the kobjects here (and after forcing data chunk creation)
2894 * since relocation is the only place we'll create chunks of a new
2895 * type at runtime. The only place where we'll remove the last
2896 * chunk of a type is the call immediately below this one. Even
2897 * so, we're protected against races with the cleaner thread since
2898 * we're covered by the delete_unused_bgs_mutex.
2900 btrfs_add_raid_kobjects(fs_info);
2902 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2904 if (IS_ERR(trans)) {
2905 ret = PTR_ERR(trans);
2906 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2911 * step two, delete the device extents and the
2912 * chunk tree entries
2914 ret = btrfs_remove_chunk(trans, chunk_offset);
2915 btrfs_end_transaction(trans);
2919 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2921 struct btrfs_root *chunk_root = fs_info->chunk_root;
2922 struct btrfs_path *path;
2923 struct extent_buffer *leaf;
2924 struct btrfs_chunk *chunk;
2925 struct btrfs_key key;
2926 struct btrfs_key found_key;
2928 bool retried = false;
2932 path = btrfs_alloc_path();
2937 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2938 key.offset = (u64)-1;
2939 key.type = BTRFS_CHUNK_ITEM_KEY;
2942 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2943 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2945 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2948 BUG_ON(ret == 0); /* Corruption */
2950 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2953 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2959 leaf = path->nodes[0];
2960 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2962 chunk = btrfs_item_ptr(leaf, path->slots[0],
2963 struct btrfs_chunk);
2964 chunk_type = btrfs_chunk_type(leaf, chunk);
2965 btrfs_release_path(path);
2967 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2968 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
2974 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2976 if (found_key.offset == 0)
2978 key.offset = found_key.offset - 1;
2981 if (failed && !retried) {
2985 } else if (WARN_ON(failed && retried)) {
2989 btrfs_free_path(path);
2994 * return 1 : allocate a data chunk successfully,
2995 * return <0: errors during allocating a data chunk,
2996 * return 0 : no need to allocate a data chunk.
2998 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3001 struct btrfs_block_group_cache *cache;
3005 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3007 chunk_type = cache->flags;
3008 btrfs_put_block_group(cache);
3010 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3011 spin_lock(&fs_info->data_sinfo->lock);
3012 bytes_used = fs_info->data_sinfo->bytes_used;
3013 spin_unlock(&fs_info->data_sinfo->lock);
3016 struct btrfs_trans_handle *trans;
3019 trans = btrfs_join_transaction(fs_info->tree_root);
3021 return PTR_ERR(trans);
3023 ret = btrfs_force_chunk_alloc(trans,
3024 BTRFS_BLOCK_GROUP_DATA);
3025 btrfs_end_transaction(trans);
3029 btrfs_add_raid_kobjects(fs_info);
3037 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3038 struct btrfs_balance_control *bctl)
3040 struct btrfs_root *root = fs_info->tree_root;
3041 struct btrfs_trans_handle *trans;
3042 struct btrfs_balance_item *item;
3043 struct btrfs_disk_balance_args disk_bargs;
3044 struct btrfs_path *path;
3045 struct extent_buffer *leaf;
3046 struct btrfs_key key;
3049 path = btrfs_alloc_path();
3053 trans = btrfs_start_transaction(root, 0);
3054 if (IS_ERR(trans)) {
3055 btrfs_free_path(path);
3056 return PTR_ERR(trans);
3059 key.objectid = BTRFS_BALANCE_OBJECTID;
3060 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3063 ret = btrfs_insert_empty_item(trans, root, path, &key,
3068 leaf = path->nodes[0];
3069 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3071 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3073 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3074 btrfs_set_balance_data(leaf, item, &disk_bargs);
3075 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3076 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3077 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3078 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3080 btrfs_set_balance_flags(leaf, item, bctl->flags);
3082 btrfs_mark_buffer_dirty(leaf);
3084 btrfs_free_path(path);
3085 err = btrfs_commit_transaction(trans);
3091 static int del_balance_item(struct btrfs_fs_info *fs_info)
3093 struct btrfs_root *root = fs_info->tree_root;
3094 struct btrfs_trans_handle *trans;
3095 struct btrfs_path *path;
3096 struct btrfs_key key;
3099 path = btrfs_alloc_path();
3103 trans = btrfs_start_transaction(root, 0);
3104 if (IS_ERR(trans)) {
3105 btrfs_free_path(path);
3106 return PTR_ERR(trans);
3109 key.objectid = BTRFS_BALANCE_OBJECTID;
3110 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3113 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3121 ret = btrfs_del_item(trans, root, path);
3123 btrfs_free_path(path);
3124 err = btrfs_commit_transaction(trans);
3131 * This is a heuristic used to reduce the number of chunks balanced on
3132 * resume after balance was interrupted.
3134 static void update_balance_args(struct btrfs_balance_control *bctl)
3137 * Turn on soft mode for chunk types that were being converted.
3139 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3140 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3141 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3142 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3143 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3144 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3147 * Turn on usage filter if is not already used. The idea is
3148 * that chunks that we have already balanced should be
3149 * reasonably full. Don't do it for chunks that are being
3150 * converted - that will keep us from relocating unconverted
3151 * (albeit full) chunks.
3153 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3154 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3155 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3156 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3157 bctl->data.usage = 90;
3159 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3160 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3161 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3162 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3163 bctl->sys.usage = 90;
3165 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3166 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3167 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3168 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3169 bctl->meta.usage = 90;
3174 * Clear the balance status in fs_info and delete the balance item from disk.
3176 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3178 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3181 BUG_ON(!fs_info->balance_ctl);
3183 spin_lock(&fs_info->balance_lock);
3184 fs_info->balance_ctl = NULL;
3185 spin_unlock(&fs_info->balance_lock);
3188 ret = del_balance_item(fs_info);
3190 btrfs_handle_fs_error(fs_info, ret, NULL);
3194 * Balance filters. Return 1 if chunk should be filtered out
3195 * (should not be balanced).
3197 static int chunk_profiles_filter(u64 chunk_type,
3198 struct btrfs_balance_args *bargs)
3200 chunk_type = chunk_to_extended(chunk_type) &
3201 BTRFS_EXTENDED_PROFILE_MASK;
3203 if (bargs->profiles & chunk_type)
3209 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3210 struct btrfs_balance_args *bargs)
3212 struct btrfs_block_group_cache *cache;
3214 u64 user_thresh_min;
3215 u64 user_thresh_max;
3218 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3219 chunk_used = btrfs_block_group_used(&cache->item);
3221 if (bargs->usage_min == 0)
3222 user_thresh_min = 0;
3224 user_thresh_min = div_factor_fine(cache->key.offset,
3227 if (bargs->usage_max == 0)
3228 user_thresh_max = 1;
3229 else if (bargs->usage_max > 100)
3230 user_thresh_max = cache->key.offset;
3232 user_thresh_max = div_factor_fine(cache->key.offset,
3235 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3238 btrfs_put_block_group(cache);
3242 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3243 u64 chunk_offset, struct btrfs_balance_args *bargs)
3245 struct btrfs_block_group_cache *cache;
3246 u64 chunk_used, user_thresh;
3249 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3250 chunk_used = btrfs_block_group_used(&cache->item);