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/iocontext.h>
12 #include <linux/capability.h>
13 #include <linux/ratelimit.h>
14 #include <linux/kthread.h>
15 #include <linux/raid/pq.h>
16 #include <linux/semaphore.h>
17 #include <linux/uuid.h>
18 #include <linux/list_sort.h>
19 #include <asm/div64.h>
21 #include "extent_map.h"
23 #include "transaction.h"
24 #include "print-tree.h"
27 #include "async-thread.h"
28 #include "check-integrity.h"
29 #include "rcu-string.h"
31 #include "dev-replace.h"
34 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
35 [BTRFS_RAID_RAID10] = {
38 .devs_max = 0, /* 0 == as many as possible */
40 .tolerated_failures = 1,
44 [BTRFS_RAID_RAID1] = {
49 .tolerated_failures = 1,
58 .tolerated_failures = 0,
62 [BTRFS_RAID_RAID0] = {
67 .tolerated_failures = 0,
71 [BTRFS_RAID_SINGLE] = {
76 .tolerated_failures = 0,
80 [BTRFS_RAID_RAID5] = {
85 .tolerated_failures = 1,
89 [BTRFS_RAID_RAID6] = {
94 .tolerated_failures = 2,
100 const u64 btrfs_raid_group[BTRFS_NR_RAID_TYPES] = {
101 [BTRFS_RAID_RAID10] = BTRFS_BLOCK_GROUP_RAID10,
102 [BTRFS_RAID_RAID1] = BTRFS_BLOCK_GROUP_RAID1,
103 [BTRFS_RAID_DUP] = BTRFS_BLOCK_GROUP_DUP,
104 [BTRFS_RAID_RAID0] = BTRFS_BLOCK_GROUP_RAID0,
105 [BTRFS_RAID_SINGLE] = 0,
106 [BTRFS_RAID_RAID5] = BTRFS_BLOCK_GROUP_RAID5,
107 [BTRFS_RAID_RAID6] = BTRFS_BLOCK_GROUP_RAID6,
111 * Table to convert BTRFS_RAID_* to the error code if minimum number of devices
112 * condition is not met. Zero means there's no corresponding
113 * BTRFS_ERROR_DEV_*_NOT_MET value.
115 const int btrfs_raid_mindev_error[BTRFS_NR_RAID_TYPES] = {
116 [BTRFS_RAID_RAID10] = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
117 [BTRFS_RAID_RAID1] = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
118 [BTRFS_RAID_DUP] = 0,
119 [BTRFS_RAID_RAID0] = 0,
120 [BTRFS_RAID_SINGLE] = 0,
121 [BTRFS_RAID_RAID5] = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
122 [BTRFS_RAID_RAID6] = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
125 static int init_first_rw_device(struct btrfs_trans_handle *trans,
126 struct btrfs_fs_info *fs_info);
127 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
128 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
129 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
130 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
131 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
132 enum btrfs_map_op op,
133 u64 logical, u64 *length,
134 struct btrfs_bio **bbio_ret,
135 int mirror_num, int need_raid_map);
141 * There are several mutexes that protect manipulation of devices and low-level
142 * structures like chunks but not block groups, extents or files
144 * uuid_mutex (global lock)
145 * ------------------------
146 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
147 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
148 * device) or requested by the device= mount option
150 * the mutex can be very coarse and can cover long-running operations
152 * protects: updates to fs_devices counters like missing devices, rw devices,
153 * seeding, structure cloning, openning/closing devices at mount/umount time
155 * global::fs_devs - add, remove, updates to the global list
157 * does not protect: manipulation of the fs_devices::devices list!
159 * btrfs_device::name - renames (write side), read is RCU
161 * fs_devices::device_list_mutex (per-fs, with RCU)
162 * ------------------------------------------------
163 * protects updates to fs_devices::devices, ie. adding and deleting
165 * simple list traversal with read-only actions can be done with RCU protection
167 * may be used to exclude some operations from running concurrently without any
168 * modifications to the list (see write_all_supers)
172 * coarse lock owned by a mounted filesystem; used to exclude some operations
173 * that cannot run in parallel and affect the higher-level properties of the
174 * filesystem like: device add/deleting/resize/replace, or balance
178 * protects balance structures (status, state) and context accessed from
179 * several places (internally, ioctl)
183 * protects chunks, adding or removing during allocation, trim or when a new
184 * device is added/removed
188 * a big lock that is held by the cleaner thread and prevents running subvolume
189 * cleaning together with relocation or delayed iputs
202 * Exclusive operations, BTRFS_FS_EXCL_OP
203 * ======================================
205 * Maintains the exclusivity of the following operations that apply to the
206 * whole filesystem and cannot run in parallel.
211 * - Device replace (*)
214 * The device operations (as above) can be in one of the following states:
220 * Only device operations marked with (*) can go into the Paused state for the
223 * - ioctl (only Balance can be Paused through ioctl)
224 * - filesystem remounted as read-only
225 * - filesystem unmounted and mounted as read-only
226 * - system power-cycle and filesystem mounted as read-only
227 * - filesystem or device errors leading to forced read-only
229 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
230 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
231 * A device operation in Paused or Running state can be canceled or resumed
232 * either by ioctl (Balance only) or when remounted as read-write.
233 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
237 DEFINE_MUTEX(uuid_mutex);
238 static LIST_HEAD(fs_uuids);
239 struct list_head *btrfs_get_fs_uuids(void)
245 * alloc_fs_devices - allocate struct btrfs_fs_devices
246 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
248 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
249 * The returned struct is not linked onto any lists and can be destroyed with
250 * kfree() right away.
252 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
254 struct btrfs_fs_devices *fs_devs;
256 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
258 return ERR_PTR(-ENOMEM);
260 mutex_init(&fs_devs->device_list_mutex);
262 INIT_LIST_HEAD(&fs_devs->devices);
263 INIT_LIST_HEAD(&fs_devs->resized_devices);
264 INIT_LIST_HEAD(&fs_devs->alloc_list);
265 INIT_LIST_HEAD(&fs_devs->fs_list);
267 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
272 static void free_device(struct btrfs_device *device)
274 rcu_string_free(device->name);
275 bio_put(device->flush_bio);
279 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
281 struct btrfs_device *device;
282 WARN_ON(fs_devices->opened);
283 while (!list_empty(&fs_devices->devices)) {
284 device = list_entry(fs_devices->devices.next,
285 struct btrfs_device, dev_list);
286 list_del(&device->dev_list);
292 static void btrfs_kobject_uevent(struct block_device *bdev,
293 enum kobject_action action)
297 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
299 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
301 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
302 &disk_to_dev(bdev->bd_disk)->kobj);
305 void __exit btrfs_cleanup_fs_uuids(void)
307 struct btrfs_fs_devices *fs_devices;
309 while (!list_empty(&fs_uuids)) {
310 fs_devices = list_entry(fs_uuids.next,
311 struct btrfs_fs_devices, fs_list);
312 list_del(&fs_devices->fs_list);
313 free_fs_devices(fs_devices);
318 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
319 * Returned struct is not linked onto any lists and must be destroyed using
322 static struct btrfs_device *__alloc_device(void)
324 struct btrfs_device *dev;
326 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
328 return ERR_PTR(-ENOMEM);
331 * Preallocate a bio that's always going to be used for flushing device
332 * barriers and matches the device lifespan
334 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
335 if (!dev->flush_bio) {
337 return ERR_PTR(-ENOMEM);
340 INIT_LIST_HEAD(&dev->dev_list);
341 INIT_LIST_HEAD(&dev->dev_alloc_list);
342 INIT_LIST_HEAD(&dev->resized_list);
344 spin_lock_init(&dev->io_lock);
346 atomic_set(&dev->reada_in_flight, 0);
347 atomic_set(&dev->dev_stats_ccnt, 0);
348 btrfs_device_data_ordered_init(dev);
349 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
350 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
356 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
359 * If devid and uuid are both specified, the match must be exact, otherwise
360 * only devid is used.
362 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
363 u64 devid, const u8 *uuid)
365 struct btrfs_device *dev;
367 list_for_each_entry(dev, &fs_devices->devices, dev_list) {
368 if (dev->devid == devid &&
369 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
376 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
378 struct btrfs_fs_devices *fs_devices;
380 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
381 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
388 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
389 int flush, struct block_device **bdev,
390 struct buffer_head **bh)
394 *bdev = blkdev_get_by_path(device_path, flags, holder);
397 ret = PTR_ERR(*bdev);
402 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
403 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
405 blkdev_put(*bdev, flags);
408 invalidate_bdev(*bdev);
409 *bh = btrfs_read_dev_super(*bdev);
412 blkdev_put(*bdev, flags);
424 static void requeue_list(struct btrfs_pending_bios *pending_bios,
425 struct bio *head, struct bio *tail)
428 struct bio *old_head;
430 old_head = pending_bios->head;
431 pending_bios->head = head;
432 if (pending_bios->tail)
433 tail->bi_next = old_head;
435 pending_bios->tail = tail;
439 * we try to collect pending bios for a device so we don't get a large
440 * number of procs sending bios down to the same device. This greatly
441 * improves the schedulers ability to collect and merge the bios.
443 * But, it also turns into a long list of bios to process and that is sure
444 * to eventually make the worker thread block. The solution here is to
445 * make some progress and then put this work struct back at the end of
446 * the list if the block device is congested. This way, multiple devices
447 * can make progress from a single worker thread.
449 static noinline void run_scheduled_bios(struct btrfs_device *device)
451 struct btrfs_fs_info *fs_info = device->fs_info;
453 struct backing_dev_info *bdi;
454 struct btrfs_pending_bios *pending_bios;
458 unsigned long num_run;
459 unsigned long batch_run = 0;
460 unsigned long last_waited = 0;
462 int sync_pending = 0;
463 struct blk_plug plug;
466 * this function runs all the bios we've collected for
467 * a particular device. We don't want to wander off to
468 * another device without first sending all of these down.
469 * So, setup a plug here and finish it off before we return
471 blk_start_plug(&plug);
473 bdi = device->bdev->bd_bdi;
476 spin_lock(&device->io_lock);
481 /* take all the bios off the list at once and process them
482 * later on (without the lock held). But, remember the
483 * tail and other pointers so the bios can be properly reinserted
484 * into the list if we hit congestion
486 if (!force_reg && device->pending_sync_bios.head) {
487 pending_bios = &device->pending_sync_bios;
490 pending_bios = &device->pending_bios;
494 pending = pending_bios->head;
495 tail = pending_bios->tail;
496 WARN_ON(pending && !tail);
499 * if pending was null this time around, no bios need processing
500 * at all and we can stop. Otherwise it'll loop back up again
501 * and do an additional check so no bios are missed.
503 * device->running_pending is used to synchronize with the
506 if (device->pending_sync_bios.head == NULL &&
507 device->pending_bios.head == NULL) {
509 device->running_pending = 0;
512 device->running_pending = 1;
515 pending_bios->head = NULL;
516 pending_bios->tail = NULL;
518 spin_unlock(&device->io_lock);
523 /* we want to work on both lists, but do more bios on the
524 * sync list than the regular list
527 pending_bios != &device->pending_sync_bios &&
528 device->pending_sync_bios.head) ||
529 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
530 device->pending_bios.head)) {
531 spin_lock(&device->io_lock);
532 requeue_list(pending_bios, pending, tail);
537 pending = pending->bi_next;
540 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
543 * if we're doing the sync list, record that our
544 * plug has some sync requests on it
546 * If we're doing the regular list and there are
547 * sync requests sitting around, unplug before
550 if (pending_bios == &device->pending_sync_bios) {
552 } else if (sync_pending) {
553 blk_finish_plug(&plug);
554 blk_start_plug(&plug);
558 btrfsic_submit_bio(cur);
565 * we made progress, there is more work to do and the bdi
566 * is now congested. Back off and let other work structs
569 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
570 fs_info->fs_devices->open_devices > 1) {
571 struct io_context *ioc;
573 ioc = current->io_context;
576 * the main goal here is that we don't want to
577 * block if we're going to be able to submit
578 * more requests without blocking.
580 * This code does two great things, it pokes into
581 * the elevator code from a filesystem _and_
582 * it makes assumptions about how batching works.
584 if (ioc && ioc->nr_batch_requests > 0 &&
585 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
587 ioc->last_waited == last_waited)) {
589 * we want to go through our batch of
590 * requests and stop. So, we copy out
591 * the ioc->last_waited time and test
592 * against it before looping
594 last_waited = ioc->last_waited;
598 spin_lock(&device->io_lock);
599 requeue_list(pending_bios, pending, tail);
600 device->running_pending = 1;
602 spin_unlock(&device->io_lock);
603 btrfs_queue_work(fs_info->submit_workers,
613 spin_lock(&device->io_lock);
614 if (device->pending_bios.head || device->pending_sync_bios.head)
616 spin_unlock(&device->io_lock);
619 blk_finish_plug(&plug);
622 static void pending_bios_fn(struct btrfs_work *work)
624 struct btrfs_device *device;
626 device = container_of(work, struct btrfs_device, work);
627 run_scheduled_bios(device);
631 * Search and remove all stale (devices which are not mounted) devices.
632 * When both inputs are NULL, it will search and release all stale devices.
633 * path: Optional. When provided will it release all unmounted devices
634 * matching this path only.
635 * skip_dev: Optional. Will skip this device when searching for the stale
638 static void btrfs_free_stale_devices(const char *path,
639 struct btrfs_device *skip_dev)
641 struct btrfs_fs_devices *fs_devs, *tmp_fs_devs;
642 struct btrfs_device *dev, *tmp_dev;
644 list_for_each_entry_safe(fs_devs, tmp_fs_devs, &fs_uuids, fs_list) {
649 list_for_each_entry_safe(dev, tmp_dev,
650 &fs_devs->devices, dev_list) {
653 if (skip_dev && skip_dev == dev)
655 if (path && !dev->name)
660 not_found = strcmp(rcu_str_deref(dev->name),
666 /* delete the stale device */
667 if (fs_devs->num_devices == 1) {
668 btrfs_sysfs_remove_fsid(fs_devs);
669 list_del(&fs_devs->fs_list);
670 free_fs_devices(fs_devs);
673 fs_devs->num_devices--;
674 list_del(&dev->dev_list);
681 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
682 struct btrfs_device *device, fmode_t flags,
685 struct request_queue *q;
686 struct block_device *bdev;
687 struct buffer_head *bh;
688 struct btrfs_super_block *disk_super;
697 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
702 disk_super = (struct btrfs_super_block *)bh->b_data;
703 devid = btrfs_stack_device_id(&disk_super->dev_item);
704 if (devid != device->devid)
707 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
710 device->generation = btrfs_super_generation(disk_super);
712 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
713 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
714 fs_devices->seeding = 1;
716 if (bdev_read_only(bdev))
717 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
719 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
722 q = bdev_get_queue(bdev);
723 if (!blk_queue_nonrot(q))
724 fs_devices->rotating = 1;
727 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
728 device->mode = flags;
730 fs_devices->open_devices++;
731 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
732 device->devid != BTRFS_DEV_REPLACE_DEVID) {
733 fs_devices->rw_devices++;
734 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
742 blkdev_put(bdev, flags);
748 * Add new device to list of registered devices
751 * device pointer which was just added or updated when successful
752 * error pointer when failed
754 static noinline struct btrfs_device *device_list_add(const char *path,
755 struct btrfs_super_block *disk_super)
757 struct btrfs_device *device;
758 struct btrfs_fs_devices *fs_devices;
759 struct rcu_string *name;
760 u64 found_transid = btrfs_super_generation(disk_super);
761 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
763 fs_devices = find_fsid(disk_super->fsid);
765 fs_devices = alloc_fs_devices(disk_super->fsid);
766 if (IS_ERR(fs_devices))
767 return ERR_CAST(fs_devices);
769 list_add(&fs_devices->fs_list, &fs_uuids);
773 device = find_device(fs_devices, devid,
774 disk_super->dev_item.uuid);
778 if (fs_devices->opened)
779 return ERR_PTR(-EBUSY);
781 device = btrfs_alloc_device(NULL, &devid,
782 disk_super->dev_item.uuid);
783 if (IS_ERR(device)) {
784 /* we can safely leave the fs_devices entry around */
788 name = rcu_string_strdup(path, GFP_NOFS);
791 return ERR_PTR(-ENOMEM);
793 rcu_assign_pointer(device->name, name);
795 mutex_lock(&fs_devices->device_list_mutex);
796 list_add_rcu(&device->dev_list, &fs_devices->devices);
797 fs_devices->num_devices++;
798 mutex_unlock(&fs_devices->device_list_mutex);
800 device->fs_devices = fs_devices;
801 btrfs_free_stale_devices(path, device);
803 if (disk_super->label[0])
804 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
805 disk_super->label, devid, found_transid, path);
807 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
808 disk_super->fsid, devid, found_transid, path);
810 } else if (!device->name || strcmp(device->name->str, path)) {
812 * When FS is already mounted.
813 * 1. If you are here and if the device->name is NULL that
814 * means this device was missing at time of FS mount.
815 * 2. If you are here and if the device->name is different
816 * from 'path' that means either
817 * a. The same device disappeared and reappeared with
819 * b. The missing-disk-which-was-replaced, has
822 * We must allow 1 and 2a above. But 2b would be a spurious
825 * Further in case of 1 and 2a above, the disk at 'path'
826 * would have missed some transaction when it was away and
827 * in case of 2a the stale bdev has to be updated as well.
828 * 2b must not be allowed at all time.
832 * For now, we do allow update to btrfs_fs_device through the
833 * btrfs dev scan cli after FS has been mounted. We're still
834 * tracking a problem where systems fail mount by subvolume id
835 * when we reject replacement on a mounted FS.
837 if (!fs_devices->opened && found_transid < device->generation) {
839 * That is if the FS is _not_ mounted and if you
840 * are here, that means there is more than one
841 * disk with same uuid and devid.We keep the one
842 * with larger generation number or the last-in if
843 * generation are equal.
845 return ERR_PTR(-EEXIST);
848 name = rcu_string_strdup(path, GFP_NOFS);
850 return ERR_PTR(-ENOMEM);
851 rcu_string_free(device->name);
852 rcu_assign_pointer(device->name, name);
853 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
854 fs_devices->missing_devices--;
855 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
860 * Unmount does not free the btrfs_device struct but would zero
861 * generation along with most of the other members. So just update
862 * it back. We need it to pick the disk with largest generation
865 if (!fs_devices->opened)
866 device->generation = found_transid;
868 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
873 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
875 struct btrfs_fs_devices *fs_devices;
876 struct btrfs_device *device;
877 struct btrfs_device *orig_dev;
879 fs_devices = alloc_fs_devices(orig->fsid);
880 if (IS_ERR(fs_devices))
883 mutex_lock(&orig->device_list_mutex);
884 fs_devices->total_devices = orig->total_devices;
886 /* We have held the volume lock, it is safe to get the devices. */
887 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
888 struct rcu_string *name;
890 device = btrfs_alloc_device(NULL, &orig_dev->devid,
896 * This is ok to do without rcu read locked because we hold the
897 * uuid mutex so nothing we touch in here is going to disappear.
899 if (orig_dev->name) {
900 name = rcu_string_strdup(orig_dev->name->str,
906 rcu_assign_pointer(device->name, name);
909 list_add(&device->dev_list, &fs_devices->devices);
910 device->fs_devices = fs_devices;
911 fs_devices->num_devices++;
913 mutex_unlock(&orig->device_list_mutex);
916 mutex_unlock(&orig->device_list_mutex);
917 free_fs_devices(fs_devices);
918 return ERR_PTR(-ENOMEM);
922 * After we have read the system tree and know devids belonging to
923 * this filesystem, remove the device which does not belong there.
925 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
927 struct btrfs_device *device, *next;
928 struct btrfs_device *latest_dev = NULL;
930 mutex_lock(&uuid_mutex);
932 /* This is the initialized path, it is safe to release the devices. */
933 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
934 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
935 &device->dev_state)) {
936 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
937 &device->dev_state) &&
939 device->generation > latest_dev->generation)) {
945 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
947 * In the first step, keep the device which has
948 * the correct fsid and the devid that is used
949 * for the dev_replace procedure.
950 * In the second step, the dev_replace state is
951 * read from the device tree and it is known
952 * whether the procedure is really active or
953 * not, which means whether this device is
954 * used or whether it should be removed.
956 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
957 &device->dev_state)) {
962 blkdev_put(device->bdev, device->mode);
964 fs_devices->open_devices--;
966 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
967 list_del_init(&device->dev_alloc_list);
968 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
969 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
971 fs_devices->rw_devices--;
973 list_del_init(&device->dev_list);
974 fs_devices->num_devices--;
978 if (fs_devices->seed) {
979 fs_devices = fs_devices->seed;
983 fs_devices->latest_bdev = latest_dev->bdev;
985 mutex_unlock(&uuid_mutex);
988 static void free_device_rcu(struct rcu_head *head)
990 struct btrfs_device *device;
992 device = container_of(head, struct btrfs_device, rcu);
996 static void btrfs_close_bdev(struct btrfs_device *device)
1001 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1002 sync_blockdev(device->bdev);
1003 invalidate_bdev(device->bdev);
1006 blkdev_put(device->bdev, device->mode);
1009 static void btrfs_prepare_close_one_device(struct btrfs_device *device)
1011 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1012 struct btrfs_device *new_device;
1013 struct rcu_string *name;
1016 fs_devices->open_devices--;
1018 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1019 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1020 list_del_init(&device->dev_alloc_list);
1021 fs_devices->rw_devices--;
1024 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1025 fs_devices->missing_devices--;
1027 new_device = btrfs_alloc_device(NULL, &device->devid,
1029 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1031 /* Safe because we are under uuid_mutex */
1033 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1034 BUG_ON(!name); /* -ENOMEM */
1035 rcu_assign_pointer(new_device->name, name);
1038 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1039 new_device->fs_devices = device->fs_devices;
1042 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1044 struct btrfs_device *device, *tmp;
1045 struct list_head pending_put;
1047 INIT_LIST_HEAD(&pending_put);
1049 if (--fs_devices->opened > 0)
1052 mutex_lock(&fs_devices->device_list_mutex);
1053 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1054 btrfs_prepare_close_one_device(device);
1055 list_add(&device->dev_list, &pending_put);
1057 mutex_unlock(&fs_devices->device_list_mutex);
1060 * btrfs_show_devname() is using the device_list_mutex,
1061 * sometimes call to blkdev_put() leads vfs calling
1062 * into this func. So do put outside of device_list_mutex,
1065 while (!list_empty(&pending_put)) {
1066 device = list_first_entry(&pending_put,
1067 struct btrfs_device, dev_list);
1068 list_del(&device->dev_list);
1069 btrfs_close_bdev(device);
1070 call_rcu(&device->rcu, free_device_rcu);
1073 WARN_ON(fs_devices->open_devices);
1074 WARN_ON(fs_devices->rw_devices);
1075 fs_devices->opened = 0;
1076 fs_devices->seeding = 0;
1081 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1083 struct btrfs_fs_devices *seed_devices = NULL;
1086 mutex_lock(&uuid_mutex);
1087 ret = close_fs_devices(fs_devices);
1088 if (!fs_devices->opened) {
1089 seed_devices = fs_devices->seed;
1090 fs_devices->seed = NULL;
1092 mutex_unlock(&uuid_mutex);
1094 while (seed_devices) {
1095 fs_devices = seed_devices;
1096 seed_devices = fs_devices->seed;
1097 close_fs_devices(fs_devices);
1098 free_fs_devices(fs_devices);
1103 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1104 fmode_t flags, void *holder)
1106 struct btrfs_device *device;
1107 struct btrfs_device *latest_dev = NULL;
1110 flags |= FMODE_EXCL;
1112 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1113 /* Just open everything we can; ignore failures here */
1114 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1118 device->generation > latest_dev->generation)
1119 latest_dev = device;
1121 if (fs_devices->open_devices == 0) {
1125 fs_devices->opened = 1;
1126 fs_devices->latest_bdev = latest_dev->bdev;
1127 fs_devices->total_rw_bytes = 0;
1132 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1134 struct btrfs_device *dev1, *dev2;
1136 dev1 = list_entry(a, struct btrfs_device, dev_list);
1137 dev2 = list_entry(b, struct btrfs_device, dev_list);
1139 if (dev1->devid < dev2->devid)
1141 else if (dev1->devid > dev2->devid)
1146 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1147 fmode_t flags, void *holder)
1151 mutex_lock(&uuid_mutex);
1152 if (fs_devices->opened) {
1153 fs_devices->opened++;
1156 list_sort(NULL, &fs_devices->devices, devid_cmp);
1157 ret = open_fs_devices(fs_devices, flags, holder);
1159 mutex_unlock(&uuid_mutex);
1163 static void btrfs_release_disk_super(struct page *page)
1169 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1171 struct btrfs_super_block **disk_super)
1176 /* make sure our super fits in the device */
1177 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1180 /* make sure our super fits in the page */
1181 if (sizeof(**disk_super) > PAGE_SIZE)
1184 /* make sure our super doesn't straddle pages on disk */
1185 index = bytenr >> PAGE_SHIFT;
1186 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1189 /* pull in the page with our super */
1190 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1193 if (IS_ERR_OR_NULL(*page))
1198 /* align our pointer to the offset of the super block */
1199 *disk_super = p + (bytenr & ~PAGE_MASK);
1201 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1202 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1203 btrfs_release_disk_super(*page);
1207 if ((*disk_super)->label[0] &&
1208 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1209 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1215 * Look for a btrfs signature on a device. This may be called out of the mount path
1216 * and we are not allowed to call set_blocksize during the scan. The superblock
1217 * is read via pagecache
1219 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1220 struct btrfs_fs_devices **fs_devices_ret)
1222 struct btrfs_super_block *disk_super;
1223 struct btrfs_device *device;
1224 struct block_device *bdev;
1230 * we would like to check all the supers, but that would make
1231 * a btrfs mount succeed after a mkfs from a different FS.
1232 * So, we need to add a special mount option to scan for
1233 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1235 bytenr = btrfs_sb_offset(0);
1236 flags |= FMODE_EXCL;
1237 mutex_lock(&uuid_mutex);
1239 bdev = blkdev_get_by_path(path, flags, holder);
1241 ret = PTR_ERR(bdev);
1245 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1247 goto error_bdev_put;
1250 device = device_list_add(path, disk_super);
1252 ret = PTR_ERR(device);
1254 *fs_devices_ret = device->fs_devices;
1256 btrfs_release_disk_super(page);
1259 blkdev_put(bdev, flags);
1261 mutex_unlock(&uuid_mutex);
1265 /* helper to account the used device space in the range */
1266 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1267 u64 end, u64 *length)
1269 struct btrfs_key key;
1270 struct btrfs_root *root = device->fs_info->dev_root;
1271 struct btrfs_dev_extent *dev_extent;
1272 struct btrfs_path *path;
1276 struct extent_buffer *l;
1280 if (start >= device->total_bytes ||
1281 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1284 path = btrfs_alloc_path();
1287 path->reada = READA_FORWARD;
1289 key.objectid = device->devid;
1291 key.type = BTRFS_DEV_EXTENT_KEY;
1293 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1297 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1304 slot = path->slots[0];
1305 if (slot >= btrfs_header_nritems(l)) {
1306 ret = btrfs_next_leaf(root, path);
1314 btrfs_item_key_to_cpu(l, &key, slot);
1316 if (key.objectid < device->devid)
1319 if (key.objectid > device->devid)
1322 if (key.type != BTRFS_DEV_EXTENT_KEY)
1325 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1326 extent_end = key.offset + btrfs_dev_extent_length(l,
1328 if (key.offset <= start && extent_end > end) {
1329 *length = end - start + 1;
1331 } else if (key.offset <= start && extent_end > start)
1332 *length += extent_end - start;
1333 else if (key.offset > start && extent_end <= end)
1334 *length += extent_end - key.offset;
1335 else if (key.offset > start && key.offset <= end) {
1336 *length += end - key.offset + 1;
1338 } else if (key.offset > end)
1346 btrfs_free_path(path);
1350 static int contains_pending_extent(struct btrfs_transaction *transaction,
1351 struct btrfs_device *device,
1352 u64 *start, u64 len)
1354 struct btrfs_fs_info *fs_info = device->fs_info;
1355 struct extent_map *em;
1356 struct list_head *search_list = &fs_info->pinned_chunks;
1358 u64 physical_start = *start;
1361 search_list = &transaction->pending_chunks;
1363 list_for_each_entry(em, search_list, list) {
1364 struct map_lookup *map;
1367 map = em->map_lookup;
1368 for (i = 0; i < map->num_stripes; i++) {
1371 if (map->stripes[i].dev != device)
1373 if (map->stripes[i].physical >= physical_start + len ||
1374 map->stripes[i].physical + em->orig_block_len <=
1378 * Make sure that while processing the pinned list we do
1379 * not override our *start with a lower value, because
1380 * we can have pinned chunks that fall within this
1381 * device hole and that have lower physical addresses
1382 * than the pending chunks we processed before. If we
1383 * do not take this special care we can end up getting
1384 * 2 pending chunks that start at the same physical
1385 * device offsets because the end offset of a pinned
1386 * chunk can be equal to the start offset of some
1389 end = map->stripes[i].physical + em->orig_block_len;
1396 if (search_list != &fs_info->pinned_chunks) {
1397 search_list = &fs_info->pinned_chunks;
1406 * find_free_dev_extent_start - find free space in the specified device
1407 * @device: the device which we search the free space in
1408 * @num_bytes: the size of the free space that we need
1409 * @search_start: the position from which to begin the search
1410 * @start: store the start of the free space.
1411 * @len: the size of the free space. that we find, or the size
1412 * of the max free space if we don't find suitable free space
1414 * this uses a pretty simple search, the expectation is that it is
1415 * called very infrequently and that a given device has a small number
1418 * @start is used to store the start of the free space if we find. But if we
1419 * don't find suitable free space, it will be used to store the start position
1420 * of the max free space.
1422 * @len is used to store the size of the free space that we find.
1423 * But if we don't find suitable free space, it is used to store the size of
1424 * the max free space.
1426 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1427 struct btrfs_device *device, u64 num_bytes,
1428 u64 search_start, u64 *start, u64 *len)
1430 struct btrfs_fs_info *fs_info = device->fs_info;
1431 struct btrfs_root *root = fs_info->dev_root;
1432 struct btrfs_key key;
1433 struct btrfs_dev_extent *dev_extent;
1434 struct btrfs_path *path;
1439 u64 search_end = device->total_bytes;
1442 struct extent_buffer *l;
1445 * We don't want to overwrite the superblock on the drive nor any area
1446 * used by the boot loader (grub for example), so we make sure to start
1447 * at an offset of at least 1MB.
1449 search_start = max_t(u64, search_start, SZ_1M);
1451 path = btrfs_alloc_path();
1455 max_hole_start = search_start;
1459 if (search_start >= search_end ||
1460 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1465 path->reada = READA_FORWARD;
1466 path->search_commit_root = 1;
1467 path->skip_locking = 1;
1469 key.objectid = device->devid;
1470 key.offset = search_start;
1471 key.type = BTRFS_DEV_EXTENT_KEY;
1473 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1477 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1484 slot = path->slots[0];
1485 if (slot >= btrfs_header_nritems(l)) {
1486 ret = btrfs_next_leaf(root, path);
1494 btrfs_item_key_to_cpu(l, &key, slot);
1496 if (key.objectid < device->devid)
1499 if (key.objectid > device->devid)
1502 if (key.type != BTRFS_DEV_EXTENT_KEY)
1505 if (key.offset > search_start) {
1506 hole_size = key.offset - search_start;
1509 * Have to check before we set max_hole_start, otherwise
1510 * we could end up sending back this offset anyway.
1512 if (contains_pending_extent(transaction, device,
1515 if (key.offset >= search_start) {
1516 hole_size = key.offset - search_start;
1523 if (hole_size > max_hole_size) {
1524 max_hole_start = search_start;
1525 max_hole_size = hole_size;
1529 * If this free space is greater than which we need,
1530 * it must be the max free space that we have found
1531 * until now, so max_hole_start must point to the start
1532 * of this free space and the length of this free space
1533 * is stored in max_hole_size. Thus, we return
1534 * max_hole_start and max_hole_size and go back to the
1537 if (hole_size >= num_bytes) {
1543 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1544 extent_end = key.offset + btrfs_dev_extent_length(l,
1546 if (extent_end > search_start)
1547 search_start = extent_end;
1554 * At this point, search_start should be the end of
1555 * allocated dev extents, and when shrinking the device,
1556 * search_end may be smaller than search_start.
1558 if (search_end > search_start) {
1559 hole_size = search_end - search_start;
1561 if (contains_pending_extent(transaction, device, &search_start,
1563 btrfs_release_path(path);
1567 if (hole_size > max_hole_size) {
1568 max_hole_start = search_start;
1569 max_hole_size = hole_size;
1574 if (max_hole_size < num_bytes)
1580 btrfs_free_path(path);
1581 *start = max_hole_start;
1583 *len = max_hole_size;
1587 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1588 struct btrfs_device *device, u64 num_bytes,
1589 u64 *start, u64 *len)
1591 /* FIXME use last free of some kind */
1592 return find_free_dev_extent_start(trans->transaction, device,
1593 num_bytes, 0, start, len);
1596 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1597 struct btrfs_device *device,
1598 u64 start, u64 *dev_extent_len)
1600 struct btrfs_fs_info *fs_info = device->fs_info;
1601 struct btrfs_root *root = fs_info->dev_root;
1603 struct btrfs_path *path;
1604 struct btrfs_key key;
1605 struct btrfs_key found_key;
1606 struct extent_buffer *leaf = NULL;
1607 struct btrfs_dev_extent *extent = NULL;
1609 path = btrfs_alloc_path();
1613 key.objectid = device->devid;
1615 key.type = BTRFS_DEV_EXTENT_KEY;
1617 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1619 ret = btrfs_previous_item(root, path, key.objectid,
1620 BTRFS_DEV_EXTENT_KEY);
1623 leaf = path->nodes[0];
1624 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1625 extent = btrfs_item_ptr(leaf, path->slots[0],
1626 struct btrfs_dev_extent);
1627 BUG_ON(found_key.offset > start || found_key.offset +
1628 btrfs_dev_extent_length(leaf, extent) < start);
1630 btrfs_release_path(path);
1632 } else if (ret == 0) {
1633 leaf = path->nodes[0];
1634 extent = btrfs_item_ptr(leaf, path->slots[0],
1635 struct btrfs_dev_extent);
1637 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1641 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1643 ret = btrfs_del_item(trans, root, path);
1645 btrfs_handle_fs_error(fs_info, ret,
1646 "Failed to remove dev extent item");
1648 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1651 btrfs_free_path(path);
1655 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1656 struct btrfs_device *device,
1657 u64 chunk_offset, u64 start, u64 num_bytes)
1660 struct btrfs_path *path;
1661 struct btrfs_fs_info *fs_info = device->fs_info;
1662 struct btrfs_root *root = fs_info->dev_root;
1663 struct btrfs_dev_extent *extent;
1664 struct extent_buffer *leaf;
1665 struct btrfs_key key;
1667 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1668 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1669 path = btrfs_alloc_path();
1673 key.objectid = device->devid;
1675 key.type = BTRFS_DEV_EXTENT_KEY;
1676 ret = btrfs_insert_empty_item(trans, root, path, &key,
1681 leaf = path->nodes[0];
1682 extent = btrfs_item_ptr(leaf, path->slots[0],
1683 struct btrfs_dev_extent);
1684 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1685 BTRFS_CHUNK_TREE_OBJECTID);
1686 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1687 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1688 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1690 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1691 btrfs_mark_buffer_dirty(leaf);
1693 btrfs_free_path(path);
1697 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1699 struct extent_map_tree *em_tree;
1700 struct extent_map *em;
1704 em_tree = &fs_info->mapping_tree.map_tree;
1705 read_lock(&em_tree->lock);
1706 n = rb_last(&em_tree->map);
1708 em = rb_entry(n, struct extent_map, rb_node);
1709 ret = em->start + em->len;
1711 read_unlock(&em_tree->lock);
1716 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1720 struct btrfs_key key;
1721 struct btrfs_key found_key;
1722 struct btrfs_path *path;
1724 path = btrfs_alloc_path();
1728 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1729 key.type = BTRFS_DEV_ITEM_KEY;
1730 key.offset = (u64)-1;
1732 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1736 BUG_ON(ret == 0); /* Corruption */
1738 ret = btrfs_previous_item(fs_info->chunk_root, path,
1739 BTRFS_DEV_ITEMS_OBJECTID,
1740 BTRFS_DEV_ITEM_KEY);
1744 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1746 *devid_ret = found_key.offset + 1;
1750 btrfs_free_path(path);
1755 * the device information is stored in the chunk root
1756 * the btrfs_device struct should be fully filled in
1758 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1759 struct btrfs_fs_info *fs_info,
1760 struct btrfs_device *device)
1762 struct btrfs_root *root = fs_info->chunk_root;
1764 struct btrfs_path *path;
1765 struct btrfs_dev_item *dev_item;
1766 struct extent_buffer *leaf;
1767 struct btrfs_key key;
1770 path = btrfs_alloc_path();
1774 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1775 key.type = BTRFS_DEV_ITEM_KEY;
1776 key.offset = device->devid;
1778 ret = btrfs_insert_empty_item(trans, root, path, &key,
1783 leaf = path->nodes[0];
1784 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1786 btrfs_set_device_id(leaf, dev_item, device->devid);
1787 btrfs_set_device_generation(leaf, dev_item, 0);
1788 btrfs_set_device_type(leaf, dev_item, device->type);
1789 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1790 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1791 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1792 btrfs_set_device_total_bytes(leaf, dev_item,
1793 btrfs_device_get_disk_total_bytes(device));
1794 btrfs_set_device_bytes_used(leaf, dev_item,
1795 btrfs_device_get_bytes_used(device));
1796 btrfs_set_device_group(leaf, dev_item, 0);
1797 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1798 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1799 btrfs_set_device_start_offset(leaf, dev_item, 0);
1801 ptr = btrfs_device_uuid(dev_item);
1802 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1803 ptr = btrfs_device_fsid(dev_item);
1804 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1805 btrfs_mark_buffer_dirty(leaf);
1809 btrfs_free_path(path);
1814 * Function to update ctime/mtime for a given device path.
1815 * Mainly used for ctime/mtime based probe like libblkid.
1817 static void update_dev_time(const char *path_name)
1821 filp = filp_open(path_name, O_RDWR, 0);
1824 file_update_time(filp);
1825 filp_close(filp, NULL);
1828 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1829 struct btrfs_device *device)
1831 struct btrfs_root *root = fs_info->chunk_root;
1833 struct btrfs_path *path;
1834 struct btrfs_key key;
1835 struct btrfs_trans_handle *trans;
1837 path = btrfs_alloc_path();
1841 trans = btrfs_start_transaction(root, 0);
1842 if (IS_ERR(trans)) {
1843 btrfs_free_path(path);
1844 return PTR_ERR(trans);
1846 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1847 key.type = BTRFS_DEV_ITEM_KEY;
1848 key.offset = device->devid;
1850 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1854 btrfs_abort_transaction(trans, ret);
1855 btrfs_end_transaction(trans);
1859 ret = btrfs_del_item(trans, root, path);
1861 btrfs_abort_transaction(trans, ret);
1862 btrfs_end_transaction(trans);
1866 btrfs_free_path(path);
1868 ret = btrfs_commit_transaction(trans);
1873 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1874 * filesystem. It's up to the caller to adjust that number regarding eg. device
1877 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1885 seq = read_seqbegin(&fs_info->profiles_lock);
1887 all_avail = fs_info->avail_data_alloc_bits |
1888 fs_info->avail_system_alloc_bits |
1889 fs_info->avail_metadata_alloc_bits;
1890 } while (read_seqretry(&fs_info->profiles_lock, seq));
1892 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1893 if (!(all_avail & btrfs_raid_group[i]))
1896 if (num_devices < btrfs_raid_array[i].devs_min) {
1897 int ret = btrfs_raid_mindev_error[i];
1907 static struct btrfs_device * btrfs_find_next_active_device(
1908 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1910 struct btrfs_device *next_device;
1912 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1913 if (next_device != device &&
1914 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1915 && next_device->bdev)
1923 * Helper function to check if the given device is part of s_bdev / latest_bdev
1924 * and replace it with the provided or the next active device, in the context
1925 * where this function called, there should be always be another device (or
1926 * this_dev) which is active.
1928 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1929 struct btrfs_device *device, struct btrfs_device *this_dev)
1931 struct btrfs_device *next_device;
1934 next_device = this_dev;
1936 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1938 ASSERT(next_device);
1940 if (fs_info->sb->s_bdev &&
1941 (fs_info->sb->s_bdev == device->bdev))
1942 fs_info->sb->s_bdev = next_device->bdev;
1944 if (fs_info->fs_devices->latest_bdev == device->bdev)
1945 fs_info->fs_devices->latest_bdev = next_device->bdev;
1948 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1951 struct btrfs_device *device;
1952 struct btrfs_fs_devices *cur_devices;
1953 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1957 mutex_lock(&fs_info->volume_mutex);
1958 mutex_lock(&uuid_mutex);
1960 num_devices = fs_devices->num_devices;
1961 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1962 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1963 WARN_ON(num_devices < 1);
1966 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1968 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1972 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1977 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1978 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1982 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1983 fs_info->fs_devices->rw_devices == 1) {
1984 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1988 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1989 mutex_lock(&fs_info->chunk_mutex);
1990 list_del_init(&device->dev_alloc_list);
1991 device->fs_devices->rw_devices--;
1992 mutex_unlock(&fs_info->chunk_mutex);
1995 mutex_unlock(&uuid_mutex);
1996 ret = btrfs_shrink_device(device, 0);
1997 mutex_lock(&uuid_mutex);
2002 * TODO: the superblock still includes this device in its num_devices
2003 * counter although write_all_supers() is not locked out. This
2004 * could give a filesystem state which requires a degraded mount.
2006 ret = btrfs_rm_dev_item(fs_info, device);
2010 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2011 btrfs_scrub_cancel_dev(fs_info, device);
2014 * the device list mutex makes sure that we don't change
2015 * the device list while someone else is writing out all
2016 * the device supers. Whoever is writing all supers, should
2017 * lock the device list mutex before getting the number of
2018 * devices in the super block (super_copy). Conversely,
2019 * whoever updates the number of devices in the super block
2020 * (super_copy) should hold the device list mutex.
2023 cur_devices = device->fs_devices;
2024 mutex_lock(&fs_devices->device_list_mutex);
2025 list_del_rcu(&device->dev_list);
2027 device->fs_devices->num_devices--;
2028 device->fs_devices->total_devices--;
2030 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2031 device->fs_devices->missing_devices--;
2033 btrfs_assign_next_active_device(fs_info, device, NULL);
2036 device->fs_devices->open_devices--;
2037 /* remove sysfs entry */
2038 btrfs_sysfs_rm_device_link(fs_devices, device);
2041 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2042 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2043 mutex_unlock(&fs_devices->device_list_mutex);
2046 * at this point, the device is zero sized and detached from
2047 * the devices list. All that's left is to zero out the old
2048 * supers and free the device.
2050 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2051 btrfs_scratch_superblocks(device->bdev, device->name->str);
2053 btrfs_close_bdev(device);
2054 call_rcu(&device->rcu, free_device_rcu);
2056 if (cur_devices->open_devices == 0) {
2057 while (fs_devices) {
2058 if (fs_devices->seed == cur_devices) {
2059 fs_devices->seed = cur_devices->seed;
2062 fs_devices = fs_devices->seed;
2064 cur_devices->seed = NULL;
2065 close_fs_devices(cur_devices);
2066 free_fs_devices(cur_devices);
2070 mutex_unlock(&uuid_mutex);
2071 mutex_unlock(&fs_info->volume_mutex);
2075 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2076 mutex_lock(&fs_info->chunk_mutex);
2077 list_add(&device->dev_alloc_list,
2078 &fs_devices->alloc_list);
2079 device->fs_devices->rw_devices++;
2080 mutex_unlock(&fs_info->chunk_mutex);
2085 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2086 struct btrfs_device *srcdev)
2088 struct btrfs_fs_devices *fs_devices;
2090 lockdep_assert_held(&fs_info->fs_devices->device_list_mutex);
2093 * in case of fs with no seed, srcdev->fs_devices will point
2094 * to fs_devices of fs_info. However when the dev being replaced is
2095 * a seed dev it will point to the seed's local fs_devices. In short
2096 * srcdev will have its correct fs_devices in both the cases.
2098 fs_devices = srcdev->fs_devices;
2100 list_del_rcu(&srcdev->dev_list);
2101 list_del(&srcdev->dev_alloc_list);
2102 fs_devices->num_devices--;
2103 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2104 fs_devices->missing_devices--;
2106 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2107 fs_devices->rw_devices--;
2110 fs_devices->open_devices--;
2113 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2114 struct btrfs_device *srcdev)
2116 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2118 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2119 /* zero out the old super if it is writable */
2120 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2123 btrfs_close_bdev(srcdev);
2124 call_rcu(&srcdev->rcu, free_device_rcu);
2126 /* if this is no devs we rather delete the fs_devices */
2127 if (!fs_devices->num_devices) {
2128 struct btrfs_fs_devices *tmp_fs_devices;
2131 * On a mounted FS, num_devices can't be zero unless it's a
2132 * seed. In case of a seed device being replaced, the replace
2133 * target added to the sprout FS, so there will be no more
2134 * device left under the seed FS.
2136 ASSERT(fs_devices->seeding);
2138 tmp_fs_devices = fs_info->fs_devices;
2139 while (tmp_fs_devices) {
2140 if (tmp_fs_devices->seed == fs_devices) {
2141 tmp_fs_devices->seed = fs_devices->seed;
2144 tmp_fs_devices = tmp_fs_devices->seed;
2146 fs_devices->seed = NULL;
2147 close_fs_devices(fs_devices);
2148 free_fs_devices(fs_devices);
2152 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2153 struct btrfs_device *tgtdev)
2155 mutex_lock(&uuid_mutex);
2157 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2159 btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2162 fs_info->fs_devices->open_devices--;
2164 fs_info->fs_devices->num_devices--;
2166 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2168 list_del_rcu(&tgtdev->dev_list);
2170 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2171 mutex_unlock(&uuid_mutex);
2174 * The update_dev_time() with in btrfs_scratch_superblocks()
2175 * may lead to a call to btrfs_show_devname() which will try
2176 * to hold device_list_mutex. And here this device
2177 * is already out of device list, so we don't have to hold
2178 * the device_list_mutex lock.
2180 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2182 btrfs_close_bdev(tgtdev);
2183 call_rcu(&tgtdev->rcu, free_device_rcu);
2186 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2187 const char *device_path,
2188 struct btrfs_device **device)
2191 struct btrfs_super_block *disk_super;
2194 struct block_device *bdev;
2195 struct buffer_head *bh;
2198 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2199 fs_info->bdev_holder, 0, &bdev, &bh);
2202 disk_super = (struct btrfs_super_block *)bh->b_data;
2203 devid = btrfs_stack_device_id(&disk_super->dev_item);
2204 dev_uuid = disk_super->dev_item.uuid;
2205 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2209 blkdev_put(bdev, FMODE_READ);
2213 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2214 const char *device_path,
2215 struct btrfs_device **device)
2218 if (strcmp(device_path, "missing") == 0) {
2219 struct list_head *devices;
2220 struct btrfs_device *tmp;
2222 devices = &fs_info->fs_devices->devices;
2224 * It is safe to read the devices since the volume_mutex
2225 * is held by the caller.
2227 list_for_each_entry(tmp, devices, dev_list) {
2228 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2229 &tmp->dev_state) && !tmp->bdev) {
2236 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2240 return btrfs_find_device_by_path(fs_info, device_path, device);
2245 * Lookup a device given by device id, or the path if the id is 0.
2247 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2248 const char *devpath,
2249 struct btrfs_device **device)
2255 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2259 if (!devpath || !devpath[0])
2262 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2269 * does all the dirty work required for changing file system's UUID.
2271 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2273 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2274 struct btrfs_fs_devices *old_devices;
2275 struct btrfs_fs_devices *seed_devices;
2276 struct btrfs_super_block *disk_super = fs_info->super_copy;
2277 struct btrfs_device *device;
2280 lockdep_assert_held(&uuid_mutex);
2281 if (!fs_devices->seeding)
2284 seed_devices = alloc_fs_devices(NULL);
2285 if (IS_ERR(seed_devices))
2286 return PTR_ERR(seed_devices);
2288 old_devices = clone_fs_devices(fs_devices);
2289 if (IS_ERR(old_devices)) {
2290 kfree(seed_devices);
2291 return PTR_ERR(old_devices);
2294 list_add(&old_devices->fs_list, &fs_uuids);
2296 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2297 seed_devices->opened = 1;
2298 INIT_LIST_HEAD(&seed_devices->devices);
2299 INIT_LIST_HEAD(&seed_devices->alloc_list);
2300 mutex_init(&seed_devices->device_list_mutex);
2302 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2303 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2305 list_for_each_entry(device, &seed_devices->devices, dev_list)
2306 device->fs_devices = seed_devices;
2308 mutex_lock(&fs_info->chunk_mutex);
2309 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2310 mutex_unlock(&fs_info->chunk_mutex);
2312 fs_devices->seeding = 0;
2313 fs_devices->num_devices = 0;
2314 fs_devices->open_devices = 0;
2315 fs_devices->missing_devices = 0;
2316 fs_devices->rotating = 0;
2317 fs_devices->seed = seed_devices;
2319 generate_random_uuid(fs_devices->fsid);
2320 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2321 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2322 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2324 super_flags = btrfs_super_flags(disk_super) &
2325 ~BTRFS_SUPER_FLAG_SEEDING;
2326 btrfs_set_super_flags(disk_super, super_flags);
2332 * Store the expected generation for seed devices in device items.
2334 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2335 struct btrfs_fs_info *fs_info)
2337 struct btrfs_root *root = fs_info->chunk_root;
2338 struct btrfs_path *path;
2339 struct extent_buffer *leaf;
2340 struct btrfs_dev_item *dev_item;
2341 struct btrfs_device *device;
2342 struct btrfs_key key;
2343 u8 fs_uuid[BTRFS_FSID_SIZE];
2344 u8 dev_uuid[BTRFS_UUID_SIZE];
2348 path = btrfs_alloc_path();
2352 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2354 key.type = BTRFS_DEV_ITEM_KEY;
2357 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2361 leaf = path->nodes[0];
2363 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2364 ret = btrfs_next_leaf(root, path);
2369 leaf = path->nodes[0];
2370 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2371 btrfs_release_path(path);
2375 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2376 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2377 key.type != BTRFS_DEV_ITEM_KEY)
2380 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2381 struct btrfs_dev_item);
2382 devid = btrfs_device_id(leaf, dev_item);
2383 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2385 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2387 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2388 BUG_ON(!device); /* Logic error */
2390 if (device->fs_devices->seeding) {
2391 btrfs_set_device_generation(leaf, dev_item,
2392 device->generation);
2393 btrfs_mark_buffer_dirty(leaf);
2401 btrfs_free_path(path);
2405 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2407 struct btrfs_root *root = fs_info->dev_root;
2408 struct request_queue *q;
2409 struct btrfs_trans_handle *trans;
2410 struct btrfs_device *device;
2411 struct block_device *bdev;
2412 struct list_head *devices;
2413 struct super_block *sb = fs_info->sb;
2414 struct rcu_string *name;
2416 int seeding_dev = 0;
2418 bool unlocked = false;
2420 if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2423 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2424 fs_info->bdev_holder);
2426 return PTR_ERR(bdev);
2428 if (fs_info->fs_devices->seeding) {
2430 down_write(&sb->s_umount);
2431 mutex_lock(&uuid_mutex);
2434 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2436 devices = &fs_info->fs_devices->devices;
2438 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2439 list_for_each_entry(device, devices, dev_list) {
2440 if (device->bdev == bdev) {
2443 &fs_info->fs_devices->device_list_mutex);
2447 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2449 device = btrfs_alloc_device(fs_info, NULL, NULL);
2450 if (IS_ERR(device)) {
2451 /* we can safely leave the fs_devices entry around */
2452 ret = PTR_ERR(device);
2456 name = rcu_string_strdup(device_path, GFP_KERNEL);
2459 goto error_free_device;
2461 rcu_assign_pointer(device->name, name);
2463 trans = btrfs_start_transaction(root, 0);
2464 if (IS_ERR(trans)) {
2465 ret = PTR_ERR(trans);
2466 goto error_free_device;
2469 q = bdev_get_queue(bdev);
2470 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2471 device->generation = trans->transid;
2472 device->io_width = fs_info->sectorsize;
2473 device->io_align = fs_info->sectorsize;
2474 device->sector_size = fs_info->sectorsize;
2475 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2476 fs_info->sectorsize);
2477 device->disk_total_bytes = device->total_bytes;
2478 device->commit_total_bytes = device->total_bytes;
2479 device->fs_info = fs_info;
2480 device->bdev = bdev;
2481 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2482 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2483 device->mode = FMODE_EXCL;
2484 device->dev_stats_valid = 1;
2485 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2488 sb->s_flags &= ~SB_RDONLY;
2489 ret = btrfs_prepare_sprout(fs_info);
2491 btrfs_abort_transaction(trans, ret);
2496 device->fs_devices = fs_info->fs_devices;
2498 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2499 mutex_lock(&fs_info->chunk_mutex);
2500 list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2501 list_add(&device->dev_alloc_list,
2502 &fs_info->fs_devices->alloc_list);
2503 fs_info->fs_devices->num_devices++;
2504 fs_info->fs_devices->open_devices++;
2505 fs_info->fs_devices->rw_devices++;
2506 fs_info->fs_devices->total_devices++;
2507 fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2509 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2511 if (!blk_queue_nonrot(q))
2512 fs_info->fs_devices->rotating = 1;
2514 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2515 btrfs_set_super_total_bytes(fs_info->super_copy,
2516 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2518 tmp = btrfs_super_num_devices(fs_info->super_copy);
2519 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2521 /* add sysfs device entry */
2522 btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2525 * we've got more storage, clear any full flags on the space
2528 btrfs_clear_space_info_full(fs_info);
2530 mutex_unlock(&fs_info->chunk_mutex);
2531 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2534 mutex_lock(&fs_info->chunk_mutex);
2535 ret = init_first_rw_device(trans, fs_info);
2536 mutex_unlock(&fs_info->chunk_mutex);
2538 btrfs_abort_transaction(trans, ret);
2543 ret = btrfs_add_dev_item(trans, fs_info, device);
2545 btrfs_abort_transaction(trans, ret);
2550 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2552 ret = btrfs_finish_sprout(trans, fs_info);
2554 btrfs_abort_transaction(trans, ret);
2558 /* Sprouting would change fsid of the mounted root,
2559 * so rename the fsid on the sysfs
2561 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2563 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2565 "sysfs: failed to create fsid for sprout");
2568 ret = btrfs_commit_transaction(trans);
2571 mutex_unlock(&uuid_mutex);
2572 up_write(&sb->s_umount);
2575 if (ret) /* transaction commit */
2578 ret = btrfs_relocate_sys_chunks(fs_info);
2580 btrfs_handle_fs_error(fs_info, ret,
2581 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2582 trans = btrfs_attach_transaction(root);
2583 if (IS_ERR(trans)) {
2584 if (PTR_ERR(trans) == -ENOENT)
2586 ret = PTR_ERR(trans);
2590 ret = btrfs_commit_transaction(trans);
2593 /* Update ctime/mtime for libblkid */
2594 update_dev_time(device_path);
2598 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2601 sb->s_flags |= SB_RDONLY;
2603 btrfs_end_transaction(trans);
2605 free_device(device);
2607 blkdev_put(bdev, FMODE_EXCL);
2608 if (seeding_dev && !unlocked) {
2609 mutex_unlock(&uuid_mutex);
2610 up_write(&sb->s_umount);
2615 int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2616 const char *device_path,
2617 struct btrfs_device *srcdev,
2618 struct btrfs_device **device_out)
2620 struct btrfs_device *device;
2621 struct block_device *bdev;
2622 struct list_head *devices;
2623 struct rcu_string *name;
2624 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2628 if (fs_info->fs_devices->seeding) {
2629 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2633 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2634 fs_info->bdev_holder);
2636 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2637 return PTR_ERR(bdev);
2640 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2642 devices = &fs_info->fs_devices->devices;
2643 list_for_each_entry(device, devices, dev_list) {
2644 if (device->bdev == bdev) {
2646 "target device is in the filesystem!");
2653 if (i_size_read(bdev->bd_inode) <
2654 btrfs_device_get_total_bytes(srcdev)) {
2656 "target device is smaller than source device!");
2662 device = btrfs_alloc_device(NULL, &devid, NULL);
2663 if (IS_ERR(device)) {
2664 ret = PTR_ERR(device);
2668 name = rcu_string_strdup(device_path, GFP_KERNEL);
2670 free_device(device);
2674 rcu_assign_pointer(device->name, name);
2676 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2677 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2678 device->generation = 0;
2679 device->io_width = fs_info->sectorsize;
2680 device->io_align = fs_info->sectorsize;
2681 device->sector_size = fs_info->sectorsize;
2682 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2683 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2684 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2685 device->commit_total_bytes = srcdev->commit_total_bytes;
2686 device->commit_bytes_used = device->bytes_used;
2687 device->fs_info = fs_info;
2688 device->bdev = bdev;
2689 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2690 set_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2691 device->mode = FMODE_EXCL;
2692 device->dev_stats_valid = 1;
2693 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2694 device->fs_devices = fs_info->fs_devices;
2695 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2696 fs_info->fs_devices->num_devices++;
2697 fs_info->fs_devices->open_devices++;
2698 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2700 *device_out = device;
2704 blkdev_put(bdev, FMODE_EXCL);
2708 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2709 struct btrfs_device *device)
2712 struct btrfs_path *path;
2713 struct btrfs_root *root = device->fs_info->chunk_root;
2714 struct btrfs_dev_item *dev_item;
2715 struct extent_buffer *leaf;
2716 struct btrfs_key key;
2718 path = btrfs_alloc_path();
2722 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2723 key.type = BTRFS_DEV_ITEM_KEY;
2724 key.offset = device->devid;
2726 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2735 leaf = path->nodes[0];
2736 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2738 btrfs_set_device_id(leaf, dev_item, device->devid);
2739 btrfs_set_device_type(leaf, dev_item, device->type);
2740 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2741 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2742 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2743 btrfs_set_device_total_bytes(leaf, dev_item,
2744 btrfs_device_get_disk_total_bytes(device));
2745 btrfs_set_device_bytes_used(leaf, dev_item,
2746 btrfs_device_get_bytes_used(device));
2747 btrfs_mark_buffer_dirty(leaf);
2750 btrfs_free_path(path);
2754 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2755 struct btrfs_device *device, u64 new_size)
2757 struct btrfs_fs_info *fs_info = device->fs_info;
2758 struct btrfs_super_block *super_copy = fs_info->super_copy;
2759 struct btrfs_fs_devices *fs_devices;
2763 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2766 new_size = round_down(new_size, fs_info->sectorsize);
2768 mutex_lock(&fs_info->chunk_mutex);
2769 old_total = btrfs_super_total_bytes(super_copy);
2770 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2772 if (new_size <= device->total_bytes ||
2773 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2774 mutex_unlock(&fs_info->chunk_mutex);
2778 fs_devices = fs_info->fs_devices;
2780 btrfs_set_super_total_bytes(super_copy,
2781 round_down(old_total + diff, fs_info->sectorsize));
2782 device->fs_devices->total_rw_bytes += diff;
2784 btrfs_device_set_total_bytes(device, new_size);
2785 btrfs_device_set_disk_total_bytes(device, new_size);
2786 btrfs_clear_space_info_full(device->fs_info);
2787 if (list_empty(&device->resized_list))
2788 list_add_tail(&device->resized_list,
2789 &fs_devices->resized_devices);
2790 mutex_unlock(&fs_info->chunk_mutex);
2792 return btrfs_update_device(trans, device);
2795 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2796 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2798 struct btrfs_root *root = fs_info->chunk_root;
2800 struct btrfs_path *path;
2801 struct btrfs_key key;
2803 path = btrfs_alloc_path();
2807 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2808 key.offset = chunk_offset;
2809 key.type = BTRFS_CHUNK_ITEM_KEY;
2811 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2814 else if (ret > 0) { /* Logic error or corruption */
2815 btrfs_handle_fs_error(fs_info, -ENOENT,
2816 "Failed lookup while freeing chunk.");
2821 ret = btrfs_del_item(trans, root, path);
2823 btrfs_handle_fs_error(fs_info, ret,
2824 "Failed to delete chunk item.");
2826 btrfs_free_path(path);
2830 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2832 struct btrfs_super_block *super_copy = fs_info->super_copy;
2833 struct btrfs_disk_key *disk_key;
2834 struct btrfs_chunk *chunk;
2841 struct btrfs_key key;
2843 mutex_lock(&fs_info->chunk_mutex);
2844 array_size = btrfs_super_sys_array_size(super_copy);
2846 ptr = super_copy->sys_chunk_array;
2849 while (cur < array_size) {
2850 disk_key = (struct btrfs_disk_key *)ptr;
2851 btrfs_disk_key_to_cpu(&key, disk_key);
2853 len = sizeof(*disk_key);
2855 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2856 chunk = (struct btrfs_chunk *)(ptr + len);
2857 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2858 len += btrfs_chunk_item_size(num_stripes);
2863 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2864 key.offset == chunk_offset) {
2865 memmove(ptr, ptr + len, array_size - (cur + len));
2867 btrfs_set_super_sys_array_size(super_copy, array_size);
2873 mutex_unlock(&fs_info->chunk_mutex);
2877 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2878 u64 logical, u64 length)
2880 struct extent_map_tree *em_tree;
2881 struct extent_map *em;
2883 em_tree = &fs_info->mapping_tree.map_tree;
2884 read_lock(&em_tree->lock);
2885 em = lookup_extent_mapping(em_tree, logical, length);
2886 read_unlock(&em_tree->lock);
2889 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2891 return ERR_PTR(-EINVAL);
2894 if (em->start > logical || em->start + em->len < logical) {
2896 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2897 logical, length, em->start, em->start + em->len);
2898 free_extent_map(em);
2899 return ERR_PTR(-EINVAL);
2902 /* callers are responsible for dropping em's ref. */
2906 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2907 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2909 struct extent_map *em;
2910 struct map_lookup *map;
2911 u64 dev_extent_len = 0;
2913 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2915 em = get_chunk_map(fs_info, chunk_offset, 1);
2918 * This is a logic error, but we don't want to just rely on the
2919 * user having built with ASSERT enabled, so if ASSERT doesn't
2920 * do anything we still error out.
2925 map = em->map_lookup;
2926 mutex_lock(&fs_info->chunk_mutex);
2927 check_system_chunk(trans, fs_info, map->type);
2928 mutex_unlock(&fs_info->chunk_mutex);
2931 * Take the device list mutex to prevent races with the final phase of
2932 * a device replace operation that replaces the device object associated
2933 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2935 mutex_lock(&fs_devices->device_list_mutex);
2936 for (i = 0; i < map->num_stripes; i++) {
2937 struct btrfs_device *device = map->stripes[i].dev;
2938 ret = btrfs_free_dev_extent(trans, device,
2939 map->stripes[i].physical,
2942 mutex_unlock(&fs_devices->device_list_mutex);
2943 btrfs_abort_transaction(trans, ret);
2947 if (device->bytes_used > 0) {
2948 mutex_lock(&fs_info->chunk_mutex);
2949 btrfs_device_set_bytes_used(device,
2950 device->bytes_used - dev_extent_len);
2951 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2952 btrfs_clear_space_info_full(fs_info);
2953 mutex_unlock(&fs_info->chunk_mutex);
2956 if (map->stripes[i].dev) {
2957 ret = btrfs_update_device(trans, map->stripes[i].dev);
2959 mutex_unlock(&fs_devices->device_list_mutex);
2960 btrfs_abort_transaction(trans, ret);
2965 mutex_unlock(&fs_devices->device_list_mutex);
2967 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2969 btrfs_abort_transaction(trans, ret);
2973 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2975 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2976 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2978 btrfs_abort_transaction(trans, ret);
2983 ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2985 btrfs_abort_transaction(trans, ret);
2991 free_extent_map(em);
2995 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2997 struct btrfs_root *root = fs_info->chunk_root;
2998 struct btrfs_trans_handle *trans;
3002 * Prevent races with automatic removal of unused block groups.
3003 * After we relocate and before we remove the chunk with offset
3004 * chunk_offset, automatic removal of the block group can kick in,
3005 * resulting in a failure when calling btrfs_remove_chunk() below.
3007 * Make sure to acquire this mutex before doing a tree search (dev
3008 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3009 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3010 * we release the path used to search the chunk/dev tree and before
3011 * the current task acquires this mutex and calls us.
3013 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3015 ret = btrfs_can_relocate(fs_info, chunk_offset);
3019 /* step one, relocate all the extents inside this chunk */
3020 btrfs_scrub_pause(fs_info);
3021 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3022 btrfs_scrub_continue(fs_info);
3027 * We add the kobjects here (and after forcing data chunk creation)
3028 * since relocation is the only place we'll create chunks of a new
3029 * type at runtime. The only place where we'll remove the last
3030 * chunk of a type is the call immediately below this one. Even
3031 * so, we're protected against races with the cleaner thread since
3032 * we're covered by the delete_unused_bgs_mutex.
3034 btrfs_add_raid_kobjects(fs_info);
3036 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3038 if (IS_ERR(trans)) {
3039 ret = PTR_ERR(trans);
3040 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3045 * step two, delete the device extents and the
3046 * chunk tree entries
3048 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
3049 btrfs_end_transaction(trans);
3053 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3055 struct btrfs_root *chunk_root = fs_info->chunk_root;
3056 struct btrfs_path *path;
3057 struct extent_buffer *leaf;
3058 struct btrfs_chunk *chunk;
3059 struct btrfs_key key;
3060 struct btrfs_key found_key;
3062 bool retried = false;
3066 path = btrfs_alloc_path();
3071 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3072 key.offset = (u64)-1;
3073 key.type = BTRFS_CHUNK_ITEM_KEY;
3076 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3077 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3079 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3082 BUG_ON(ret == 0); /* Corruption */
3084 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3087 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3093 leaf = path->nodes[0];
3094 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3096 chunk = btrfs_item_ptr(leaf, path->slots[0],
3097 struct btrfs_chunk);
3098 chunk_type = btrfs_chunk_type(leaf, chunk);
3099 btrfs_release_path(path);
3101 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3102 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3108 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3110 if (found_key.offset == 0)
3112 key.offset = found_key.offset - 1;
3115 if (failed && !retried) {
3119 } else if (WARN_ON(failed && retried)) {
3123 btrfs_free_path(path);
3128 * return 1 : allocate a data chunk successfully,
3129 * return <0: errors during allocating a data chunk,
3130 * return 0 : no need to allocate a data chunk.
3132 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3135 struct btrfs_block_group_cache *cache;
3139 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3141 chunk_type = cache->flags;
3142 btrfs_put_block_group(cache);
3144 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3145 spin_lock(&fs_info->data_sinfo->lock);
3146 bytes_used = fs_info->data_sinfo->bytes_used;
3147 spin_unlock(&fs_info->data_sinfo->lock);
3150 struct btrfs_trans_handle *trans;
3153 trans = btrfs_join_transaction(fs_info->tree_root);
3155 return PTR_ERR(trans);
3157 ret = btrfs_force_chunk_alloc(trans, fs_info,
3158 BTRFS_BLOCK_GROUP_DATA);
3159 btrfs_end_transaction(trans);
3163 btrfs_add_raid_kobjects(fs_info);
3171 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3172 struct btrfs_balance_control *bctl)
3174 struct btrfs_root *root = fs_info->tree_root;
3175 struct btrfs_trans_handle *trans;
3176 struct btrfs_balance_item *item;
3177 struct btrfs_disk_balance_args disk_bargs;
3178 struct btrfs_path *path;
3179 struct extent_buffer *leaf;
3180 struct btrfs_key key;
3183 path = btrfs_alloc_path();
3187 trans = btrfs_start_transaction(root, 0);
3188 if (IS_ERR(trans)) {
3189 btrfs_free_path(path);
3190 return PTR_ERR(trans);
3193 key.objectid = BTRFS_BALANCE_OBJECTID;
3194 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3197 ret = btrfs_insert_empty_item(trans, root, path, &key,
3202 leaf = path->nodes[0];
3203 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3205 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3207 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3208 btrfs_set_balance_data(leaf, item, &disk_bargs);
3209 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3210 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3211 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3212 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3214 btrfs_set_balance_flags(leaf, item, bctl->flags);
3216 btrfs_mark_buffer_dirty(leaf);
3218 btrfs_free_path(path);
3219 err = btrfs_commit_transaction(trans);
3225 static int del_balance_item(struct btrfs_fs_info *fs_info)
3227 struct btrfs_root *root = fs_info->tree_root;
3228 struct btrfs_trans_handle *trans;
3229 struct btrfs_path *path;
3230 struct btrfs_key key;
3233 path = btrfs_alloc_path();
3237 trans = btrfs_start_transaction(root, 0);
3238 if (IS_ERR(trans)) {
3239 btrfs_free_path(path);
3240 return PTR_ERR(trans);
3243 key.objectid = BTRFS_BALANCE_OBJECTID;
3244 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3247 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);