1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
8 #include <linux/slab.h>
9 #include <linux/buffer_head.h>
10 #include <linux/blkdev.h>
11 #include <linux/ratelimit.h>
12 #include <linux/kthread.h>
13 #include <linux/raid/pq.h>
14 #include <linux/semaphore.h>
15 #include <linux/uuid.h>
16 #include <linux/list_sort.h>
18 #include "extent_map.h"
20 #include "transaction.h"
21 #include "print-tree.h"
24 #include "async-thread.h"
25 #include "check-integrity.h"
26 #include "rcu-string.h"
28 #include "dev-replace.h"
31 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
32 [BTRFS_RAID_RAID10] = {
35 .devs_max = 0, /* 0 == as many as possible */
37 .tolerated_failures = 1,
41 .raid_name = "raid10",
42 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
43 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
45 [BTRFS_RAID_RAID1] = {
50 .tolerated_failures = 1,
55 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
56 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
63 .tolerated_failures = 0,
68 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
71 [BTRFS_RAID_RAID0] = {
76 .tolerated_failures = 0,
81 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
84 [BTRFS_RAID_SINGLE] = {
89 .tolerated_failures = 0,
93 .raid_name = "single",
97 [BTRFS_RAID_RAID5] = {
102 .tolerated_failures = 1,
106 .raid_name = "raid5",
107 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
108 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
110 [BTRFS_RAID_RAID6] = {
115 .tolerated_failures = 2,
119 .raid_name = "raid6",
120 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
121 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
125 const char *get_raid_name(enum btrfs_raid_types type)
127 if (type >= BTRFS_NR_RAID_TYPES)
130 return btrfs_raid_array[type].raid_name;
133 static int init_first_rw_device(struct btrfs_trans_handle *trans,
134 struct btrfs_fs_info *fs_info);
135 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
136 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
137 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
138 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
139 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
140 enum btrfs_map_op op,
141 u64 logical, u64 *length,
142 struct btrfs_bio **bbio_ret,
143 int mirror_num, int need_raid_map);
149 * There are several mutexes that protect manipulation of devices and low-level
150 * structures like chunks but not block groups, extents or files
152 * uuid_mutex (global lock)
153 * ------------------------
154 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
155 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
156 * device) or requested by the device= mount option
158 * the mutex can be very coarse and can cover long-running operations
160 * protects: updates to fs_devices counters like missing devices, rw devices,
161 * seeding, structure cloning, openning/closing devices at mount/umount time
163 * global::fs_devs - add, remove, updates to the global list
165 * does not protect: manipulation of the fs_devices::devices list!
167 * btrfs_device::name - renames (write side), read is RCU
169 * fs_devices::device_list_mutex (per-fs, with RCU)
170 * ------------------------------------------------
171 * protects updates to fs_devices::devices, ie. adding and deleting
173 * simple list traversal with read-only actions can be done with RCU protection
175 * may be used to exclude some operations from running concurrently without any
176 * modifications to the list (see write_all_supers)
180 * protects balance structures (status, state) and context accessed from
181 * several places (internally, ioctl)
185 * protects chunks, adding or removing during allocation, trim or when a new
186 * device is added/removed
190 * a big lock that is held by the cleaner thread and prevents running subvolume
191 * cleaning together with relocation or delayed iputs
204 * Exclusive operations, BTRFS_FS_EXCL_OP
205 * ======================================
207 * Maintains the exclusivity of the following operations that apply to the
208 * whole filesystem and cannot run in parallel.
213 * - Device replace (*)
216 * The device operations (as above) can be in one of the following states:
222 * Only device operations marked with (*) can go into the Paused state for the
225 * - ioctl (only Balance can be Paused through ioctl)
226 * - filesystem remounted as read-only
227 * - filesystem unmounted and mounted as read-only
228 * - system power-cycle and filesystem mounted as read-only
229 * - filesystem or device errors leading to forced read-only
231 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
232 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
233 * A device operation in Paused or Running state can be canceled or resumed
234 * either by ioctl (Balance only) or when remounted as read-write.
235 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
239 DEFINE_MUTEX(uuid_mutex);
240 static LIST_HEAD(fs_uuids);
241 struct list_head *btrfs_get_fs_uuids(void)
247 * alloc_fs_devices - allocate struct btrfs_fs_devices
248 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
249 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
251 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
252 * The returned struct is not linked onto any lists and can be destroyed with
253 * kfree() right away.
255 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
256 const u8 *metadata_fsid)
258 struct btrfs_fs_devices *fs_devs;
260 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
262 return ERR_PTR(-ENOMEM);
264 mutex_init(&fs_devs->device_list_mutex);
266 INIT_LIST_HEAD(&fs_devs->devices);
267 INIT_LIST_HEAD(&fs_devs->resized_devices);
268 INIT_LIST_HEAD(&fs_devs->alloc_list);
269 INIT_LIST_HEAD(&fs_devs->fs_list);
271 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
274 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
276 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
281 void btrfs_free_device(struct btrfs_device *device)
283 rcu_string_free(device->name);
284 bio_put(device->flush_bio);
288 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
290 struct btrfs_device *device;
291 WARN_ON(fs_devices->opened);
292 while (!list_empty(&fs_devices->devices)) {
293 device = list_entry(fs_devices->devices.next,
294 struct btrfs_device, dev_list);
295 list_del(&device->dev_list);
296 btrfs_free_device(device);
301 static void btrfs_kobject_uevent(struct block_device *bdev,
302 enum kobject_action action)
306 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
308 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
310 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
311 &disk_to_dev(bdev->bd_disk)->kobj);
314 void __exit btrfs_cleanup_fs_uuids(void)
316 struct btrfs_fs_devices *fs_devices;
318 while (!list_empty(&fs_uuids)) {
319 fs_devices = list_entry(fs_uuids.next,
320 struct btrfs_fs_devices, fs_list);
321 list_del(&fs_devices->fs_list);
322 free_fs_devices(fs_devices);
327 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
328 * Returned struct is not linked onto any lists and must be destroyed using
331 static struct btrfs_device *__alloc_device(void)
333 struct btrfs_device *dev;
335 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
337 return ERR_PTR(-ENOMEM);
340 * Preallocate a bio that's always going to be used for flushing device
341 * barriers and matches the device lifespan
343 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
344 if (!dev->flush_bio) {
346 return ERR_PTR(-ENOMEM);
349 INIT_LIST_HEAD(&dev->dev_list);
350 INIT_LIST_HEAD(&dev->dev_alloc_list);
351 INIT_LIST_HEAD(&dev->resized_list);
353 spin_lock_init(&dev->io_lock);
355 atomic_set(&dev->reada_in_flight, 0);
356 atomic_set(&dev->dev_stats_ccnt, 0);
357 btrfs_device_data_ordered_init(dev);
358 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
359 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
365 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
368 * If devid and uuid are both specified, the match must be exact, otherwise
369 * only devid is used.
371 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
372 u64 devid, const u8 *uuid)
374 struct btrfs_device *dev;
376 list_for_each_entry(dev, &fs_devices->devices, dev_list) {
377 if (dev->devid == devid &&
378 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
385 static noinline struct btrfs_fs_devices *find_fsid(
386 const u8 *fsid, const u8 *metadata_fsid)
388 struct btrfs_fs_devices *fs_devices;
392 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
394 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
395 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
396 BTRFS_FSID_SIZE) == 0)
399 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
407 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
408 int flush, struct block_device **bdev,
409 struct buffer_head **bh)
413 *bdev = blkdev_get_by_path(device_path, flags, holder);
416 ret = PTR_ERR(*bdev);
421 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
422 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
424 blkdev_put(*bdev, flags);
427 invalidate_bdev(*bdev);
428 *bh = btrfs_read_dev_super(*bdev);
431 blkdev_put(*bdev, flags);
443 static void requeue_list(struct btrfs_pending_bios *pending_bios,
444 struct bio *head, struct bio *tail)
447 struct bio *old_head;
449 old_head = pending_bios->head;
450 pending_bios->head = head;
451 if (pending_bios->tail)
452 tail->bi_next = old_head;
454 pending_bios->tail = tail;
458 * we try to collect pending bios for a device so we don't get a large
459 * number of procs sending bios down to the same device. This greatly
460 * improves the schedulers ability to collect and merge the bios.
462 * But, it also turns into a long list of bios to process and that is sure
463 * to eventually make the worker thread block. The solution here is to
464 * make some progress and then put this work struct back at the end of
465 * the list if the block device is congested. This way, multiple devices
466 * can make progress from a single worker thread.
468 static noinline void run_scheduled_bios(struct btrfs_device *device)
470 struct btrfs_fs_info *fs_info = device->fs_info;
472 struct backing_dev_info *bdi;
473 struct btrfs_pending_bios *pending_bios;
477 unsigned long num_run;
478 unsigned long batch_run = 0;
479 unsigned long last_waited = 0;
481 int sync_pending = 0;
482 struct blk_plug plug;
485 * this function runs all the bios we've collected for
486 * a particular device. We don't want to wander off to
487 * another device without first sending all of these down.
488 * So, setup a plug here and finish it off before we return
490 blk_start_plug(&plug);
492 bdi = device->bdev->bd_bdi;
495 spin_lock(&device->io_lock);
500 /* take all the bios off the list at once and process them
501 * later on (without the lock held). But, remember the
502 * tail and other pointers so the bios can be properly reinserted
503 * into the list if we hit congestion
505 if (!force_reg && device->pending_sync_bios.head) {
506 pending_bios = &device->pending_sync_bios;
509 pending_bios = &device->pending_bios;
513 pending = pending_bios->head;
514 tail = pending_bios->tail;
515 WARN_ON(pending && !tail);
518 * if pending was null this time around, no bios need processing
519 * at all and we can stop. Otherwise it'll loop back up again
520 * and do an additional check so no bios are missed.
522 * device->running_pending is used to synchronize with the
525 if (device->pending_sync_bios.head == NULL &&
526 device->pending_bios.head == NULL) {
528 device->running_pending = 0;
531 device->running_pending = 1;
534 pending_bios->head = NULL;
535 pending_bios->tail = NULL;
537 spin_unlock(&device->io_lock);
542 /* we want to work on both lists, but do more bios on the
543 * sync list than the regular list
546 pending_bios != &device->pending_sync_bios &&
547 device->pending_sync_bios.head) ||
548 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
549 device->pending_bios.head)) {
550 spin_lock(&device->io_lock);
551 requeue_list(pending_bios, pending, tail);
556 pending = pending->bi_next;
559 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
562 * if we're doing the sync list, record that our
563 * plug has some sync requests on it
565 * If we're doing the regular list and there are
566 * sync requests sitting around, unplug before
569 if (pending_bios == &device->pending_sync_bios) {
571 } else if (sync_pending) {
572 blk_finish_plug(&plug);
573 blk_start_plug(&plug);
577 btrfsic_submit_bio(cur);
584 * we made progress, there is more work to do and the bdi
585 * is now congested. Back off and let other work structs
588 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
589 fs_info->fs_devices->open_devices > 1) {
590 struct io_context *ioc;
592 ioc = current->io_context;
595 * the main goal here is that we don't want to
596 * block if we're going to be able to submit
597 * more requests without blocking.
599 * This code does two great things, it pokes into
600 * the elevator code from a filesystem _and_
601 * it makes assumptions about how batching works.
603 if (ioc && ioc->nr_batch_requests > 0 &&
604 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
606 ioc->last_waited == last_waited)) {
608 * we want to go through our batch of
609 * requests and stop. So, we copy out
610 * the ioc->last_waited time and test
611 * against it before looping
613 last_waited = ioc->last_waited;
617 spin_lock(&device->io_lock);
618 requeue_list(pending_bios, pending, tail);
619 device->running_pending = 1;
621 spin_unlock(&device->io_lock);
622 btrfs_queue_work(fs_info->submit_workers,
632 spin_lock(&device->io_lock);
633 if (device->pending_bios.head || device->pending_sync_bios.head)
635 spin_unlock(&device->io_lock);
638 blk_finish_plug(&plug);
641 static void pending_bios_fn(struct btrfs_work *work)
643 struct btrfs_device *device;
645 device = container_of(work, struct btrfs_device, work);
646 run_scheduled_bios(device);
650 * Search and remove all stale (devices which are not mounted) devices.
651 * When both inputs are NULL, it will search and release all stale devices.
652 * path: Optional. When provided will it release all unmounted devices
653 * matching this path only.
654 * skip_dev: Optional. Will skip this device when searching for the stale
657 static void btrfs_free_stale_devices(const char *path,
658 struct btrfs_device *skip_device)
660 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
661 struct btrfs_device *device, *tmp_device;
663 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
664 mutex_lock(&fs_devices->device_list_mutex);
665 if (fs_devices->opened) {
666 mutex_unlock(&fs_devices->device_list_mutex);
670 list_for_each_entry_safe(device, tmp_device,
671 &fs_devices->devices, dev_list) {
674 if (skip_device && skip_device == device)
676 if (path && !device->name)
681 not_found = strcmp(rcu_str_deref(device->name),
687 /* delete the stale device */
688 fs_devices->num_devices--;
689 list_del(&device->dev_list);
690 btrfs_free_device(device);
692 if (fs_devices->num_devices == 0)
695 mutex_unlock(&fs_devices->device_list_mutex);
696 if (fs_devices->num_devices == 0) {
697 btrfs_sysfs_remove_fsid(fs_devices);
698 list_del(&fs_devices->fs_list);
699 free_fs_devices(fs_devices);
704 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
705 struct btrfs_device *device, fmode_t flags,
708 struct request_queue *q;
709 struct block_device *bdev;
710 struct buffer_head *bh;
711 struct btrfs_super_block *disk_super;
720 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
725 disk_super = (struct btrfs_super_block *)bh->b_data;
726 devid = btrfs_stack_device_id(&disk_super->dev_item);
727 if (devid != device->devid)
730 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
733 device->generation = btrfs_super_generation(disk_super);
735 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
736 if (btrfs_super_incompat_flags(disk_super) &
737 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
739 "BTRFS: Invalid seeding and uuid-changed device detected\n");
743 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
744 fs_devices->seeding = 1;
746 if (bdev_read_only(bdev))
747 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
749 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
752 q = bdev_get_queue(bdev);
753 if (!blk_queue_nonrot(q))
754 fs_devices->rotating = 1;
757 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
758 device->mode = flags;
760 fs_devices->open_devices++;
761 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
762 device->devid != BTRFS_DEV_REPLACE_DEVID) {
763 fs_devices->rw_devices++;
764 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
772 blkdev_put(bdev, flags);
778 * Add new device to list of registered devices
781 * device pointer which was just added or updated when successful
782 * error pointer when failed
784 static noinline struct btrfs_device *device_list_add(const char *path,
785 struct btrfs_super_block *disk_super,
786 bool *new_device_added)
788 struct btrfs_device *device;
789 struct btrfs_fs_devices *fs_devices;
790 struct rcu_string *name;
791 u64 found_transid = btrfs_super_generation(disk_super);
792 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
793 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
794 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
796 if (has_metadata_uuid)
797 fs_devices = find_fsid(disk_super->fsid, disk_super->metadata_uuid);
799 fs_devices = find_fsid(disk_super->fsid, NULL);
802 if (has_metadata_uuid)
803 fs_devices = alloc_fs_devices(disk_super->fsid,
804 disk_super->metadata_uuid);
806 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
808 if (IS_ERR(fs_devices))
809 return ERR_CAST(fs_devices);
811 mutex_lock(&fs_devices->device_list_mutex);
812 list_add(&fs_devices->fs_list, &fs_uuids);
816 mutex_lock(&fs_devices->device_list_mutex);
817 device = find_device(fs_devices, devid,
818 disk_super->dev_item.uuid);
822 if (fs_devices->opened) {
823 mutex_unlock(&fs_devices->device_list_mutex);
824 return ERR_PTR(-EBUSY);
827 device = btrfs_alloc_device(NULL, &devid,
828 disk_super->dev_item.uuid);
829 if (IS_ERR(device)) {
830 mutex_unlock(&fs_devices->device_list_mutex);
831 /* we can safely leave the fs_devices entry around */
835 name = rcu_string_strdup(path, GFP_NOFS);
837 btrfs_free_device(device);
838 mutex_unlock(&fs_devices->device_list_mutex);
839 return ERR_PTR(-ENOMEM);
841 rcu_assign_pointer(device->name, name);
843 list_add_rcu(&device->dev_list, &fs_devices->devices);
844 fs_devices->num_devices++;
846 device->fs_devices = fs_devices;
847 *new_device_added = true;
849 if (disk_super->label[0])
850 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
851 disk_super->label, devid, found_transid, path);
853 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
854 disk_super->fsid, devid, found_transid, path);
856 } else if (!device->name || strcmp(device->name->str, path)) {
858 * When FS is already mounted.
859 * 1. If you are here and if the device->name is NULL that
860 * means this device was missing at time of FS mount.
861 * 2. If you are here and if the device->name is different
862 * from 'path' that means either
863 * a. The same device disappeared and reappeared with
865 * b. The missing-disk-which-was-replaced, has
868 * We must allow 1 and 2a above. But 2b would be a spurious
871 * Further in case of 1 and 2a above, the disk at 'path'
872 * would have missed some transaction when it was away and
873 * in case of 2a the stale bdev has to be updated as well.
874 * 2b must not be allowed at all time.
878 * For now, we do allow update to btrfs_fs_device through the
879 * btrfs dev scan cli after FS has been mounted. We're still
880 * tracking a problem where systems fail mount by subvolume id
881 * when we reject replacement on a mounted FS.
883 if (!fs_devices->opened && found_transid < device->generation) {
885 * That is if the FS is _not_ mounted and if you
886 * are here, that means there is more than one
887 * disk with same uuid and devid.We keep the one
888 * with larger generation number or the last-in if
889 * generation are equal.
891 mutex_unlock(&fs_devices->device_list_mutex);
892 return ERR_PTR(-EEXIST);
896 * We are going to replace the device path for a given devid,
897 * make sure it's the same device if the device is mounted
900 struct block_device *path_bdev;
902 path_bdev = lookup_bdev(path);
903 if (IS_ERR(path_bdev)) {
904 mutex_unlock(&fs_devices->device_list_mutex);
905 return ERR_CAST(path_bdev);
908 if (device->bdev != path_bdev) {
910 mutex_unlock(&fs_devices->device_list_mutex);
911 btrfs_warn_in_rcu(device->fs_info,
912 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
913 disk_super->fsid, devid,
914 rcu_str_deref(device->name), path);
915 return ERR_PTR(-EEXIST);
918 btrfs_info_in_rcu(device->fs_info,
919 "device fsid %pU devid %llu moved old:%s new:%s",
920 disk_super->fsid, devid,
921 rcu_str_deref(device->name), path);
924 name = rcu_string_strdup(path, GFP_NOFS);
926 mutex_unlock(&fs_devices->device_list_mutex);
927 return ERR_PTR(-ENOMEM);
929 rcu_string_free(device->name);
930 rcu_assign_pointer(device->name, name);
931 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
932 fs_devices->missing_devices--;
933 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
938 * Unmount does not free the btrfs_device struct but would zero
939 * generation along with most of the other members. So just update
940 * it back. We need it to pick the disk with largest generation
943 if (!fs_devices->opened)
944 device->generation = found_transid;
946 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
948 mutex_unlock(&fs_devices->device_list_mutex);
952 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
954 struct btrfs_fs_devices *fs_devices;
955 struct btrfs_device *device;
956 struct btrfs_device *orig_dev;
958 fs_devices = alloc_fs_devices(orig->fsid, NULL);
959 if (IS_ERR(fs_devices))
962 mutex_lock(&orig->device_list_mutex);
963 fs_devices->total_devices = orig->total_devices;
965 /* We have held the volume lock, it is safe to get the devices. */
966 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
967 struct rcu_string *name;
969 device = btrfs_alloc_device(NULL, &orig_dev->devid,
975 * This is ok to do without rcu read locked because we hold the
976 * uuid mutex so nothing we touch in here is going to disappear.
978 if (orig_dev->name) {
979 name = rcu_string_strdup(orig_dev->name->str,
982 btrfs_free_device(device);
985 rcu_assign_pointer(device->name, name);
988 list_add(&device->dev_list, &fs_devices->devices);
989 device->fs_devices = fs_devices;
990 fs_devices->num_devices++;
992 mutex_unlock(&orig->device_list_mutex);
995 mutex_unlock(&orig->device_list_mutex);
996 free_fs_devices(fs_devices);
997 return ERR_PTR(-ENOMEM);
1001 * After we have read the system tree and know devids belonging to
1002 * this filesystem, remove the device which does not belong there.
1004 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1006 struct btrfs_device *device, *next;
1007 struct btrfs_device *latest_dev = NULL;
1009 mutex_lock(&uuid_mutex);
1011 /* This is the initialized path, it is safe to release the devices. */
1012 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1013 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1014 &device->dev_state)) {
1015 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1016 &device->dev_state) &&
1018 device->generation > latest_dev->generation)) {
1019 latest_dev = device;
1024 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1026 * In the first step, keep the device which has
1027 * the correct fsid and the devid that is used
1028 * for the dev_replace procedure.
1029 * In the second step, the dev_replace state is
1030 * read from the device tree and it is known
1031 * whether the procedure is really active or
1032 * not, which means whether this device is
1033 * used or whether it should be removed.
1035 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1036 &device->dev_state)) {
1041 blkdev_put(device->bdev, device->mode);
1042 device->bdev = NULL;
1043 fs_devices->open_devices--;
1045 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1046 list_del_init(&device->dev_alloc_list);
1047 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1048 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1049 &device->dev_state))
1050 fs_devices->rw_devices--;
1052 list_del_init(&device->dev_list);
1053 fs_devices->num_devices--;
1054 btrfs_free_device(device);
1057 if (fs_devices->seed) {
1058 fs_devices = fs_devices->seed;
1062 fs_devices->latest_bdev = latest_dev->bdev;
1064 mutex_unlock(&uuid_mutex);
1067 static void free_device_rcu(struct rcu_head *head)
1069 struct btrfs_device *device;
1071 device = container_of(head, struct btrfs_device, rcu);
1072 btrfs_free_device(device);
1075 static void btrfs_close_bdev(struct btrfs_device *device)
1080 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1081 sync_blockdev(device->bdev);
1082 invalidate_bdev(device->bdev);
1085 blkdev_put(device->bdev, device->mode);
1088 static void btrfs_close_one_device(struct btrfs_device *device)
1090 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1091 struct btrfs_device *new_device;
1092 struct rcu_string *name;
1095 fs_devices->open_devices--;
1097 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1098 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1099 list_del_init(&device->dev_alloc_list);
1100 fs_devices->rw_devices--;
1103 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1104 fs_devices->missing_devices--;
1106 btrfs_close_bdev(device);
1108 new_device = btrfs_alloc_device(NULL, &device->devid,
1110 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1112 /* Safe because we are under uuid_mutex */
1114 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1115 BUG_ON(!name); /* -ENOMEM */
1116 rcu_assign_pointer(new_device->name, name);
1119 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1120 new_device->fs_devices = device->fs_devices;
1122 call_rcu(&device->rcu, free_device_rcu);
1125 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1127 struct btrfs_device *device, *tmp;
1129 if (--fs_devices->opened > 0)
1132 mutex_lock(&fs_devices->device_list_mutex);
1133 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1134 btrfs_close_one_device(device);
1136 mutex_unlock(&fs_devices->device_list_mutex);
1138 WARN_ON(fs_devices->open_devices);
1139 WARN_ON(fs_devices->rw_devices);
1140 fs_devices->opened = 0;
1141 fs_devices->seeding = 0;
1146 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1148 struct btrfs_fs_devices *seed_devices = NULL;
1151 mutex_lock(&uuid_mutex);
1152 ret = close_fs_devices(fs_devices);
1153 if (!fs_devices->opened) {
1154 seed_devices = fs_devices->seed;
1155 fs_devices->seed = NULL;
1157 mutex_unlock(&uuid_mutex);
1159 while (seed_devices) {
1160 fs_devices = seed_devices;
1161 seed_devices = fs_devices->seed;
1162 close_fs_devices(fs_devices);
1163 free_fs_devices(fs_devices);
1168 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1169 fmode_t flags, void *holder)
1171 struct btrfs_device *device;
1172 struct btrfs_device *latest_dev = NULL;
1175 flags |= FMODE_EXCL;
1177 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1178 /* Just open everything we can; ignore failures here */
1179 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1183 device->generation > latest_dev->generation)
1184 latest_dev = device;
1186 if (fs_devices->open_devices == 0) {
1190 fs_devices->opened = 1;
1191 fs_devices->latest_bdev = latest_dev->bdev;
1192 fs_devices->total_rw_bytes = 0;
1197 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1199 struct btrfs_device *dev1, *dev2;
1201 dev1 = list_entry(a, struct btrfs_device, dev_list);
1202 dev2 = list_entry(b, struct btrfs_device, dev_list);
1204 if (dev1->devid < dev2->devid)
1206 else if (dev1->devid > dev2->devid)
1211 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1212 fmode_t flags, void *holder)
1216 lockdep_assert_held(&uuid_mutex);
1218 mutex_lock(&fs_devices->device_list_mutex);
1219 if (fs_devices->opened) {
1220 fs_devices->opened++;
1223 list_sort(NULL, &fs_devices->devices, devid_cmp);
1224 ret = open_fs_devices(fs_devices, flags, holder);
1226 mutex_unlock(&fs_devices->device_list_mutex);
1231 static void btrfs_release_disk_super(struct page *page)
1237 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1239 struct btrfs_super_block **disk_super)
1244 /* make sure our super fits in the device */
1245 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1248 /* make sure our super fits in the page */
1249 if (sizeof(**disk_super) > PAGE_SIZE)
1252 /* make sure our super doesn't straddle pages on disk */
1253 index = bytenr >> PAGE_SHIFT;
1254 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1257 /* pull in the page with our super */
1258 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1261 if (IS_ERR_OR_NULL(*page))
1266 /* align our pointer to the offset of the super block */
1267 *disk_super = p + (bytenr & ~PAGE_MASK);
1269 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1270 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1271 btrfs_release_disk_super(*page);
1275 if ((*disk_super)->label[0] &&
1276 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1277 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1283 * Look for a btrfs signature on a device. This may be called out of the mount path
1284 * and we are not allowed to call set_blocksize during the scan. The superblock
1285 * is read via pagecache
1287 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1290 struct btrfs_super_block *disk_super;
1291 bool new_device_added = false;
1292 struct btrfs_device *device = NULL;
1293 struct block_device *bdev;
1297 lockdep_assert_held(&uuid_mutex);
1300 * we would like to check all the supers, but that would make
1301 * a btrfs mount succeed after a mkfs from a different FS.
1302 * So, we need to add a special mount option to scan for
1303 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1305 bytenr = btrfs_sb_offset(0);
1306 flags |= FMODE_EXCL;
1308 bdev = blkdev_get_by_path(path, flags, holder);
1310 return ERR_CAST(bdev);
1312 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1313 device = ERR_PTR(-EINVAL);
1314 goto error_bdev_put;
1317 device = device_list_add(path, disk_super, &new_device_added);
1318 if (!IS_ERR(device)) {
1319 if (new_device_added)
1320 btrfs_free_stale_devices(path, device);
1323 btrfs_release_disk_super(page);
1326 blkdev_put(bdev, flags);
1331 static int contains_pending_extent(struct btrfs_transaction *transaction,
1332 struct btrfs_device *device,
1333 u64 *start, u64 len)
1335 struct btrfs_fs_info *fs_info = device->fs_info;
1336 struct extent_map *em;
1337 struct list_head *search_list = &fs_info->pinned_chunks;
1339 u64 physical_start = *start;
1342 search_list = &transaction->pending_chunks;
1344 list_for_each_entry(em, search_list, list) {
1345 struct map_lookup *map;
1348 map = em->map_lookup;
1349 for (i = 0; i < map->num_stripes; i++) {
1352 if (map->stripes[i].dev != device)
1354 if (map->stripes[i].physical >= physical_start + len ||
1355 map->stripes[i].physical + em->orig_block_len <=
1359 * Make sure that while processing the pinned list we do
1360 * not override our *start with a lower value, because
1361 * we can have pinned chunks that fall within this
1362 * device hole and that have lower physical addresses
1363 * than the pending chunks we processed before. If we
1364 * do not take this special care we can end up getting
1365 * 2 pending chunks that start at the same physical
1366 * device offsets because the end offset of a pinned
1367 * chunk can be equal to the start offset of some
1370 end = map->stripes[i].physical + em->orig_block_len;
1377 if (search_list != &fs_info->pinned_chunks) {
1378 search_list = &fs_info->pinned_chunks;
1387 * find_free_dev_extent_start - find free space in the specified device
1388 * @device: the device which we search the free space in
1389 * @num_bytes: the size of the free space that we need
1390 * @search_start: the position from which to begin the search
1391 * @start: store the start of the free space.
1392 * @len: the size of the free space. that we find, or the size
1393 * of the max free space if we don't find suitable free space
1395 * this uses a pretty simple search, the expectation is that it is
1396 * called very infrequently and that a given device has a small number
1399 * @start is used to store the start of the free space if we find. But if we
1400 * don't find suitable free space, it will be used to store the start position
1401 * of the max free space.
1403 * @len is used to store the size of the free space that we find.
1404 * But if we don't find suitable free space, it is used to store the size of
1405 * the max free space.
1407 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1408 struct btrfs_device *device, u64 num_bytes,
1409 u64 search_start, u64 *start, u64 *len)
1411 struct btrfs_fs_info *fs_info = device->fs_info;
1412 struct btrfs_root *root = fs_info->dev_root;
1413 struct btrfs_key key;
1414 struct btrfs_dev_extent *dev_extent;
1415 struct btrfs_path *path;
1420 u64 search_end = device->total_bytes;
1423 struct extent_buffer *l;
1426 * We don't want to overwrite the superblock on the drive nor any area
1427 * used by the boot loader (grub for example), so we make sure to start
1428 * at an offset of at least 1MB.
1430 search_start = max_t(u64, search_start, SZ_1M);
1432 path = btrfs_alloc_path();
1436 max_hole_start = search_start;
1440 if (search_start >= search_end ||
1441 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1446 path->reada = READA_FORWARD;
1447 path->search_commit_root = 1;
1448 path->skip_locking = 1;
1450 key.objectid = device->devid;
1451 key.offset = search_start;
1452 key.type = BTRFS_DEV_EXTENT_KEY;
1454 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1458 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1465 slot = path->slots[0];
1466 if (slot >= btrfs_header_nritems(l)) {
1467 ret = btrfs_next_leaf(root, path);
1475 btrfs_item_key_to_cpu(l, &key, slot);
1477 if (key.objectid < device->devid)
1480 if (key.objectid > device->devid)
1483 if (key.type != BTRFS_DEV_EXTENT_KEY)
1486 if (key.offset > search_start) {
1487 hole_size = key.offset - search_start;
1490 * Have to check before we set max_hole_start, otherwise
1491 * we could end up sending back this offset anyway.
1493 if (contains_pending_extent(transaction, device,
1496 if (key.offset >= search_start) {
1497 hole_size = key.offset - search_start;
1504 if (hole_size > max_hole_size) {
1505 max_hole_start = search_start;
1506 max_hole_size = hole_size;
1510 * If this free space is greater than which we need,
1511 * it must be the max free space that we have found
1512 * until now, so max_hole_start must point to the start
1513 * of this free space and the length of this free space
1514 * is stored in max_hole_size. Thus, we return
1515 * max_hole_start and max_hole_size and go back to the
1518 if (hole_size >= num_bytes) {
1524 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1525 extent_end = key.offset + btrfs_dev_extent_length(l,
1527 if (extent_end > search_start)
1528 search_start = extent_end;
1535 * At this point, search_start should be the end of
1536 * allocated dev extents, and when shrinking the device,
1537 * search_end may be smaller than search_start.
1539 if (search_end > search_start) {
1540 hole_size = search_end - search_start;
1542 if (contains_pending_extent(transaction, device, &search_start,
1544 btrfs_release_path(path);
1548 if (hole_size > max_hole_size) {
1549 max_hole_start = search_start;
1550 max_hole_size = hole_size;
1555 if (max_hole_size < num_bytes)
1561 btrfs_free_path(path);
1562 *start = max_hole_start;
1564 *len = max_hole_size;
1568 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1569 struct btrfs_device *device, u64 num_bytes,
1570 u64 *start, u64 *len)
1572 /* FIXME use last free of some kind */
1573 return find_free_dev_extent_start(trans->transaction, device,
1574 num_bytes, 0, start, len);
1577 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1578 struct btrfs_device *device,
1579 u64 start, u64 *dev_extent_len)
1581 struct btrfs_fs_info *fs_info = device->fs_info;
1582 struct btrfs_root *root = fs_info->dev_root;
1584 struct btrfs_path *path;
1585 struct btrfs_key key;
1586 struct btrfs_key found_key;
1587 struct extent_buffer *leaf = NULL;
1588 struct btrfs_dev_extent *extent = NULL;
1590 path = btrfs_alloc_path();
1594 key.objectid = device->devid;
1596 key.type = BTRFS_DEV_EXTENT_KEY;
1598 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1600 ret = btrfs_previous_item(root, path, key.objectid,
1601 BTRFS_DEV_EXTENT_KEY);
1604 leaf = path->nodes[0];
1605 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1606 extent = btrfs_item_ptr(leaf, path->slots[0],
1607 struct btrfs_dev_extent);
1608 BUG_ON(found_key.offset > start || found_key.offset +
1609 btrfs_dev_extent_length(leaf, extent) < start);
1611 btrfs_release_path(path);
1613 } else if (ret == 0) {
1614 leaf = path->nodes[0];
1615 extent = btrfs_item_ptr(leaf, path->slots[0],
1616 struct btrfs_dev_extent);
1618 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1622 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1624 ret = btrfs_del_item(trans, root, path);
1626 btrfs_handle_fs_error(fs_info, ret,
1627 "Failed to remove dev extent item");
1629 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1632 btrfs_free_path(path);
1636 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1637 struct btrfs_device *device,
1638 u64 chunk_offset, u64 start, u64 num_bytes)
1641 struct btrfs_path *path;
1642 struct btrfs_fs_info *fs_info = device->fs_info;
1643 struct btrfs_root *root = fs_info->dev_root;
1644 struct btrfs_dev_extent *extent;
1645 struct extent_buffer *leaf;
1646 struct btrfs_key key;
1648 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1649 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1650 path = btrfs_alloc_path();
1654 key.objectid = device->devid;
1656 key.type = BTRFS_DEV_EXTENT_KEY;
1657 ret = btrfs_insert_empty_item(trans, root, path, &key,
1662 leaf = path->nodes[0];
1663 extent = btrfs_item_ptr(leaf, path->slots[0],
1664 struct btrfs_dev_extent);
1665 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1666 BTRFS_CHUNK_TREE_OBJECTID);
1667 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1668 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1669 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1671 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1672 btrfs_mark_buffer_dirty(leaf);
1674 btrfs_free_path(path);
1678 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1680 struct extent_map_tree *em_tree;
1681 struct extent_map *em;
1685 em_tree = &fs_info->mapping_tree.map_tree;
1686 read_lock(&em_tree->lock);
1687 n = rb_last(&em_tree->map.rb_root);
1689 em = rb_entry(n, struct extent_map, rb_node);
1690 ret = em->start + em->len;
1692 read_unlock(&em_tree->lock);
1697 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1701 struct btrfs_key key;
1702 struct btrfs_key found_key;
1703 struct btrfs_path *path;
1705 path = btrfs_alloc_path();
1709 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1710 key.type = BTRFS_DEV_ITEM_KEY;
1711 key.offset = (u64)-1;
1713 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1717 BUG_ON(ret == 0); /* Corruption */
1719 ret = btrfs_previous_item(fs_info->chunk_root, path,
1720 BTRFS_DEV_ITEMS_OBJECTID,
1721 BTRFS_DEV_ITEM_KEY);
1725 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1727 *devid_ret = found_key.offset + 1;
1731 btrfs_free_path(path);
1736 * the device information is stored in the chunk root
1737 * the btrfs_device struct should be fully filled in
1739 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1740 struct btrfs_device *device)
1743 struct btrfs_path *path;
1744 struct btrfs_dev_item *dev_item;
1745 struct extent_buffer *leaf;
1746 struct btrfs_key key;
1749 path = btrfs_alloc_path();
1753 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1754 key.type = BTRFS_DEV_ITEM_KEY;
1755 key.offset = device->devid;
1757 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1758 &key, sizeof(*dev_item));
1762 leaf = path->nodes[0];
1763 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1765 btrfs_set_device_id(leaf, dev_item, device->devid);
1766 btrfs_set_device_generation(leaf, dev_item, 0);
1767 btrfs_set_device_type(leaf, dev_item, device->type);
1768 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1769 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1770 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1771 btrfs_set_device_total_bytes(leaf, dev_item,
1772 btrfs_device_get_disk_total_bytes(device));
1773 btrfs_set_device_bytes_used(leaf, dev_item,
1774 btrfs_device_get_bytes_used(device));
1775 btrfs_set_device_group(leaf, dev_item, 0);
1776 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1777 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1778 btrfs_set_device_start_offset(leaf, dev_item, 0);
1780 ptr = btrfs_device_uuid(dev_item);
1781 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1782 ptr = btrfs_device_fsid(dev_item);
1783 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1784 ptr, BTRFS_FSID_SIZE);
1785 btrfs_mark_buffer_dirty(leaf);
1789 btrfs_free_path(path);
1794 * Function to update ctime/mtime for a given device path.
1795 * Mainly used for ctime/mtime based probe like libblkid.
1797 static void update_dev_time(const char *path_name)
1801 filp = filp_open(path_name, O_RDWR, 0);
1804 file_update_time(filp);
1805 filp_close(filp, NULL);
1808 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1809 struct btrfs_device *device)
1811 struct btrfs_root *root = fs_info->chunk_root;
1813 struct btrfs_path *path;
1814 struct btrfs_key key;
1815 struct btrfs_trans_handle *trans;
1817 path = btrfs_alloc_path();
1821 trans = btrfs_start_transaction(root, 0);
1822 if (IS_ERR(trans)) {
1823 btrfs_free_path(path);
1824 return PTR_ERR(trans);
1826 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1827 key.type = BTRFS_DEV_ITEM_KEY;
1828 key.offset = device->devid;
1830 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1834 btrfs_abort_transaction(trans, ret);
1835 btrfs_end_transaction(trans);
1839 ret = btrfs_del_item(trans, root, path);
1841 btrfs_abort_transaction(trans, ret);
1842 btrfs_end_transaction(trans);
1846 btrfs_free_path(path);
1848 ret = btrfs_commit_transaction(trans);
1853 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1854 * filesystem. It's up to the caller to adjust that number regarding eg. device
1857 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1865 seq = read_seqbegin(&fs_info->profiles_lock);
1867 all_avail = fs_info->avail_data_alloc_bits |
1868 fs_info->avail_system_alloc_bits |
1869 fs_info->avail_metadata_alloc_bits;
1870 } while (read_seqretry(&fs_info->profiles_lock, seq));
1872 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1873 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1876 if (num_devices < btrfs_raid_array[i].devs_min) {
1877 int ret = btrfs_raid_array[i].mindev_error;
1887 static struct btrfs_device * btrfs_find_next_active_device(
1888 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1890 struct btrfs_device *next_device;
1892 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1893 if (next_device != device &&
1894 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1895 && next_device->bdev)
1903 * Helper function to check if the given device is part of s_bdev / latest_bdev
1904 * and replace it with the provided or the next active device, in the context
1905 * where this function called, there should be always be another device (or
1906 * this_dev) which is active.
1908 void btrfs_assign_next_active_device(struct btrfs_device *device,
1909 struct btrfs_device *this_dev)
1911 struct btrfs_fs_info *fs_info = device->fs_info;
1912 struct btrfs_device *next_device;
1915 next_device = this_dev;
1917 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1919 ASSERT(next_device);
1921 if (fs_info->sb->s_bdev &&
1922 (fs_info->sb->s_bdev == device->bdev))
1923 fs_info->sb->s_bdev = next_device->bdev;
1925 if (fs_info->fs_devices->latest_bdev == device->bdev)
1926 fs_info->fs_devices->latest_bdev = next_device->bdev;
1930 * Return btrfs_fs_devices::num_devices excluding the device that's being
1931 * currently replaced.
1933 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1935 u64 num_devices = fs_info->fs_devices->num_devices;
1937 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1938 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1939 ASSERT(num_devices > 1);
1942 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1947 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1950 struct btrfs_device *device;
1951 struct btrfs_fs_devices *cur_devices;
1952 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1956 mutex_lock(&uuid_mutex);
1958 num_devices = btrfs_num_devices(fs_info);
1960 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1964 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
1966 if (IS_ERR(device)) {
1967 if (PTR_ERR(device) == -ENOENT &&
1968 strcmp(device_path, "missing") == 0)
1969 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1971 ret = PTR_ERR(device);
1975 if (btrfs_pinned_by_swapfile(fs_info, device)) {
1976 btrfs_warn_in_rcu(fs_info,
1977 "cannot remove device %s (devid %llu) due to active swapfile",
1978 rcu_str_deref(device->name), device->devid);
1983 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1984 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1988 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1989 fs_info->fs_devices->rw_devices == 1) {
1990 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1994 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1995 mutex_lock(&fs_info->chunk_mutex);
1996 list_del_init(&device->dev_alloc_list);
1997 device->fs_devices->rw_devices--;
1998 mutex_unlock(&fs_info->chunk_mutex);
2001 mutex_unlock(&uuid_mutex);
2002 ret = btrfs_shrink_device(device, 0);
2003 mutex_lock(&uuid_mutex);
2008 * TODO: the superblock still includes this device in its num_devices
2009 * counter although write_all_supers() is not locked out. This
2010 * could give a filesystem state which requires a degraded mount.
2012 ret = btrfs_rm_dev_item(fs_info, device);
2016 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2017 btrfs_scrub_cancel_dev(fs_info, device);
2020 * the device list mutex makes sure that we don't change
2021 * the device list while someone else is writing out all
2022 * the device supers. Whoever is writing all supers, should
2023 * lock the device list mutex before getting the number of
2024 * devices in the super block (super_copy). Conversely,
2025 * whoever updates the number of devices in the super block
2026 * (super_copy) should hold the device list mutex.
2030 * In normal cases the cur_devices == fs_devices. But in case
2031 * of deleting a seed device, the cur_devices should point to
2032 * its own fs_devices listed under the fs_devices->seed.
2034 cur_devices = device->fs_devices;
2035 mutex_lock(&fs_devices->device_list_mutex);
2036 list_del_rcu(&device->dev_list);
2038 cur_devices->num_devices--;
2039 cur_devices->total_devices--;
2040 /* Update total_devices of the parent fs_devices if it's seed */
2041 if (cur_devices != fs_devices)
2042 fs_devices->total_devices--;
2044 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2045 cur_devices->missing_devices--;
2047 btrfs_assign_next_active_device(device, NULL);
2050 cur_devices->open_devices--;
2051 /* remove sysfs entry */
2052 btrfs_sysfs_rm_device_link(fs_devices, device);
2055 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2056 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2057 mutex_unlock(&fs_devices->device_list_mutex);
2060 * at this point, the device is zero sized and detached from
2061 * the devices list. All that's left is to zero out the old
2062 * supers and free the device.
2064 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2065 btrfs_scratch_superblocks(device->bdev, device->name->str);
2067 btrfs_close_bdev(device);
2068 call_rcu(&device->rcu, free_device_rcu);
2070 if (cur_devices->open_devices == 0) {
2071 while (fs_devices) {
2072 if (fs_devices->seed == cur_devices) {
2073 fs_devices->seed = cur_devices->seed;
2076 fs_devices = fs_devices->seed;
2078 cur_devices->seed = NULL;
2079 close_fs_devices(cur_devices);
2080 free_fs_devices(cur_devices);
2084 mutex_unlock(&uuid_mutex);
2088 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2089 mutex_lock(&fs_info->chunk_mutex);
2090 list_add(&device->dev_alloc_list,
2091 &fs_devices->alloc_list);
2092 device->fs_devices->rw_devices++;
2093 mutex_unlock(&fs_info->chunk_mutex);
2098 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2100 struct btrfs_fs_devices *fs_devices;
2102 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2105 * in case of fs with no seed, srcdev->fs_devices will point
2106 * to fs_devices of fs_info. However when the dev being replaced is
2107 * a seed dev it will point to the seed's local fs_devices. In short
2108 * srcdev will have its correct fs_devices in both the cases.
2110 fs_devices = srcdev->fs_devices;
2112 list_del_rcu(&srcdev->dev_list);
2113 list_del(&srcdev->dev_alloc_list);
2114 fs_devices->num_devices--;
2115 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2116 fs_devices->missing_devices--;
2118 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2119 fs_devices->rw_devices--;
2122 fs_devices->open_devices--;
2125 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2126 struct btrfs_device *srcdev)
2128 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2130 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2131 /* zero out the old super if it is writable */
2132 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2135 btrfs_close_bdev(srcdev);
2136 call_rcu(&srcdev->rcu, free_device_rcu);
2138 /* if this is no devs we rather delete the fs_devices */
2139 if (!fs_devices->num_devices) {
2140 struct btrfs_fs_devices *tmp_fs_devices;
2143 * On a mounted FS, num_devices can't be zero unless it's a
2144 * seed. In case of a seed device being replaced, the replace
2145 * target added to the sprout FS, so there will be no more
2146 * device left under the seed FS.
2148 ASSERT(fs_devices->seeding);
2150 tmp_fs_devices = fs_info->fs_devices;
2151 while (tmp_fs_devices) {
2152 if (tmp_fs_devices->seed == fs_devices) {
2153 tmp_fs_devices->seed = fs_devices->seed;
2156 tmp_fs_devices = tmp_fs_devices->seed;
2158 fs_devices->seed = NULL;
2159 close_fs_devices(fs_devices);
2160 free_fs_devices(fs_devices);
2164 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2166 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2169 mutex_lock(&fs_devices->device_list_mutex);
2171 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2174 fs_devices->open_devices--;
2176 fs_devices->num_devices--;
2178 btrfs_assign_next_active_device(tgtdev, NULL);
2180 list_del_rcu(&tgtdev->dev_list);
2182 mutex_unlock(&fs_devices->device_list_mutex);
2185 * The update_dev_time() with in btrfs_scratch_superblocks()
2186 * may lead to a call to btrfs_show_devname() which will try
2187 * to hold device_list_mutex. And here this device
2188 * is already out of device list, so we don't have to hold
2189 * the device_list_mutex lock.
2191 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2193 btrfs_close_bdev(tgtdev);
2194 call_rcu(&tgtdev->rcu, free_device_rcu);
2197 static struct btrfs_device *btrfs_find_device_by_path(
2198 struct btrfs_fs_info *fs_info, const char *device_path)
2201 struct btrfs_super_block *disk_super;
2204 struct block_device *bdev;
2205 struct buffer_head *bh;
2206 struct btrfs_device *device;
2208 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2209 fs_info->bdev_holder, 0, &bdev, &bh);
2211 return ERR_PTR(ret);
2212 disk_super = (struct btrfs_super_block *)bh->b_data;
2213 devid = btrfs_stack_device_id(&disk_super->dev_item);
2214 dev_uuid = disk_super->dev_item.uuid;
2215 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2216 device = btrfs_find_device(fs_info, devid, dev_uuid,
2217 disk_super->metadata_uuid);
2219 device = btrfs_find_device(fs_info, devid,
2220 dev_uuid, disk_super->fsid);
2224 device = ERR_PTR(-ENOENT);
2225 blkdev_put(bdev, FMODE_READ);
2229 static struct btrfs_device *btrfs_find_device_missing_or_by_path(
2230 struct btrfs_fs_info *fs_info, const char *device_path)
2232 struct btrfs_device *device = NULL;
2233 if (strcmp(device_path, "missing") == 0) {
2234 struct list_head *devices;
2235 struct btrfs_device *tmp;
2237 devices = &fs_info->fs_devices->devices;
2238 list_for_each_entry(tmp, devices, dev_list) {
2239 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2240 &tmp->dev_state) && !tmp->bdev) {
2247 return ERR_PTR(-ENOENT);
2249 device = btrfs_find_device_by_path(fs_info, device_path);
2256 * Lookup a device given by device id, or the path if the id is 0.
2258 struct btrfs_device *btrfs_find_device_by_devspec(
2259 struct btrfs_fs_info *fs_info, u64 devid, const char *devpath)
2261 struct btrfs_device *device;
2264 device = btrfs_find_device(fs_info, devid, NULL, NULL);
2266 return ERR_PTR(-ENOENT);
2268 if (!devpath || !devpath[0])
2269 return ERR_PTR(-EINVAL);
2270 device = btrfs_find_device_missing_or_by_path(fs_info, devpath);
2276 * does all the dirty work required for changing file system's UUID.
2278 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2280 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2281 struct btrfs_fs_devices *old_devices;
2282 struct btrfs_fs_devices *seed_devices;
2283 struct btrfs_super_block *disk_super = fs_info->super_copy;
2284 struct btrfs_device *device;
2287 lockdep_assert_held(&uuid_mutex);
2288 if (!fs_devices->seeding)
2291 seed_devices = alloc_fs_devices(NULL, NULL);
2292 if (IS_ERR(seed_devices))
2293 return PTR_ERR(seed_devices);
2295 old_devices = clone_fs_devices(fs_devices);
2296 if (IS_ERR(old_devices)) {
2297 kfree(seed_devices);
2298 return PTR_ERR(old_devices);
2301 list_add(&old_devices->fs_list, &fs_uuids);
2303 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2304 seed_devices->opened = 1;
2305 INIT_LIST_HEAD(&seed_devices->devices);
2306 INIT_LIST_HEAD(&seed_devices->alloc_list);
2307 mutex_init(&seed_devices->device_list_mutex);
2309 mutex_lock(&fs_devices->device_list_mutex);
2310 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2312 list_for_each_entry(device, &seed_devices->devices, dev_list)
2313 device->fs_devices = seed_devices;
2315 mutex_lock(&fs_info->chunk_mutex);
2316 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2317 mutex_unlock(&fs_info->chunk_mutex);
2319 fs_devices->seeding = 0;
2320 fs_devices->num_devices = 0;
2321 fs_devices->open_devices = 0;
2322 fs_devices->missing_devices = 0;
2323 fs_devices->rotating = 0;
2324 fs_devices->seed = seed_devices;
2326 generate_random_uuid(fs_devices->fsid);
2327 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2328 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2329 mutex_unlock(&fs_devices->device_list_mutex);
2331 super_flags = btrfs_super_flags(disk_super) &
2332 ~BTRFS_SUPER_FLAG_SEEDING;
2333 btrfs_set_super_flags(disk_super, super_flags);
2339 * Store the expected generation for seed devices in device items.
2341 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2342 struct btrfs_fs_info *fs_info)
2344 struct btrfs_root *root = fs_info->chunk_root;
2345 struct btrfs_path *path;
2346 struct extent_buffer *leaf;
2347 struct btrfs_dev_item *dev_item;
2348 struct btrfs_device *device;
2349 struct btrfs_key key;
2350 u8 fs_uuid[BTRFS_FSID_SIZE];
2351 u8 dev_uuid[BTRFS_UUID_SIZE];
2355 path = btrfs_alloc_path();
2359 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2361 key.type = BTRFS_DEV_ITEM_KEY;
2364 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2368 leaf = path->nodes[0];
2370 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2371 ret = btrfs_next_leaf(root, path);
2376 leaf = path->nodes[0];
2377 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2378 btrfs_release_path(path);
2382 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2383 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2384 key.type != BTRFS_DEV_ITEM_KEY)
2387 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2388 struct btrfs_dev_item);
2389 devid = btrfs_device_id(leaf, dev_item);
2390 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2392 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2394 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2395 BUG_ON(!device); /* Logic error */
2397 if (device->fs_devices->seeding) {
2398 btrfs_set_device_generation(leaf, dev_item,
2399 device->generation);
2400 btrfs_mark_buffer_dirty(leaf);
2408 btrfs_free_path(path);
2412 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2414 struct btrfs_root *root = fs_info->dev_root;
2415 struct request_queue *q;
2416 struct btrfs_trans_handle *trans;
2417 struct btrfs_device *device;
2418 struct block_device *bdev;
2419 struct super_block *sb = fs_info->sb;
2420 struct rcu_string *name;
2421 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2422 u64 orig_super_total_bytes;
2423 u64 orig_super_num_devices;
2424 int seeding_dev = 0;
2426 bool unlocked = false;
2428 if (sb_rdonly(sb) && !fs_devices->seeding)
2431 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2432 fs_info->bdev_holder);
2434 return PTR_ERR(bdev);
2436 if (fs_devices->seeding) {
2438 down_write(&sb->s_umount);
2439 mutex_lock(&uuid_mutex);
2442 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2444 mutex_lock(&fs_devices->device_list_mutex);
2445 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2446 if (device->bdev == bdev) {
2449 &fs_devices->device_list_mutex);
2453 mutex_unlock(&fs_devices->device_list_mutex);
2455 device = btrfs_alloc_device(fs_info, NULL, NULL);
2456 if (IS_ERR(device)) {
2457 /* we can safely leave the fs_devices entry around */
2458 ret = PTR_ERR(device);
2462 name = rcu_string_strdup(device_path, GFP_KERNEL);
2465 goto error_free_device;
2467 rcu_assign_pointer(device->name, name);
2469 trans = btrfs_start_transaction(root, 0);
2470 if (IS_ERR(trans)) {
2471 ret = PTR_ERR(trans);
2472 goto error_free_device;
2475 q = bdev_get_queue(bdev);
2476 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2477 device->generation = trans->transid;
2478 device->io_width = fs_info->sectorsize;
2479 device->io_align = fs_info->sectorsize;
2480 device->sector_size = fs_info->sectorsize;
2481 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2482 fs_info->sectorsize);
2483 device->disk_total_bytes = device->total_bytes;
2484 device->commit_total_bytes = device->total_bytes;
2485 device->fs_info = fs_info;
2486 device->bdev = bdev;
2487 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2488 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2489 device->mode = FMODE_EXCL;
2490 device->dev_stats_valid = 1;
2491 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2494 sb->s_flags &= ~SB_RDONLY;
2495 ret = btrfs_prepare_sprout(fs_info);
2497 btrfs_abort_transaction(trans, ret);
2502 device->fs_devices = fs_devices;
2504 mutex_lock(&fs_devices->device_list_mutex);
2505 mutex_lock(&fs_info->chunk_mutex);
2506 list_add_rcu(&device->dev_list, &fs_devices->devices);
2507 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2508 fs_devices->num_devices++;
2509 fs_devices->open_devices++;
2510 fs_devices->rw_devices++;
2511 fs_devices->total_devices++;
2512 fs_devices->total_rw_bytes += device->total_bytes;
2514 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2516 if (!blk_queue_nonrot(q))
2517 fs_devices->rotating = 1;
2519 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2520 btrfs_set_super_total_bytes(fs_info->super_copy,
2521 round_down(orig_super_total_bytes + device->total_bytes,
2522 fs_info->sectorsize));
2524 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2525 btrfs_set_super_num_devices(fs_info->super_copy,
2526 orig_super_num_devices + 1);
2528 /* add sysfs device entry */
2529 btrfs_sysfs_add_device_link(fs_devices, device);
2532 * we've got more storage, clear any full flags on the space
2535 btrfs_clear_space_info_full(fs_info);
2537 mutex_unlock(&fs_info->chunk_mutex);
2538 mutex_unlock(&fs_devices->device_list_mutex);
2541 mutex_lock(&fs_info->chunk_mutex);
2542 ret = init_first_rw_device(trans, fs_info);
2543 mutex_unlock(&fs_info->chunk_mutex);
2545 btrfs_abort_transaction(trans, ret);
2550 ret = btrfs_add_dev_item(trans, device);
2552 btrfs_abort_transaction(trans, ret);
2557 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2559 ret = btrfs_finish_sprout(trans, fs_info);
2561 btrfs_abort_transaction(trans, ret);
2565 /* Sprouting would change fsid of the mounted root,
2566 * so rename the fsid on the sysfs
2568 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2569 fs_info->fs_devices->fsid);
2570 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2572 "sysfs: failed to create fsid for sprout");
2575 ret = btrfs_commit_transaction(trans);
2578 mutex_unlock(&uuid_mutex);
2579 up_write(&sb->s_umount);
2582 if (ret) /* transaction commit */
2585 ret = btrfs_relocate_sys_chunks(fs_info);
2587 btrfs_handle_fs_error(fs_info, ret,
2588 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2589 trans = btrfs_attach_transaction(root);
2590 if (IS_ERR(trans)) {
2591 if (PTR_ERR(trans) == -ENOENT)
2593 ret = PTR_ERR(trans);
2597 ret = btrfs_commit_transaction(trans);
2600 /* Update ctime/mtime for libblkid */
2601 update_dev_time(device_path);
2605 btrfs_sysfs_rm_device_link(fs_devices, device);
2606 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2607 mutex_lock(&fs_info->chunk_mutex);
2608 list_del_rcu(&device->dev_list);
2609 list_del(&device->dev_alloc_list);
2610 fs_info->fs_devices->num_devices--;
2611 fs_info->fs_devices->open_devices--;
2612 fs_info->fs_devices->rw_devices--;
2613 fs_info->fs_devices->total_devices--;
2614 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2615 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2616 btrfs_set_super_total_bytes(fs_info->super_copy,
2617 orig_super_total_bytes);
2618 btrfs_set_super_num_devices(fs_info->super_copy,
2619 orig_super_num_devices);
2620 mutex_unlock(&fs_info->chunk_mutex);
2621 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2624 sb->s_flags |= SB_RDONLY;
2626 btrfs_end_transaction(trans);
2628 btrfs_free_device(device);
2630 blkdev_put(bdev, FMODE_EXCL);
2631 if (seeding_dev && !unlocked) {
2632 mutex_unlock(&uuid_mutex);
2633 up_write(&sb->s_umount);
2638 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2639 struct btrfs_device *device)
2642 struct btrfs_path *path;
2643 struct btrfs_root *root = device->fs_info->chunk_root;
2644 struct btrfs_dev_item *dev_item;
2645 struct extent_buffer *leaf;
2646 struct btrfs_key key;
2648 path = btrfs_alloc_path();
2652 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2653 key.type = BTRFS_DEV_ITEM_KEY;
2654 key.offset = device->devid;
2656 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2665 leaf = path->nodes[0];
2666 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2668 btrfs_set_device_id(leaf, dev_item, device->devid);
2669 btrfs_set_device_type(leaf, dev_item, device->type);
2670 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2671 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2672 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2673 btrfs_set_device_total_bytes(leaf, dev_item,
2674 btrfs_device_get_disk_total_bytes(device));
2675 btrfs_set_device_bytes_used(leaf, dev_item,
2676 btrfs_device_get_bytes_used(device));
2677 btrfs_mark_buffer_dirty(leaf);
2680 btrfs_free_path(path);
2684 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2685 struct btrfs_device *device, u64 new_size)
2687 struct btrfs_fs_info *fs_info = device->fs_info;
2688 struct btrfs_super_block *super_copy = fs_info->super_copy;
2689 struct btrfs_fs_devices *fs_devices;
2693 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2696 new_size = round_down(new_size, fs_info->sectorsize);
2698 mutex_lock(&fs_info->chunk_mutex);
2699 old_total = btrfs_super_total_bytes(super_copy);
2700 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2702 if (new_size <= device->total_bytes ||
2703 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2704 mutex_unlock(&fs_info->chunk_mutex);
2708 fs_devices = fs_info->fs_devices;
2710 btrfs_set_super_total_bytes(super_copy,
2711 round_down(old_total + diff, fs_info->sectorsize));
2712 device->fs_devices->total_rw_bytes += diff;
2714 btrfs_device_set_total_bytes(device, new_size);
2715 btrfs_device_set_disk_total_bytes(device, new_size);
2716 btrfs_clear_space_info_full(device->fs_info);
2717 if (list_empty(&device->resized_list))
2718 list_add_tail(&device->resized_list,
2719 &fs_devices->resized_devices);
2720 mutex_unlock(&fs_info->chunk_mutex);
2722 return btrfs_update_device(trans, device);
2725 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2727 struct btrfs_fs_info *fs_info = trans->fs_info;
2728 struct btrfs_root *root = fs_info->chunk_root;
2730 struct btrfs_path *path;
2731 struct btrfs_key key;
2733 path = btrfs_alloc_path();
2737 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2738 key.offset = chunk_offset;
2739 key.type = BTRFS_CHUNK_ITEM_KEY;
2741 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2744 else if (ret > 0) { /* Logic error or corruption */
2745 btrfs_handle_fs_error(fs_info, -ENOENT,
2746 "Failed lookup while freeing chunk.");
2751 ret = btrfs_del_item(trans, root, path);
2753 btrfs_handle_fs_error(fs_info, ret,
2754 "Failed to delete chunk item.");
2756 btrfs_free_path(path);
2760 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2762 struct btrfs_super_block *super_copy = fs_info->super_copy;
2763 struct btrfs_disk_key *disk_key;
2764 struct btrfs_chunk *chunk;
2771 struct btrfs_key key;
2773 mutex_lock(&fs_info->chunk_mutex);
2774 array_size = btrfs_super_sys_array_size(super_copy);
2776 ptr = super_copy->sys_chunk_array;
2779 while (cur < array_size) {
2780 disk_key = (struct btrfs_disk_key *)ptr;
2781 btrfs_disk_key_to_cpu(&key, disk_key);
2783 len = sizeof(*disk_key);
2785 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2786 chunk = (struct btrfs_chunk *)(ptr + len);
2787 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2788 len += btrfs_chunk_item_size(num_stripes);
2793 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2794 key.offset == chunk_offset) {
2795 memmove(ptr, ptr + len, array_size - (cur + len));
2797 btrfs_set_super_sys_array_size(super_copy, array_size);
2803 mutex_unlock(&fs_info->chunk_mutex);
2808 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2809 * @logical: Logical block offset in bytes.
2810 * @length: Length of extent in bytes.
2812 * Return: Chunk mapping or ERR_PTR.
2814 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2815 u64 logical, u64 length)
2817 struct extent_map_tree *em_tree;
2818 struct extent_map *em;
2820 em_tree = &fs_info->mapping_tree.map_tree;
2821 read_lock(&em_tree->lock);
2822 em = lookup_extent_mapping(em_tree, logical, length);
2823 read_unlock(&em_tree->lock);
2826 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2828 return ERR_PTR(-EINVAL);
2831 if (em->start > logical || em->start + em->len < logical) {
2833 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2834 logical, length, em->start, em->start + em->len);
2835 free_extent_map(em);
2836 return ERR_PTR(-EINVAL);
2839 /* callers are responsible for dropping em's ref. */
2843 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2845 struct btrfs_fs_info *fs_info = trans->fs_info;
2846 struct extent_map *em;
2847 struct map_lookup *map;
2848 u64 dev_extent_len = 0;
2850 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2852 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2855 * This is a logic error, but we don't want to just rely on the
2856 * user having built with ASSERT enabled, so if ASSERT doesn't
2857 * do anything we still error out.
2862 map = em->map_lookup;
2863 mutex_lock(&fs_info->chunk_mutex);
2864 check_system_chunk(trans, map->type);
2865 mutex_unlock(&fs_info->chunk_mutex);
2868 * Take the device list mutex to prevent races with the final phase of
2869 * a device replace operation that replaces the device object associated
2870 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2872 mutex_lock(&fs_devices->device_list_mutex);
2873 for (i = 0; i < map->num_stripes; i++) {
2874 struct btrfs_device *device = map->stripes[i].dev;
2875 ret = btrfs_free_dev_extent(trans, device,
2876 map->stripes[i].physical,
2879 mutex_unlock(&fs_devices->device_list_mutex);
2880 btrfs_abort_transaction(trans, ret);
2884 if (device->bytes_used > 0) {
2885 mutex_lock(&fs_info->chunk_mutex);
2886 btrfs_device_set_bytes_used(device,
2887 device->bytes_used - dev_extent_len);
2888 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2889 btrfs_clear_space_info_full(fs_info);
2890 mutex_unlock(&fs_info->chunk_mutex);
2893 ret = btrfs_update_device(trans, device);
2895 mutex_unlock(&fs_devices->device_list_mutex);
2896 btrfs_abort_transaction(trans, ret);
2900 mutex_unlock(&fs_devices->device_list_mutex);
2902 ret = btrfs_free_chunk(trans, chunk_offset);
2904 btrfs_abort_transaction(trans, ret);
2908 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2910 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2911 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2913 btrfs_abort_transaction(trans, ret);
2918 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2920 btrfs_abort_transaction(trans, ret);
2926 free_extent_map(em);
2930 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2932 struct btrfs_root *root = fs_info->chunk_root;
2933 struct btrfs_trans_handle *trans;
2937 * Prevent races with automatic removal of unused block groups.
2938 * After we relocate and before we remove the chunk with offset
2939 * chunk_offset, automatic removal of the block group can kick in,
2940 * resulting in a failure when calling btrfs_remove_chunk() below.
2942 * Make sure to acquire this mutex before doing a tree search (dev
2943 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2944 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2945 * we release the path used to search the chunk/dev tree and before
2946 * the current task acquires this mutex and calls us.
2948 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2950 ret = btrfs_can_relocate(fs_info, chunk_offset);
2954 /* step one, relocate all the extents inside this chunk */
2955 btrfs_scrub_pause(fs_info);
2956 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2957 btrfs_scrub_continue(fs_info);
2962 * We add the kobjects here (and after forcing data chunk creation)
2963 * since relocation is the only place we'll create chunks of a new
2964 * type at runtime. The only place where we'll remove the last
2965 * chunk of a type is the call immediately below this one. Even
2966 * so, we're protected against races with the cleaner thread since
2967 * we're covered by the delete_unused_bgs_mutex.
2969 btrfs_add_raid_kobjects(fs_info);
2971 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2973 if (IS_ERR(trans)) {
2974 ret = PTR_ERR(trans);
2975 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2980 * step two, delete the device extents and the
2981 * chunk tree entries
2983 ret = btrfs_remove_chunk(trans, chunk_offset);
2984 btrfs_end_transaction(trans);
2988 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2990 struct btrfs_root *chunk_root = fs_info->chunk_root;
2991 struct btrfs_path *path;
2992 struct extent_buffer *leaf;
2993 struct btrfs_chunk *chunk;
2994 struct btrfs_key key;
2995 struct btrfs_key found_key;
2997 bool retried = false;
3001 path = btrfs_alloc_path();
3006 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3007 key.offset = (u64)-1;
3008 key.type = BTRFS_CHUNK_ITEM_KEY;
3011 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3012 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3014 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3017 BUG_ON(ret == 0); /* Corruption */
3019 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3022 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3028 leaf = path->nodes[0];
3029 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3031 chunk = btrfs_item_ptr(leaf, path->slots[0],
3032 struct btrfs_chunk);
3033 chunk_type = btrfs_chunk_type(leaf, chunk);
3034 btrfs_release_path(path);
3036 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3037 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3043 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3045 if (found_key.offset == 0)
3047 key.offset = found_key.offset - 1;
3050 if (failed && !retried) {
3054 } else if (WARN_ON(failed && retried)) {
3058 btrfs_free_path(path);
3063 * return 1 : allocate a data chunk successfully,
3064 * return <0: errors during allocating a data chunk,
3065 * return 0 : no need to allocate a data chunk.
3067 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3070 struct btrfs_block_group_cache *cache;
3074 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3076 chunk_type = cache->flags;
3077 btrfs_put_block_group(cache);
3079 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3080 spin_lock(&fs_info->data_sinfo->lock);
3081 bytes_used = fs_info->data_sinfo->bytes_used;
3082 spin_unlock(&fs_info->data_sinfo->lock);
3085 struct btrfs_trans_handle *trans;
3088 trans = btrfs_join_transaction(fs_info->tree_root);
3090 return PTR_ERR(trans);
3092 ret = btrfs_force_chunk_alloc(trans,
3093 BTRFS_BLOCK_GROUP_DATA);
3094 btrfs_end_transaction(trans);
3098 btrfs_add_raid_kobjects(fs_info);
3106 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3107 struct btrfs_balance_control *bctl)
3109 struct btrfs_root *root = fs_info->tree_root;
3110 struct btrfs_trans_handle *trans;
3111 struct btrfs_balance_item *item;
3112 struct btrfs_disk_balance_args disk_bargs;
3113 struct btrfs_path *path;
3114 struct extent_buffer *leaf;
3115 struct btrfs_key key;
3118 path = btrfs_alloc_path();
3122 trans = btrfs_start_transaction(root, 0);
3123 if (IS_ERR(trans)) {
3124 btrfs_free_path(path);
3125 return PTR_ERR(trans);
3128 key.objectid = BTRFS_BALANCE_OBJECTID;
3129 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3132 ret = btrfs_insert_empty_item(trans, root, path, &key,
3137 leaf = path->nodes[0];
3138 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3140 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3142 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3143 btrfs_set_balance_data(leaf, item, &disk_bargs);
3144 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3145 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3146 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3147 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3149 btrfs_set_balance_flags(leaf, item, bctl->flags);
3151 btrfs_mark_buffer_dirty(leaf);
3153 btrfs_free_path(path);
3154 err = btrfs_commit_transaction(trans);
3160 static int del_balance_item(struct btrfs_fs_info *fs_info)
3162 struct btrfs_root *root = fs_info->tree_root;
3163 struct btrfs_trans_handle *trans;
3164 struct btrfs_path *path;
3165 struct btrfs_key key;
3168 path = btrfs_alloc_path();
3172 trans = btrfs_start_transaction(root, 0);
3173 if (IS_ERR(trans)) {
3174 btrfs_free_path(path);
3175 return PTR_ERR(trans);
3178 key.objectid = BTRFS_BALANCE_OBJECTID;
3179 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3182 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3190 ret = btrfs_del_item(trans, root, path);
3192 btrfs_free_path(path);
3193 err = btrfs_commit_transaction(trans);
3200 * This is a heuristic used to reduce the number of chunks balanced on
3201 * resume after balance was interrupted.
3203 static void update_balance_args(struct btrfs_balance_control *bctl)
3206 * Turn on soft mode for chunk types that were being converted.
3208 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3209 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3210 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3211 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3212 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3213 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3216 * Turn on usage filter if is not already used. The idea is
3217 * that chunks that we have already balanced should be
3218 * reasonably full. Don't do it for chunks that are being
3219 * converted - that will keep us from relocating unconverted
3220 * (albeit full) chunks.
3222 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3223 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3224 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3225 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3226 bctl->data.usage = 90;
3228 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3229 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3230 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3231 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3232 bctl->sys.usage = 90;
3234 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3235 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3236 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {