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->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, list);
312 list_del(&fs_devices->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 list_head *head = &fs_devices->devices;
366 struct btrfs_device *dev;
368 list_for_each_entry(dev, head, dev_list) {
369 if (dev->devid == devid &&
370 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
377 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
379 struct btrfs_fs_devices *fs_devices;
381 list_for_each_entry(fs_devices, &fs_uuids, list) {
382 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
389 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
390 int flush, struct block_device **bdev,
391 struct buffer_head **bh)
395 *bdev = blkdev_get_by_path(device_path, flags, holder);
398 ret = PTR_ERR(*bdev);
403 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
404 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
406 blkdev_put(*bdev, flags);
409 invalidate_bdev(*bdev);
410 *bh = btrfs_read_dev_super(*bdev);
413 blkdev_put(*bdev, flags);
425 static void requeue_list(struct btrfs_pending_bios *pending_bios,
426 struct bio *head, struct bio *tail)
429 struct bio *old_head;
431 old_head = pending_bios->head;
432 pending_bios->head = head;
433 if (pending_bios->tail)
434 tail->bi_next = old_head;
436 pending_bios->tail = tail;
440 * we try to collect pending bios for a device so we don't get a large
441 * number of procs sending bios down to the same device. This greatly
442 * improves the schedulers ability to collect and merge the bios.
444 * But, it also turns into a long list of bios to process and that is sure
445 * to eventually make the worker thread block. The solution here is to
446 * make some progress and then put this work struct back at the end of
447 * the list if the block device is congested. This way, multiple devices
448 * can make progress from a single worker thread.
450 static noinline void run_scheduled_bios(struct btrfs_device *device)
452 struct btrfs_fs_info *fs_info = device->fs_info;
454 struct backing_dev_info *bdi;
455 struct btrfs_pending_bios *pending_bios;
459 unsigned long num_run;
460 unsigned long batch_run = 0;
461 unsigned long last_waited = 0;
463 int sync_pending = 0;
464 struct blk_plug plug;
467 * this function runs all the bios we've collected for
468 * a particular device. We don't want to wander off to
469 * another device without first sending all of these down.
470 * So, setup a plug here and finish it off before we return
472 blk_start_plug(&plug);
474 bdi = device->bdev->bd_bdi;
477 spin_lock(&device->io_lock);
482 /* take all the bios off the list at once and process them
483 * later on (without the lock held). But, remember the
484 * tail and other pointers so the bios can be properly reinserted
485 * into the list if we hit congestion
487 if (!force_reg && device->pending_sync_bios.head) {
488 pending_bios = &device->pending_sync_bios;
491 pending_bios = &device->pending_bios;
495 pending = pending_bios->head;
496 tail = pending_bios->tail;
497 WARN_ON(pending && !tail);
500 * if pending was null this time around, no bios need processing
501 * at all and we can stop. Otherwise it'll loop back up again
502 * and do an additional check so no bios are missed.
504 * device->running_pending is used to synchronize with the
507 if (device->pending_sync_bios.head == NULL &&
508 device->pending_bios.head == NULL) {
510 device->running_pending = 0;
513 device->running_pending = 1;
516 pending_bios->head = NULL;
517 pending_bios->tail = NULL;
519 spin_unlock(&device->io_lock);
524 /* we want to work on both lists, but do more bios on the
525 * sync list than the regular list
528 pending_bios != &device->pending_sync_bios &&
529 device->pending_sync_bios.head) ||
530 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
531 device->pending_bios.head)) {
532 spin_lock(&device->io_lock);
533 requeue_list(pending_bios, pending, tail);
538 pending = pending->bi_next;
541 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
544 * if we're doing the sync list, record that our
545 * plug has some sync requests on it
547 * If we're doing the regular list and there are
548 * sync requests sitting around, unplug before
551 if (pending_bios == &device->pending_sync_bios) {
553 } else if (sync_pending) {
554 blk_finish_plug(&plug);
555 blk_start_plug(&plug);
559 btrfsic_submit_bio(cur);
566 * we made progress, there is more work to do and the bdi
567 * is now congested. Back off and let other work structs
570 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
571 fs_info->fs_devices->open_devices > 1) {
572 struct io_context *ioc;
574 ioc = current->io_context;
577 * the main goal here is that we don't want to
578 * block if we're going to be able to submit
579 * more requests without blocking.
581 * This code does two great things, it pokes into
582 * the elevator code from a filesystem _and_
583 * it makes assumptions about how batching works.
585 if (ioc && ioc->nr_batch_requests > 0 &&
586 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
588 ioc->last_waited == last_waited)) {
590 * we want to go through our batch of
591 * requests and stop. So, we copy out
592 * the ioc->last_waited time and test
593 * against it before looping
595 last_waited = ioc->last_waited;
599 spin_lock(&device->io_lock);
600 requeue_list(pending_bios, pending, tail);
601 device->running_pending = 1;
603 spin_unlock(&device->io_lock);
604 btrfs_queue_work(fs_info->submit_workers,
614 spin_lock(&device->io_lock);
615 if (device->pending_bios.head || device->pending_sync_bios.head)
617 spin_unlock(&device->io_lock);
620 blk_finish_plug(&plug);
623 static void pending_bios_fn(struct btrfs_work *work)
625 struct btrfs_device *device;
627 device = container_of(work, struct btrfs_device, work);
628 run_scheduled_bios(device);
632 * Search and remove all stale (devices which are not mounted) devices.
633 * When both inputs are NULL, it will search and release all stale devices.
634 * path: Optional. When provided will it release all unmounted devices
635 * matching this path only.
636 * skip_dev: Optional. Will skip this device when searching for the stale
639 static void btrfs_free_stale_devices(const char *path,
640 struct btrfs_device *skip_dev)
642 struct btrfs_fs_devices *fs_devs, *tmp_fs_devs;
643 struct btrfs_device *dev, *tmp_dev;
645 list_for_each_entry_safe(fs_devs, tmp_fs_devs, &fs_uuids, list) {
650 list_for_each_entry_safe(dev, tmp_dev,
651 &fs_devs->devices, dev_list) {
654 if (skip_dev && skip_dev == dev)
656 if (path && !dev->name)
661 not_found = strcmp(rcu_str_deref(dev->name),
667 /* delete the stale device */
668 if (fs_devs->num_devices == 1) {
669 btrfs_sysfs_remove_fsid(fs_devs);
670 list_del(&fs_devs->list);
671 free_fs_devices(fs_devs);
674 fs_devs->num_devices--;
675 list_del(&dev->dev_list);
682 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
683 struct btrfs_device *device, fmode_t flags,
686 struct request_queue *q;
687 struct block_device *bdev;
688 struct buffer_head *bh;
689 struct btrfs_super_block *disk_super;
698 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
703 disk_super = (struct btrfs_super_block *)bh->b_data;
704 devid = btrfs_stack_device_id(&disk_super->dev_item);
705 if (devid != device->devid)
708 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
711 device->generation = btrfs_super_generation(disk_super);
713 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
714 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
715 fs_devices->seeding = 1;
717 if (bdev_read_only(bdev))
718 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
720 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
723 q = bdev_get_queue(bdev);
724 if (!blk_queue_nonrot(q))
725 fs_devices->rotating = 1;
728 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
729 device->mode = flags;
731 fs_devices->open_devices++;
732 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
733 device->devid != BTRFS_DEV_REPLACE_DEVID) {
734 fs_devices->rw_devices++;
735 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
743 blkdev_put(bdev, flags);
749 * Add new device to list of registered devices
752 * device pointer which was just added or updated when successful
753 * error pointer when failed
755 static noinline struct btrfs_device *device_list_add(const char *path,
756 struct btrfs_super_block *disk_super)
758 struct btrfs_device *device;
759 struct btrfs_fs_devices *fs_devices;
760 struct rcu_string *name;
761 u64 found_transid = btrfs_super_generation(disk_super);
762 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
764 fs_devices = find_fsid(disk_super->fsid);
766 fs_devices = alloc_fs_devices(disk_super->fsid);
767 if (IS_ERR(fs_devices))
768 return ERR_CAST(fs_devices);
770 list_add(&fs_devices->list, &fs_uuids);
774 device = find_device(fs_devices, devid,
775 disk_super->dev_item.uuid);
779 if (fs_devices->opened)
780 return ERR_PTR(-EBUSY);
782 device = btrfs_alloc_device(NULL, &devid,
783 disk_super->dev_item.uuid);
784 if (IS_ERR(device)) {
785 /* we can safely leave the fs_devices entry around */
789 name = rcu_string_strdup(path, GFP_NOFS);
792 return ERR_PTR(-ENOMEM);
794 rcu_assign_pointer(device->name, name);
796 mutex_lock(&fs_devices->device_list_mutex);
797 list_add_rcu(&device->dev_list, &fs_devices->devices);
798 fs_devices->num_devices++;
799 mutex_unlock(&fs_devices->device_list_mutex);
801 device->fs_devices = fs_devices;
802 btrfs_free_stale_devices(path, device);
804 if (disk_super->label[0])
805 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
806 disk_super->label, devid, found_transid, path);
808 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
809 disk_super->fsid, devid, found_transid, path);
811 } else if (!device->name || strcmp(device->name->str, path)) {
813 * When FS is already mounted.
814 * 1. If you are here and if the device->name is NULL that
815 * means this device was missing at time of FS mount.
816 * 2. If you are here and if the device->name is different
817 * from 'path' that means either
818 * a. The same device disappeared and reappeared with
820 * b. The missing-disk-which-was-replaced, has
823 * We must allow 1 and 2a above. But 2b would be a spurious
826 * Further in case of 1 and 2a above, the disk at 'path'
827 * would have missed some transaction when it was away and
828 * in case of 2a the stale bdev has to be updated as well.
829 * 2b must not be allowed at all time.
833 * For now, we do allow update to btrfs_fs_device through the
834 * btrfs dev scan cli after FS has been mounted. We're still
835 * tracking a problem where systems fail mount by subvolume id
836 * when we reject replacement on a mounted FS.
838 if (!fs_devices->opened && found_transid < device->generation) {
840 * That is if the FS is _not_ mounted and if you
841 * are here, that means there is more than one
842 * disk with same uuid and devid.We keep the one
843 * with larger generation number or the last-in if
844 * generation are equal.
846 return ERR_PTR(-EEXIST);
849 name = rcu_string_strdup(path, GFP_NOFS);
851 return ERR_PTR(-ENOMEM);
852 rcu_string_free(device->name);
853 rcu_assign_pointer(device->name, name);
854 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
855 fs_devices->missing_devices--;
856 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
861 * Unmount does not free the btrfs_device struct but would zero
862 * generation along with most of the other members. So just update
863 * it back. We need it to pick the disk with largest generation
866 if (!fs_devices->opened)
867 device->generation = found_transid;
869 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
874 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
876 struct btrfs_fs_devices *fs_devices;
877 struct btrfs_device *device;
878 struct btrfs_device *orig_dev;
880 fs_devices = alloc_fs_devices(orig->fsid);
881 if (IS_ERR(fs_devices))
884 mutex_lock(&orig->device_list_mutex);
885 fs_devices->total_devices = orig->total_devices;
887 /* We have held the volume lock, it is safe to get the devices. */
888 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
889 struct rcu_string *name;
891 device = btrfs_alloc_device(NULL, &orig_dev->devid,
897 * This is ok to do without rcu read locked because we hold the
898 * uuid mutex so nothing we touch in here is going to disappear.
900 if (orig_dev->name) {
901 name = rcu_string_strdup(orig_dev->name->str,
907 rcu_assign_pointer(device->name, name);
910 list_add(&device->dev_list, &fs_devices->devices);
911 device->fs_devices = fs_devices;
912 fs_devices->num_devices++;
914 mutex_unlock(&orig->device_list_mutex);
917 mutex_unlock(&orig->device_list_mutex);
918 free_fs_devices(fs_devices);
919 return ERR_PTR(-ENOMEM);
923 * After we have read the system tree and know devids belonging to
924 * this filesystem, remove the device which does not belong there.
926 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
928 struct btrfs_device *device, *next;
929 struct btrfs_device *latest_dev = NULL;
931 mutex_lock(&uuid_mutex);
933 /* This is the initialized path, it is safe to release the devices. */
934 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
935 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
936 &device->dev_state)) {
937 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
938 &device->dev_state) &&
940 device->generation > latest_dev->generation)) {
946 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
948 * In the first step, keep the device which has
949 * the correct fsid and the devid that is used
950 * for the dev_replace procedure.
951 * In the second step, the dev_replace state is
952 * read from the device tree and it is known
953 * whether the procedure is really active or
954 * not, which means whether this device is
955 * used or whether it should be removed.
957 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
958 &device->dev_state)) {
963 blkdev_put(device->bdev, device->mode);
965 fs_devices->open_devices--;
967 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
968 list_del_init(&device->dev_alloc_list);
969 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
970 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
972 fs_devices->rw_devices--;
974 list_del_init(&device->dev_list);
975 fs_devices->num_devices--;
979 if (fs_devices->seed) {
980 fs_devices = fs_devices->seed;
984 fs_devices->latest_bdev = latest_dev->bdev;
986 mutex_unlock(&uuid_mutex);
989 static void free_device_rcu(struct rcu_head *head)
991 struct btrfs_device *device;
993 device = container_of(head, struct btrfs_device, rcu);
997 static void btrfs_close_bdev(struct btrfs_device *device)
1002 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1003 sync_blockdev(device->bdev);
1004 invalidate_bdev(device->bdev);
1007 blkdev_put(device->bdev, device->mode);
1010 static void btrfs_prepare_close_one_device(struct btrfs_device *device)
1012 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1013 struct btrfs_device *new_device;
1014 struct rcu_string *name;
1017 fs_devices->open_devices--;
1019 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1020 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1021 list_del_init(&device->dev_alloc_list);
1022 fs_devices->rw_devices--;
1025 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1026 fs_devices->missing_devices--;
1028 new_device = btrfs_alloc_device(NULL, &device->devid,
1030 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1032 /* Safe because we are under uuid_mutex */
1034 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1035 BUG_ON(!name); /* -ENOMEM */
1036 rcu_assign_pointer(new_device->name, name);
1039 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1040 new_device->fs_devices = device->fs_devices;
1043 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1045 struct btrfs_device *device, *tmp;
1046 struct list_head pending_put;
1048 INIT_LIST_HEAD(&pending_put);
1050 if (--fs_devices->opened > 0)
1053 mutex_lock(&fs_devices->device_list_mutex);
1054 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1055 btrfs_prepare_close_one_device(device);
1056 list_add(&device->dev_list, &pending_put);
1058 mutex_unlock(&fs_devices->device_list_mutex);
1061 * btrfs_show_devname() is using the device_list_mutex,
1062 * sometimes call to blkdev_put() leads vfs calling
1063 * into this func. So do put outside of device_list_mutex,
1066 while (!list_empty(&pending_put)) {
1067 device = list_first_entry(&pending_put,
1068 struct btrfs_device, dev_list);
1069 list_del(&device->dev_list);
1070 btrfs_close_bdev(device);
1071 call_rcu(&device->rcu, free_device_rcu);
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 = __btrfs_close_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 __btrfs_close_devices(fs_devices);
1099 free_fs_devices(fs_devices);
1104 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1105 fmode_t flags, void *holder)
1107 struct list_head *head = &fs_devices->devices;
1108 struct btrfs_device *device;
1109 struct btrfs_device *latest_dev = NULL;
1112 flags |= FMODE_EXCL;
1114 list_for_each_entry(device, head, dev_list) {
1115 /* Just open everything we can; ignore failures here */
1116 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1120 device->generation > latest_dev->generation)
1121 latest_dev = device;
1123 if (fs_devices->open_devices == 0) {
1127 fs_devices->opened = 1;
1128 fs_devices->latest_bdev = latest_dev->bdev;
1129 fs_devices->total_rw_bytes = 0;
1134 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1136 struct btrfs_device *dev1, *dev2;
1138 dev1 = list_entry(a, struct btrfs_device, dev_list);
1139 dev2 = list_entry(b, struct btrfs_device, dev_list);
1141 if (dev1->devid < dev2->devid)
1143 else if (dev1->devid > dev2->devid)
1148 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1149 fmode_t flags, void *holder)
1153 mutex_lock(&uuid_mutex);
1154 if (fs_devices->opened) {
1155 fs_devices->opened++;
1158 list_sort(NULL, &fs_devices->devices, devid_cmp);
1159 ret = __btrfs_open_devices(fs_devices, flags, holder);
1161 mutex_unlock(&uuid_mutex);
1165 static void btrfs_release_disk_super(struct page *page)
1171 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1173 struct btrfs_super_block **disk_super)
1178 /* make sure our super fits in the device */
1179 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1182 /* make sure our super fits in the page */
1183 if (sizeof(**disk_super) > PAGE_SIZE)
1186 /* make sure our super doesn't straddle pages on disk */
1187 index = bytenr >> PAGE_SHIFT;
1188 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1191 /* pull in the page with our super */
1192 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1195 if (IS_ERR_OR_NULL(*page))
1200 /* align our pointer to the offset of the super block */
1201 *disk_super = p + (bytenr & ~PAGE_MASK);
1203 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1204 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1205 btrfs_release_disk_super(*page);
1209 if ((*disk_super)->label[0] &&
1210 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1211 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1217 * Look for a btrfs signature on a device. This may be called out of the mount path
1218 * and we are not allowed to call set_blocksize during the scan. The superblock
1219 * is read via pagecache
1221 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1222 struct btrfs_fs_devices **fs_devices_ret)
1224 struct btrfs_super_block *disk_super;
1225 struct btrfs_device *device;
1226 struct block_device *bdev;
1232 * we would like to check all the supers, but that would make
1233 * a btrfs mount succeed after a mkfs from a different FS.
1234 * So, we need to add a special mount option to scan for
1235 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1237 bytenr = btrfs_sb_offset(0);
1238 flags |= FMODE_EXCL;
1239 mutex_lock(&uuid_mutex);
1241 bdev = blkdev_get_by_path(path, flags, holder);
1243 ret = PTR_ERR(bdev);
1247 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1249 goto error_bdev_put;
1252 device = device_list_add(path, disk_super);
1254 ret = PTR_ERR(device);
1256 *fs_devices_ret = device->fs_devices;
1258 btrfs_release_disk_super(page);
1261 blkdev_put(bdev, flags);
1263 mutex_unlock(&uuid_mutex);
1267 /* helper to account the used device space in the range */
1268 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1269 u64 end, u64 *length)
1271 struct btrfs_key key;
1272 struct btrfs_root *root = device->fs_info->dev_root;
1273 struct btrfs_dev_extent *dev_extent;
1274 struct btrfs_path *path;
1278 struct extent_buffer *l;
1282 if (start >= device->total_bytes ||
1283 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1286 path = btrfs_alloc_path();
1289 path->reada = READA_FORWARD;
1291 key.objectid = device->devid;
1293 key.type = BTRFS_DEV_EXTENT_KEY;
1295 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1299 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1306 slot = path->slots[0];
1307 if (slot >= btrfs_header_nritems(l)) {
1308 ret = btrfs_next_leaf(root, path);
1316 btrfs_item_key_to_cpu(l, &key, slot);
1318 if (key.objectid < device->devid)
1321 if (key.objectid > device->devid)
1324 if (key.type != BTRFS_DEV_EXTENT_KEY)
1327 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1328 extent_end = key.offset + btrfs_dev_extent_length(l,
1330 if (key.offset <= start && extent_end > end) {
1331 *length = end - start + 1;
1333 } else if (key.offset <= start && extent_end > start)
1334 *length += extent_end - start;
1335 else if (key.offset > start && extent_end <= end)
1336 *length += extent_end - key.offset;
1337 else if (key.offset > start && key.offset <= end) {
1338 *length += end - key.offset + 1;
1340 } else if (key.offset > end)
1348 btrfs_free_path(path);
1352 static int contains_pending_extent(struct btrfs_transaction *transaction,
1353 struct btrfs_device *device,
1354 u64 *start, u64 len)
1356 struct btrfs_fs_info *fs_info = device->fs_info;
1357 struct extent_map *em;
1358 struct list_head *search_list = &fs_info->pinned_chunks;
1360 u64 physical_start = *start;
1363 search_list = &transaction->pending_chunks;
1365 list_for_each_entry(em, search_list, list) {
1366 struct map_lookup *map;
1369 map = em->map_lookup;
1370 for (i = 0; i < map->num_stripes; i++) {
1373 if (map->stripes[i].dev != device)
1375 if (map->stripes[i].physical >= physical_start + len ||
1376 map->stripes[i].physical + em->orig_block_len <=
1380 * Make sure that while processing the pinned list we do
1381 * not override our *start with a lower value, because
1382 * we can have pinned chunks that fall within this
1383 * device hole and that have lower physical addresses
1384 * than the pending chunks we processed before. If we
1385 * do not take this special care we can end up getting
1386 * 2 pending chunks that start at the same physical
1387 * device offsets because the end offset of a pinned
1388 * chunk can be equal to the start offset of some
1391 end = map->stripes[i].physical + em->orig_block_len;
1398 if (search_list != &fs_info->pinned_chunks) {
1399 search_list = &fs_info->pinned_chunks;
1408 * find_free_dev_extent_start - find free space in the specified device
1409 * @device: the device which we search the free space in
1410 * @num_bytes: the size of the free space that we need
1411 * @search_start: the position from which to begin the search
1412 * @start: store the start of the free space.
1413 * @len: the size of the free space. that we find, or the size
1414 * of the max free space if we don't find suitable free space
1416 * this uses a pretty simple search, the expectation is that it is
1417 * called very infrequently and that a given device has a small number
1420 * @start is used to store the start of the free space if we find. But if we
1421 * don't find suitable free space, it will be used to store the start position
1422 * of the max free space.
1424 * @len is used to store the size of the free space that we find.
1425 * But if we don't find suitable free space, it is used to store the size of
1426 * the max free space.
1428 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1429 struct btrfs_device *device, u64 num_bytes,
1430 u64 search_start, u64 *start, u64 *len)
1432 struct btrfs_fs_info *fs_info = device->fs_info;
1433 struct btrfs_root *root = fs_info->dev_root;
1434 struct btrfs_key key;
1435 struct btrfs_dev_extent *dev_extent;
1436 struct btrfs_path *path;
1441 u64 search_end = device->total_bytes;
1444 struct extent_buffer *l;
1447 * We don't want to overwrite the superblock on the drive nor any area
1448 * used by the boot loader (grub for example), so we make sure to start
1449 * at an offset of at least 1MB.
1451 search_start = max_t(u64, search_start, SZ_1M);
1453 path = btrfs_alloc_path();
1457 max_hole_start = search_start;
1461 if (search_start >= search_end ||
1462 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1467 path->reada = READA_FORWARD;
1468 path->search_commit_root = 1;
1469 path->skip_locking = 1;
1471 key.objectid = device->devid;
1472 key.offset = search_start;
1473 key.type = BTRFS_DEV_EXTENT_KEY;
1475 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1479 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1486 slot = path->slots[0];
1487 if (slot >= btrfs_header_nritems(l)) {
1488 ret = btrfs_next_leaf(root, path);
1496 btrfs_item_key_to_cpu(l, &key, slot);
1498 if (key.objectid < device->devid)
1501 if (key.objectid > device->devid)
1504 if (key.type != BTRFS_DEV_EXTENT_KEY)
1507 if (key.offset > search_start) {
1508 hole_size = key.offset - search_start;
1511 * Have to check before we set max_hole_start, otherwise
1512 * we could end up sending back this offset anyway.
1514 if (contains_pending_extent(transaction, device,
1517 if (key.offset >= search_start) {
1518 hole_size = key.offset - search_start;
1525 if (hole_size > max_hole_size) {
1526 max_hole_start = search_start;
1527 max_hole_size = hole_size;
1531 * If this free space is greater than which we need,
1532 * it must be the max free space that we have found
1533 * until now, so max_hole_start must point to the start
1534 * of this free space and the length of this free space
1535 * is stored in max_hole_size. Thus, we return
1536 * max_hole_start and max_hole_size and go back to the
1539 if (hole_size >= num_bytes) {
1545 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1546 extent_end = key.offset + btrfs_dev_extent_length(l,
1548 if (extent_end > search_start)
1549 search_start = extent_end;
1556 * At this point, search_start should be the end of
1557 * allocated dev extents, and when shrinking the device,
1558 * search_end may be smaller than search_start.
1560 if (search_end > search_start) {
1561 hole_size = search_end - search_start;
1563 if (contains_pending_extent(transaction, device, &search_start,
1565 btrfs_release_path(path);
1569 if (hole_size > max_hole_size) {
1570 max_hole_start = search_start;
1571 max_hole_size = hole_size;
1576 if (max_hole_size < num_bytes)
1582 btrfs_free_path(path);
1583 *start = max_hole_start;
1585 *len = max_hole_size;
1589 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1590 struct btrfs_device *device, u64 num_bytes,
1591 u64 *start, u64 *len)
1593 /* FIXME use last free of some kind */
1594 return find_free_dev_extent_start(trans->transaction, device,
1595 num_bytes, 0, start, len);
1598 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1599 struct btrfs_device *device,
1600 u64 start, u64 *dev_extent_len)
1602 struct btrfs_fs_info *fs_info = device->fs_info;
1603 struct btrfs_root *root = fs_info->dev_root;
1605 struct btrfs_path *path;
1606 struct btrfs_key key;
1607 struct btrfs_key found_key;
1608 struct extent_buffer *leaf = NULL;
1609 struct btrfs_dev_extent *extent = NULL;
1611 path = btrfs_alloc_path();
1615 key.objectid = device->devid;
1617 key.type = BTRFS_DEV_EXTENT_KEY;
1619 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1621 ret = btrfs_previous_item(root, path, key.objectid,
1622 BTRFS_DEV_EXTENT_KEY);
1625 leaf = path->nodes[0];
1626 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1627 extent = btrfs_item_ptr(leaf, path->slots[0],
1628 struct btrfs_dev_extent);
1629 BUG_ON(found_key.offset > start || found_key.offset +
1630 btrfs_dev_extent_length(leaf, extent) < start);
1632 btrfs_release_path(path);
1634 } else if (ret == 0) {
1635 leaf = path->nodes[0];
1636 extent = btrfs_item_ptr(leaf, path->slots[0],
1637 struct btrfs_dev_extent);
1639 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1643 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1645 ret = btrfs_del_item(trans, root, path);
1647 btrfs_handle_fs_error(fs_info, ret,
1648 "Failed to remove dev extent item");
1650 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1653 btrfs_free_path(path);
1657 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1658 struct btrfs_device *device,
1659 u64 chunk_offset, u64 start, u64 num_bytes)
1662 struct btrfs_path *path;
1663 struct btrfs_fs_info *fs_info = device->fs_info;
1664 struct btrfs_root *root = fs_info->dev_root;
1665 struct btrfs_dev_extent *extent;
1666 struct extent_buffer *leaf;
1667 struct btrfs_key key;
1669 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1670 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1671 path = btrfs_alloc_path();
1675 key.objectid = device->devid;
1677 key.type = BTRFS_DEV_EXTENT_KEY;
1678 ret = btrfs_insert_empty_item(trans, root, path, &key,
1683 leaf = path->nodes[0];
1684 extent = btrfs_item_ptr(leaf, path->slots[0],
1685 struct btrfs_dev_extent);
1686 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1687 BTRFS_CHUNK_TREE_OBJECTID);
1688 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1689 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1690 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1692 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1693 btrfs_mark_buffer_dirty(leaf);
1695 btrfs_free_path(path);
1699 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1701 struct extent_map_tree *em_tree;
1702 struct extent_map *em;
1706 em_tree = &fs_info->mapping_tree.map_tree;
1707 read_lock(&em_tree->lock);
1708 n = rb_last(&em_tree->map);
1710 em = rb_entry(n, struct extent_map, rb_node);
1711 ret = em->start + em->len;
1713 read_unlock(&em_tree->lock);
1718 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1722 struct btrfs_key key;
1723 struct btrfs_key found_key;
1724 struct btrfs_path *path;
1726 path = btrfs_alloc_path();
1730 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1731 key.type = BTRFS_DEV_ITEM_KEY;
1732 key.offset = (u64)-1;
1734 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1738 BUG_ON(ret == 0); /* Corruption */
1740 ret = btrfs_previous_item(fs_info->chunk_root, path,
1741 BTRFS_DEV_ITEMS_OBJECTID,
1742 BTRFS_DEV_ITEM_KEY);
1746 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1748 *devid_ret = found_key.offset + 1;
1752 btrfs_free_path(path);
1757 * the device information is stored in the chunk root
1758 * the btrfs_device struct should be fully filled in
1760 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1761 struct btrfs_fs_info *fs_info,
1762 struct btrfs_device *device)
1764 struct btrfs_root *root = fs_info->chunk_root;
1766 struct btrfs_path *path;
1767 struct btrfs_dev_item *dev_item;
1768 struct extent_buffer *leaf;
1769 struct btrfs_key key;
1772 path = btrfs_alloc_path();
1776 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1777 key.type = BTRFS_DEV_ITEM_KEY;
1778 key.offset = device->devid;
1780 ret = btrfs_insert_empty_item(trans, root, path, &key,
1785 leaf = path->nodes[0];
1786 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1788 btrfs_set_device_id(leaf, dev_item, device->devid);
1789 btrfs_set_device_generation(leaf, dev_item, 0);
1790 btrfs_set_device_type(leaf, dev_item, device->type);
1791 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1792 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1793 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1794 btrfs_set_device_total_bytes(leaf, dev_item,
1795 btrfs_device_get_disk_total_bytes(device));
1796 btrfs_set_device_bytes_used(leaf, dev_item,
1797 btrfs_device_get_bytes_used(device));
1798 btrfs_set_device_group(leaf, dev_item, 0);
1799 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1800 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1801 btrfs_set_device_start_offset(leaf, dev_item, 0);
1803 ptr = btrfs_device_uuid(dev_item);
1804 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1805 ptr = btrfs_device_fsid(dev_item);
1806 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1807 btrfs_mark_buffer_dirty(leaf);
1811 btrfs_free_path(path);
1816 * Function to update ctime/mtime for a given device path.
1817 * Mainly used for ctime/mtime based probe like libblkid.
1819 static void update_dev_time(const char *path_name)
1823 filp = filp_open(path_name, O_RDWR, 0);
1826 file_update_time(filp);
1827 filp_close(filp, NULL);
1830 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1831 struct btrfs_device *device)
1833 struct btrfs_root *root = fs_info->chunk_root;
1835 struct btrfs_path *path;
1836 struct btrfs_key key;
1837 struct btrfs_trans_handle *trans;
1839 path = btrfs_alloc_path();
1843 trans = btrfs_start_transaction(root, 0);
1844 if (IS_ERR(trans)) {
1845 btrfs_free_path(path);
1846 return PTR_ERR(trans);
1848 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1849 key.type = BTRFS_DEV_ITEM_KEY;
1850 key.offset = device->devid;
1852 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1856 btrfs_abort_transaction(trans, ret);
1857 btrfs_end_transaction(trans);
1861 ret = btrfs_del_item(trans, root, path);
1863 btrfs_abort_transaction(trans, ret);
1864 btrfs_end_transaction(trans);
1868 btrfs_free_path(path);
1870 ret = btrfs_commit_transaction(trans);
1875 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1876 * filesystem. It's up to the caller to adjust that number regarding eg. device
1879 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1887 seq = read_seqbegin(&fs_info->profiles_lock);
1889 all_avail = fs_info->avail_data_alloc_bits |
1890 fs_info->avail_system_alloc_bits |
1891 fs_info->avail_metadata_alloc_bits;
1892 } while (read_seqretry(&fs_info->profiles_lock, seq));
1894 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1895 if (!(all_avail & btrfs_raid_group[i]))
1898 if (num_devices < btrfs_raid_array[i].devs_min) {
1899 int ret = btrfs_raid_mindev_error[i];
1909 static struct btrfs_device * btrfs_find_next_active_device(
1910 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1912 struct btrfs_device *next_device;
1914 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1915 if (next_device != device &&
1916 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1917 && next_device->bdev)
1925 * Helper function to check if the given device is part of s_bdev / latest_bdev
1926 * and replace it with the provided or the next active device, in the context
1927 * where this function called, there should be always be another device (or
1928 * this_dev) which is active.
1930 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1931 struct btrfs_device *device, struct btrfs_device *this_dev)
1933 struct btrfs_device *next_device;
1936 next_device = this_dev;
1938 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1940 ASSERT(next_device);
1942 if (fs_info->sb->s_bdev &&
1943 (fs_info->sb->s_bdev == device->bdev))
1944 fs_info->sb->s_bdev = next_device->bdev;
1946 if (fs_info->fs_devices->latest_bdev == device->bdev)
1947 fs_info->fs_devices->latest_bdev = next_device->bdev;
1950 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1953 struct btrfs_device *device;
1954 struct btrfs_fs_devices *cur_devices;
1958 mutex_lock(&fs_info->volume_mutex);
1959 mutex_lock(&uuid_mutex);
1961 num_devices = fs_info->fs_devices->num_devices;
1962 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1963 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1964 WARN_ON(num_devices < 1);
1967 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1969 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1973 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1978 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1979 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1983 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1984 fs_info->fs_devices->rw_devices == 1) {
1985 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1989 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1990 mutex_lock(&fs_info->chunk_mutex);
1991 list_del_init(&device->dev_alloc_list);
1992 device->fs_devices->rw_devices--;
1993 mutex_unlock(&fs_info->chunk_mutex);
1996 mutex_unlock(&uuid_mutex);
1997 ret = btrfs_shrink_device(device, 0);
1998 mutex_lock(&uuid_mutex);
2003 * TODO: the superblock still includes this device in its num_devices
2004 * counter although write_all_supers() is not locked out. This
2005 * could give a filesystem state which requires a degraded mount.
2007 ret = btrfs_rm_dev_item(fs_info, device);
2011 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2012 btrfs_scrub_cancel_dev(fs_info, device);
2015 * the device list mutex makes sure that we don't change
2016 * the device list while someone else is writing out all
2017 * the device supers. Whoever is writing all supers, should
2018 * lock the device list mutex before getting the number of
2019 * devices in the super block (super_copy). Conversely,
2020 * whoever updates the number of devices in the super block
2021 * (super_copy) should hold the device list mutex.
2024 cur_devices = device->fs_devices;
2025 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2026 list_del_rcu(&device->dev_list);
2028 device->fs_devices->num_devices--;
2029 device->fs_devices->total_devices--;
2031 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2032 device->fs_devices->missing_devices--;
2034 btrfs_assign_next_active_device(fs_info, device, NULL);
2037 device->fs_devices->open_devices--;
2038 /* remove sysfs entry */
2039 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2042 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2043 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2044 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2047 * at this point, the device is zero sized and detached from
2048 * the devices list. All that's left is to zero out the old
2049 * supers and free the device.
2051 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2052 btrfs_scratch_superblocks(device->bdev, device->name->str);
2054 btrfs_close_bdev(device);
2055 call_rcu(&device->rcu, free_device_rcu);
2057 if (cur_devices->open_devices == 0) {
2058 struct btrfs_fs_devices *fs_devices;
2059 fs_devices = fs_info->fs_devices;
2060 while (fs_devices) {
2061 if (fs_devices->seed == cur_devices) {
2062 fs_devices->seed = cur_devices->seed;
2065 fs_devices = fs_devices->seed;
2067 cur_devices->seed = NULL;
2068 __btrfs_close_devices(cur_devices);
2069 free_fs_devices(cur_devices);
2073 mutex_unlock(&uuid_mutex);
2074 mutex_unlock(&fs_info->volume_mutex);
2078 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2079 mutex_lock(&fs_info->chunk_mutex);
2080 list_add(&device->dev_alloc_list,
2081 &fs_info->fs_devices->alloc_list);
2082 device->fs_devices->rw_devices++;
2083 mutex_unlock(&fs_info->chunk_mutex);
2088 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2089 struct btrfs_device *srcdev)
2091 struct btrfs_fs_devices *fs_devices;
2093 lockdep_assert_held(&fs_info->fs_devices->device_list_mutex);
2096 * in case of fs with no seed, srcdev->fs_devices will point
2097 * to fs_devices of fs_info. However when the dev being replaced is
2098 * a seed dev it will point to the seed's local fs_devices. In short
2099 * srcdev will have its correct fs_devices in both the cases.
2101 fs_devices = srcdev->fs_devices;
2103 list_del_rcu(&srcdev->dev_list);
2104 list_del(&srcdev->dev_alloc_list);
2105 fs_devices->num_devices--;
2106 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2107 fs_devices->missing_devices--;
2109 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2110 fs_devices->rw_devices--;
2113 fs_devices->open_devices--;
2116 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2117 struct btrfs_device *srcdev)
2119 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2121 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2122 /* zero out the old super if it is writable */
2123 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2126 btrfs_close_bdev(srcdev);
2127 call_rcu(&srcdev->rcu, free_device_rcu);
2129 /* if this is no devs we rather delete the fs_devices */
2130 if (!fs_devices->num_devices) {
2131 struct btrfs_fs_devices *tmp_fs_devices;
2134 * On a mounted FS, num_devices can't be zero unless it's a
2135 * seed. In case of a seed device being replaced, the replace
2136 * target added to the sprout FS, so there will be no more
2137 * device left under the seed FS.
2139 ASSERT(fs_devices->seeding);
2141 tmp_fs_devices = fs_info->fs_devices;
2142 while (tmp_fs_devices) {
2143 if (tmp_fs_devices->seed == fs_devices) {
2144 tmp_fs_devices->seed = fs_devices->seed;
2147 tmp_fs_devices = tmp_fs_devices->seed;
2149 fs_devices->seed = NULL;
2150 __btrfs_close_devices(fs_devices);
2151 free_fs_devices(fs_devices);
2155 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2156 struct btrfs_device *tgtdev)
2158 mutex_lock(&uuid_mutex);
2160 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2162 btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2165 fs_info->fs_devices->open_devices--;
2167 fs_info->fs_devices->num_devices--;
2169 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2171 list_del_rcu(&tgtdev->dev_list);
2173 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2174 mutex_unlock(&uuid_mutex);
2177 * The update_dev_time() with in btrfs_scratch_superblocks()
2178 * may lead to a call to btrfs_show_devname() which will try
2179 * to hold device_list_mutex. And here this device
2180 * is already out of device list, so we don't have to hold
2181 * the device_list_mutex lock.
2183 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2185 btrfs_close_bdev(tgtdev);
2186 call_rcu(&tgtdev->rcu, free_device_rcu);
2189 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2190 const char *device_path,
2191 struct btrfs_device **device)
2194 struct btrfs_super_block *disk_super;
2197 struct block_device *bdev;
2198 struct buffer_head *bh;
2201 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2202 fs_info->bdev_holder, 0, &bdev, &bh);
2205 disk_super = (struct btrfs_super_block *)bh->b_data;
2206 devid = btrfs_stack_device_id(&disk_super->dev_item);
2207 dev_uuid = disk_super->dev_item.uuid;
2208 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2212 blkdev_put(bdev, FMODE_READ);
2216 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2217 const char *device_path,
2218 struct btrfs_device **device)
2221 if (strcmp(device_path, "missing") == 0) {
2222 struct list_head *devices;
2223 struct btrfs_device *tmp;
2225 devices = &fs_info->fs_devices->devices;
2227 * It is safe to read the devices since the volume_mutex
2228 * is held by the caller.
2230 list_for_each_entry(tmp, devices, dev_list) {
2231 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2232 &tmp->dev_state) && !tmp->bdev) {
2239 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2243 return btrfs_find_device_by_path(fs_info, device_path, device);
2248 * Lookup a device given by device id, or the path if the id is 0.
2250 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2251 const char *devpath,
2252 struct btrfs_device **device)
2258 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2262 if (!devpath || !devpath[0])
2265 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2272 * does all the dirty work required for changing file system's UUID.
2274 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2276 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2277 struct btrfs_fs_devices *old_devices;
2278 struct btrfs_fs_devices *seed_devices;
2279 struct btrfs_super_block *disk_super = fs_info->super_copy;
2280 struct btrfs_device *device;
2283 lockdep_assert_held(&uuid_mutex);
2284 if (!fs_devices->seeding)
2287 seed_devices = alloc_fs_devices(NULL);
2288 if (IS_ERR(seed_devices))
2289 return PTR_ERR(seed_devices);
2291 old_devices = clone_fs_devices(fs_devices);
2292 if (IS_ERR(old_devices)) {
2293 kfree(seed_devices);
2294 return PTR_ERR(old_devices);
2297 list_add(&old_devices->list, &fs_uuids);
2299 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2300 seed_devices->opened = 1;
2301 INIT_LIST_HEAD(&seed_devices->devices);
2302 INIT_LIST_HEAD(&seed_devices->alloc_list);
2303 mutex_init(&seed_devices->device_list_mutex);
2305 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2306 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2308 list_for_each_entry(device, &seed_devices->devices, dev_list)
2309 device->fs_devices = seed_devices;
2311 mutex_lock(&fs_info->chunk_mutex);
2312 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2313 mutex_unlock(&fs_info->chunk_mutex);
2315 fs_devices->seeding = 0;
2316 fs_devices->num_devices = 0;
2317 fs_devices->open_devices = 0;
2318 fs_devices->missing_devices = 0;
2319 fs_devices->rotating = 0;
2320 fs_devices->seed = seed_devices;
2322 generate_random_uuid(fs_devices->fsid);
2323 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2324 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2325 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2327 super_flags = btrfs_super_flags(disk_super) &
2328 ~BTRFS_SUPER_FLAG_SEEDING;
2329 btrfs_set_super_flags(disk_super, super_flags);
2335 * Store the expected generation for seed devices in device items.
2337 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2338 struct btrfs_fs_info *fs_info)
2340 struct btrfs_root *root = fs_info->chunk_root;
2341 struct btrfs_path *path;
2342 struct extent_buffer *leaf;
2343 struct btrfs_dev_item *dev_item;
2344 struct btrfs_device *device;
2345 struct btrfs_key key;
2346 u8 fs_uuid[BTRFS_FSID_SIZE];
2347 u8 dev_uuid[BTRFS_UUID_SIZE];
2351 path = btrfs_alloc_path();
2355 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2357 key.type = BTRFS_DEV_ITEM_KEY;
2360 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2364 leaf = path->nodes[0];
2366 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2367 ret = btrfs_next_leaf(root, path);
2372 leaf = path->nodes[0];
2373 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2374 btrfs_release_path(path);
2378 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2379 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2380 key.type != BTRFS_DEV_ITEM_KEY)
2383 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2384 struct btrfs_dev_item);
2385 devid = btrfs_device_id(leaf, dev_item);
2386 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2388 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2390 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2391 BUG_ON(!device); /* Logic error */
2393 if (device->fs_devices->seeding) {
2394 btrfs_set_device_generation(leaf, dev_item,
2395 device->generation);
2396 btrfs_mark_buffer_dirty(leaf);
2404 btrfs_free_path(path);
2408 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2410 struct btrfs_root *root = fs_info->dev_root;
2411 struct request_queue *q;
2412 struct btrfs_trans_handle *trans;
2413 struct btrfs_device *device;
2414 struct block_device *bdev;
2415 struct list_head *devices;
2416 struct super_block *sb = fs_info->sb;
2417 struct rcu_string *name;
2419 int seeding_dev = 0;
2421 bool unlocked = false;
2423 if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2426 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2427 fs_info->bdev_holder);
2429 return PTR_ERR(bdev);
2431 if (fs_info->fs_devices->seeding) {
2433 down_write(&sb->s_umount);
2434 mutex_lock(&uuid_mutex);
2437 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2439 devices = &fs_info->fs_devices->devices;
2441 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2442 list_for_each_entry(device, devices, dev_list) {
2443 if (device->bdev == bdev) {
2446 &fs_info->fs_devices->device_list_mutex);
2450 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2452 device = btrfs_alloc_device(fs_info, NULL, NULL);
2453 if (IS_ERR(device)) {
2454 /* we can safely leave the fs_devices entry around */
2455 ret = PTR_ERR(device);
2459 name = rcu_string_strdup(device_path, GFP_KERNEL);
2462 goto error_free_device;
2464 rcu_assign_pointer(device->name, name);
2466 trans = btrfs_start_transaction(root, 0);
2467 if (IS_ERR(trans)) {
2468 ret = PTR_ERR(trans);
2469 goto error_free_device;
2472 q = bdev_get_queue(bdev);
2473 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2474 device->generation = trans->transid;
2475 device->io_width = fs_info->sectorsize;
2476 device->io_align = fs_info->sectorsize;
2477 device->sector_size = fs_info->sectorsize;
2478 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2479 fs_info->sectorsize);
2480 device->disk_total_bytes = device->total_bytes;
2481 device->commit_total_bytes = device->total_bytes;
2482 device->fs_info = fs_info;
2483 device->bdev = bdev;
2484 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2485 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2486 device->mode = FMODE_EXCL;
2487 device->dev_stats_valid = 1;
2488 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2491 sb->s_flags &= ~SB_RDONLY;
2492 ret = btrfs_prepare_sprout(fs_info);
2494 btrfs_abort_transaction(trans, ret);
2499 device->fs_devices = fs_info->fs_devices;
2501 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2502 mutex_lock(&fs_info->chunk_mutex);
2503 list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2504 list_add(&device->dev_alloc_list,
2505 &fs_info->fs_devices->alloc_list);
2506 fs_info->fs_devices->num_devices++;
2507 fs_info->fs_devices->open_devices++;
2508 fs_info->fs_devices->rw_devices++;
2509 fs_info->fs_devices->total_devices++;
2510 fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2512 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2514 if (!blk_queue_nonrot(q))
2515 fs_info->fs_devices->rotating = 1;
2517 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2518 btrfs_set_super_total_bytes(fs_info->super_copy,
2519 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2521 tmp = btrfs_super_num_devices(fs_info->super_copy);
2522 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2524 /* add sysfs device entry */
2525 btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2528 * we've got more storage, clear any full flags on the space
2531 btrfs_clear_space_info_full(fs_info);
2533 mutex_unlock(&fs_info->chunk_mutex);
2534 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2537 mutex_lock(&fs_info->chunk_mutex);
2538 ret = init_first_rw_device(trans, fs_info);
2539 mutex_unlock(&fs_info->chunk_mutex);
2541 btrfs_abort_transaction(trans, ret);
2546 ret = btrfs_add_dev_item(trans, fs_info, device);
2548 btrfs_abort_transaction(trans, ret);
2553 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2555 ret = btrfs_finish_sprout(trans, fs_info);
2557 btrfs_abort_transaction(trans, ret);
2561 /* Sprouting would change fsid of the mounted root,
2562 * so rename the fsid on the sysfs
2564 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2566 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2568 "sysfs: failed to create fsid for sprout");
2571 ret = btrfs_commit_transaction(trans);
2574 mutex_unlock(&uuid_mutex);
2575 up_write(&sb->s_umount);
2578 if (ret) /* transaction commit */
2581 ret = btrfs_relocate_sys_chunks(fs_info);
2583 btrfs_handle_fs_error(fs_info, ret,
2584 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2585 trans = btrfs_attach_transaction(root);
2586 if (IS_ERR(trans)) {
2587 if (PTR_ERR(trans) == -ENOENT)
2589 ret = PTR_ERR(trans);
2593 ret = btrfs_commit_transaction(trans);
2596 /* Update ctime/mtime for libblkid */
2597 update_dev_time(device_path);
2601 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2604 sb->s_flags |= SB_RDONLY;
2606 btrfs_end_transaction(trans);
2608 free_device(device);
2610 blkdev_put(bdev, FMODE_EXCL);
2611 if (seeding_dev && !unlocked) {
2612 mutex_unlock(&uuid_mutex);
2613 up_write(&sb->s_umount);
2618 int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2619 const char *device_path,
2620 struct btrfs_device *srcdev,
2621 struct btrfs_device **device_out)
2623 struct btrfs_device *device;
2624 struct block_device *bdev;
2625 struct list_head *devices;
2626 struct rcu_string *name;
2627 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2631 if (fs_info->fs_devices->seeding) {
2632 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2636 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2637 fs_info->bdev_holder);
2639 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2640 return PTR_ERR(bdev);
2643 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2645 devices = &fs_info->fs_devices->devices;
2646 list_for_each_entry(device, devices, dev_list) {
2647 if (device->bdev == bdev) {
2649 "target device is in the filesystem!");
2656 if (i_size_read(bdev->bd_inode) <
2657 btrfs_device_get_total_bytes(srcdev)) {
2659 "target device is smaller than source device!");
2665 device = btrfs_alloc_device(NULL, &devid, NULL);
2666 if (IS_ERR(device)) {
2667 ret = PTR_ERR(device);
2671 name = rcu_string_strdup(device_path, GFP_KERNEL);
2673 free_device(device);
2677 rcu_assign_pointer(device->name, name);
2679 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2680 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2681 device->generation = 0;
2682 device->io_width = fs_info->sectorsize;
2683 device->io_align = fs_info->sectorsize;
2684 device->sector_size = fs_info->sectorsize;
2685 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2686 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2687 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2688 device->commit_total_bytes = srcdev->commit_total_bytes;
2689 device->commit_bytes_used = device->bytes_used;
2690 device->fs_info = fs_info;
2691 device->bdev = bdev;
2692 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2693 set_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2694 device->mode = FMODE_EXCL;
2695 device->dev_stats_valid = 1;
2696 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2697 device->fs_devices = fs_info->fs_devices;
2698 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2699 fs_info->fs_devices->num_devices++;
2700 fs_info->fs_devices->open_devices++;
2701 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2703 *device_out = device;
2707 blkdev_put(bdev, FMODE_EXCL);
2711 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2712 struct btrfs_device *device)
2715 struct btrfs_path *path;
2716 struct btrfs_root *root = device->fs_info->chunk_root;
2717 struct btrfs_dev_item *dev_item;
2718 struct extent_buffer *leaf;
2719 struct btrfs_key key;
2721 path = btrfs_alloc_path();
2725 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2726 key.type = BTRFS_DEV_ITEM_KEY;
2727 key.offset = device->devid;
2729 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2738 leaf = path->nodes[0];
2739 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2741 btrfs_set_device_id(leaf, dev_item, device->devid);
2742 btrfs_set_device_type(leaf, dev_item, device->type);
2743 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2744 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2745 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2746 btrfs_set_device_total_bytes(leaf, dev_item,
2747 btrfs_device_get_disk_total_bytes(device));
2748 btrfs_set_device_bytes_used(leaf, dev_item,
2749 btrfs_device_get_bytes_used(device));
2750 btrfs_mark_buffer_dirty(leaf);
2753 btrfs_free_path(path);
2757 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2758 struct btrfs_device *device, u64 new_size)
2760 struct btrfs_fs_info *fs_info = device->fs_info;
2761 struct btrfs_super_block *super_copy = fs_info->super_copy;
2762 struct btrfs_fs_devices *fs_devices;
2766 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2769 new_size = round_down(new_size, fs_info->sectorsize);
2771 mutex_lock(&fs_info->chunk_mutex);
2772 old_total = btrfs_super_total_bytes(super_copy);
2773 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2775 if (new_size <= device->total_bytes ||
2776 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2777 mutex_unlock(&fs_info->chunk_mutex);
2781 fs_devices = fs_info->fs_devices;
2783 btrfs_set_super_total_bytes(super_copy,
2784 round_down(old_total + diff, fs_info->sectorsize));
2785 device->fs_devices->total_rw_bytes += diff;
2787 btrfs_device_set_total_bytes(device, new_size);
2788 btrfs_device_set_disk_total_bytes(device, new_size);
2789 btrfs_clear_space_info_full(device->fs_info);
2790 if (list_empty(&device->resized_list))
2791 list_add_tail(&device->resized_list,
2792 &fs_devices->resized_devices);
2793 mutex_unlock(&fs_info->chunk_mutex);
2795 return btrfs_update_device(trans, device);
2798 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2799 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2801 struct btrfs_root *root = fs_info->chunk_root;
2803 struct btrfs_path *path;
2804 struct btrfs_key key;
2806 path = btrfs_alloc_path();
2810 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2811 key.offset = chunk_offset;
2812 key.type = BTRFS_CHUNK_ITEM_KEY;
2814 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2817 else if (ret > 0) { /* Logic error or corruption */
2818 btrfs_handle_fs_error(fs_info, -ENOENT,
2819 "Failed lookup while freeing chunk.");
2824 ret = btrfs_del_item(trans, root, path);
2826 btrfs_handle_fs_error(fs_info, ret,
2827 "Failed to delete chunk item.");
2829 btrfs_free_path(path);
2833 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2835 struct btrfs_super_block *super_copy = fs_info->super_copy;
2836 struct btrfs_disk_key *disk_key;
2837 struct btrfs_chunk *chunk;
2844 struct btrfs_key key;
2846 mutex_lock(&fs_info->chunk_mutex);
2847 array_size = btrfs_super_sys_array_size(super_copy);
2849 ptr = super_copy->sys_chunk_array;
2852 while (cur < array_size) {
2853 disk_key = (struct btrfs_disk_key *)ptr;
2854 btrfs_disk_key_to_cpu(&key, disk_key);
2856 len = sizeof(*disk_key);
2858 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2859 chunk = (struct btrfs_chunk *)(ptr + len);
2860 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2861 len += btrfs_chunk_item_size(num_stripes);
2866 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2867 key.offset == chunk_offset) {
2868 memmove(ptr, ptr + len, array_size - (cur + len));
2870 btrfs_set_super_sys_array_size(super_copy, array_size);
2876 mutex_unlock(&fs_info->chunk_mutex);
2880 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2881 u64 logical, u64 length)
2883 struct extent_map_tree *em_tree;
2884 struct extent_map *em;
2886 em_tree = &fs_info->mapping_tree.map_tree;
2887 read_lock(&em_tree->lock);
2888 em = lookup_extent_mapping(em_tree, logical, length);
2889 read_unlock(&em_tree->lock);
2892 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2894 return ERR_PTR(-EINVAL);
2897 if (em->start > logical || em->start + em->len < logical) {
2899 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2900 logical, length, em->start, em->start + em->len);
2901 free_extent_map(em);
2902 return ERR_PTR(-EINVAL);
2905 /* callers are responsible for dropping em's ref. */
2909 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2910 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2912 struct extent_map *em;
2913 struct map_lookup *map;
2914 u64 dev_extent_len = 0;
2916 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2918 em = get_chunk_map(fs_info, chunk_offset, 1);
2921 * This is a logic error, but we don't want to just rely on the
2922 * user having built with ASSERT enabled, so if ASSERT doesn't
2923 * do anything we still error out.
2928 map = em->map_lookup;
2929 mutex_lock(&fs_info->chunk_mutex);
2930 check_system_chunk(trans, fs_info, map->type);
2931 mutex_unlock(&fs_info->chunk_mutex);
2934 * Take the device list mutex to prevent races with the final phase of
2935 * a device replace operation that replaces the device object associated
2936 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2938 mutex_lock(&fs_devices->device_list_mutex);
2939 for (i = 0; i < map->num_stripes; i++) {
2940 struct btrfs_device *device = map->stripes[i].dev;
2941 ret = btrfs_free_dev_extent(trans, device,
2942 map->stripes[i].physical,
2945 mutex_unlock(&fs_devices->device_list_mutex);
2946 btrfs_abort_transaction(trans, ret);
2950 if (device->bytes_used > 0) {
2951 mutex_lock(&fs_info->chunk_mutex);
2952 btrfs_device_set_bytes_used(device,
2953 device->bytes_used - dev_extent_len);
2954 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2955 btrfs_clear_space_info_full(fs_info);
2956 mutex_unlock(&fs_info->chunk_mutex);
2959 if (map->stripes[i].dev) {
2960 ret = btrfs_update_device(trans, map->stripes[i].dev);
2962 mutex_unlock(&fs_devices->device_list_mutex);
2963 btrfs_abort_transaction(trans, ret);
2968 mutex_unlock(&fs_devices->device_list_mutex);
2970 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2972 btrfs_abort_transaction(trans, ret);
2976 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2978 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2979 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2981 btrfs_abort_transaction(trans, ret);
2986 ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2988 btrfs_abort_transaction(trans, ret);
2994 free_extent_map(em);
2998 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3000 struct btrfs_root *root = fs_info->chunk_root;
3001 struct btrfs_trans_handle *trans;
3005 * Prevent races with automatic removal of unused block groups.
3006 * After we relocate and before we remove the chunk with offset
3007 * chunk_offset, automatic removal of the block group can kick in,
3008 * resulting in a failure when calling btrfs_remove_chunk() below.
3010 * Make sure to acquire this mutex before doing a tree search (dev
3011 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3012 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3013 * we release the path used to search the chunk/dev tree and before
3014 * the current task acquires this mutex and calls us.
3016 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3018 ret = btrfs_can_relocate(fs_info, chunk_offset);
3022 /* step one, relocate all the extents inside this chunk */
3023 btrfs_scrub_pause(fs_info);
3024 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3025 btrfs_scrub_continue(fs_info);
3030 * We add the kobjects here (and after forcing data chunk creation)
3031 * since relocation is the only place we'll create chunks of a new
3032 * type at runtime. The only place where we'll remove the last
3033 * chunk of a type is the call immediately below this one. Even
3034 * so, we're protected against races with the cleaner thread since
3035 * we're covered by the delete_unused_bgs_mutex.
3037 btrfs_add_raid_kobjects(fs_info);
3039 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3041 if (IS_ERR(trans)) {
3042 ret = PTR_ERR(trans);
3043 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3048 * step two, delete the device extents and the
3049 * chunk tree entries
3051 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
3052 btrfs_end_transaction(trans);
3056 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3058 struct btrfs_root *chunk_root = fs_info->chunk_root;
3059 struct btrfs_path *path;
3060 struct extent_buffer *leaf;
3061 struct btrfs_chunk *chunk;
3062 struct btrfs_key key;
3063 struct btrfs_key found_key;
3065 bool retried = false;
3069 path = btrfs_alloc_path();
3074 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3075 key.offset = (u64)-1;
3076 key.type = BTRFS_CHUNK_ITEM_KEY;
3079 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3080 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3082 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3085 BUG_ON(ret == 0); /* Corruption */
3087 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3090 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3096 leaf = path->nodes[0];
3097 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3099 chunk = btrfs_item_ptr(leaf, path->slots[0],
3100 struct btrfs_chunk);
3101 chunk_type = btrfs_chunk_type(leaf, chunk);
3102 btrfs_release_path(path);
3104 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3105 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3111 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3113 if (found_key.offset == 0)
3115 key.offset = found_key.offset - 1;
3118 if (failed && !retried) {
3122 } else if (WARN_ON(failed && retried)) {
3126 btrfs_free_path(path);
3131 * return 1 : allocate a data chunk successfully,
3132 * return <0: errors during allocating a data chunk,
3133 * return 0 : no need to allocate a data chunk.
3135 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3138 struct btrfs_block_group_cache *cache;
3142 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3144 chunk_type = cache->flags;
3145 btrfs_put_block_group(cache);
3147 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3148 spin_lock(&fs_info->data_sinfo->lock);
3149 bytes_used = fs_info->data_sinfo->bytes_used;
3150 spin_unlock(&fs_info->data_sinfo->lock);
3153 struct btrfs_trans_handle *trans;
3156 trans = btrfs_join_transaction(fs_info->tree_root);
3158 return PTR_ERR(trans);
3160 ret = btrfs_force_chunk_alloc(trans, fs_info,
3161 BTRFS_BLOCK_GROUP_DATA);
3162 btrfs_end_transaction(trans);
3166 btrfs_add_raid_kobjects(fs_info);
3174 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3175 struct btrfs_balance_control *bctl)
3177 struct btrfs_root *root = fs_info->tree_root;
3178 struct btrfs_trans_handle *trans;
3179 struct btrfs_balance_item *item;
3180 struct btrfs_disk_balance_args disk_bargs;
3181 struct btrfs_path *path;
3182 struct extent_buffer *leaf;
3183 struct btrfs_key key;
3186 path = btrfs_alloc_path();
3190 trans = btrfs_start_transaction(root, 0);
3191 if (IS_ERR(trans)) {
3192 btrfs_free_path(path);
3193 return PTR_ERR(trans);
3196 key.objectid = BTRFS_BALANCE_OBJECTID;
3197 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3200 ret = btrfs_insert_empty_item(trans, root, path, &key,
3205 leaf = path->nodes[0];
3206 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3208 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3210 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3211 btrfs_set_balance_data(leaf, item, &disk_bargs);
3212 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3213 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3214 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3215 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3217 btrfs_set_balance_flags(leaf, item, bctl->flags);
3219 btrfs_mark_buffer_dirty(leaf);
3221 btrfs_free_path(path);
3222 err = btrfs_commit_transaction(trans);
3228 static int del_balance_item(struct btrfs_fs_info *fs_info)
3230 struct btrfs_root *root = fs_info->tree_root;
3231 struct btrfs_trans_handle *trans;
3232 struct btrfs_path *path;
3233 struct btrfs_key key;
3236 path = btrfs_alloc_path();
3240 trans = btrfs_start_transaction(root, 0);
3241 if (IS_ERR(trans)) {
3242 btrfs_free_path(path);
3243 return PTR_ERR(trans);