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,
40 .raid_name = "raid10",
41 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
42 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
44 [BTRFS_RAID_RAID1] = {
49 .tolerated_failures = 1,
53 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
54 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
61 .tolerated_failures = 0,
65 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
68 [BTRFS_RAID_RAID0] = {
73 .tolerated_failures = 0,
77 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
80 [BTRFS_RAID_SINGLE] = {
85 .tolerated_failures = 0,
88 .raid_name = "single",
92 [BTRFS_RAID_RAID5] = {
97 .tolerated_failures = 1,
100 .raid_name = "raid5",
101 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
102 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
104 [BTRFS_RAID_RAID6] = {
109 .tolerated_failures = 2,
112 .raid_name = "raid6",
113 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
114 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
118 const char *get_raid_name(enum btrfs_raid_types type)
120 if (type >= BTRFS_NR_RAID_TYPES)
123 return btrfs_raid_array[type].raid_name;
126 static int init_first_rw_device(struct btrfs_trans_handle *trans,
127 struct btrfs_fs_info *fs_info);
128 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
129 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
130 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
131 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
132 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
133 enum btrfs_map_op op,
134 u64 logical, u64 *length,
135 struct btrfs_bio **bbio_ret,
136 int mirror_num, int need_raid_map);
142 * There are several mutexes that protect manipulation of devices and low-level
143 * structures like chunks but not block groups, extents or files
145 * uuid_mutex (global lock)
146 * ------------------------
147 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
148 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
149 * device) or requested by the device= mount option
151 * the mutex can be very coarse and can cover long-running operations
153 * protects: updates to fs_devices counters like missing devices, rw devices,
154 * seeding, structure cloning, openning/closing devices at mount/umount time
156 * global::fs_devs - add, remove, updates to the global list
158 * does not protect: manipulation of the fs_devices::devices list!
160 * btrfs_device::name - renames (write side), read is RCU
162 * fs_devices::device_list_mutex (per-fs, with RCU)
163 * ------------------------------------------------
164 * protects updates to fs_devices::devices, ie. adding and deleting
166 * simple list traversal with read-only actions can be done with RCU protection
168 * may be used to exclude some operations from running concurrently without any
169 * modifications to the list (see write_all_supers)
173 * protects balance structures (status, state) and context accessed from
174 * several places (internally, ioctl)
178 * protects chunks, adding or removing during allocation, trim or when a new
179 * device is added/removed
183 * a big lock that is held by the cleaner thread and prevents running subvolume
184 * cleaning together with relocation or delayed iputs
197 * Exclusive operations, BTRFS_FS_EXCL_OP
198 * ======================================
200 * Maintains the exclusivity of the following operations that apply to the
201 * whole filesystem and cannot run in parallel.
206 * - Device replace (*)
209 * The device operations (as above) can be in one of the following states:
215 * Only device operations marked with (*) can go into the Paused state for the
218 * - ioctl (only Balance can be Paused through ioctl)
219 * - filesystem remounted as read-only
220 * - filesystem unmounted and mounted as read-only
221 * - system power-cycle and filesystem mounted as read-only
222 * - filesystem or device errors leading to forced read-only
224 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
225 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
226 * A device operation in Paused or Running state can be canceled or resumed
227 * either by ioctl (Balance only) or when remounted as read-write.
228 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
232 DEFINE_MUTEX(uuid_mutex);
233 static LIST_HEAD(fs_uuids);
234 struct list_head *btrfs_get_fs_uuids(void)
240 * alloc_fs_devices - allocate struct btrfs_fs_devices
241 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
243 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
244 * The returned struct is not linked onto any lists and can be destroyed with
245 * kfree() right away.
247 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
249 struct btrfs_fs_devices *fs_devs;
251 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
253 return ERR_PTR(-ENOMEM);
255 mutex_init(&fs_devs->device_list_mutex);
257 INIT_LIST_HEAD(&fs_devs->devices);
258 INIT_LIST_HEAD(&fs_devs->resized_devices);
259 INIT_LIST_HEAD(&fs_devs->alloc_list);
260 INIT_LIST_HEAD(&fs_devs->fs_list);
262 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
267 void btrfs_free_device(struct btrfs_device *device)
269 rcu_string_free(device->name);
270 bio_put(device->flush_bio);
274 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
276 struct btrfs_device *device;
277 WARN_ON(fs_devices->opened);
278 while (!list_empty(&fs_devices->devices)) {
279 device = list_entry(fs_devices->devices.next,
280 struct btrfs_device, dev_list);
281 list_del(&device->dev_list);
282 btrfs_free_device(device);
287 static void btrfs_kobject_uevent(struct block_device *bdev,
288 enum kobject_action action)
292 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
294 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
296 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
297 &disk_to_dev(bdev->bd_disk)->kobj);
300 void __exit btrfs_cleanup_fs_uuids(void)
302 struct btrfs_fs_devices *fs_devices;
304 while (!list_empty(&fs_uuids)) {
305 fs_devices = list_entry(fs_uuids.next,
306 struct btrfs_fs_devices, fs_list);
307 list_del(&fs_devices->fs_list);
308 free_fs_devices(fs_devices);
313 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
314 * Returned struct is not linked onto any lists and must be destroyed using
317 static struct btrfs_device *__alloc_device(void)
319 struct btrfs_device *dev;
321 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
323 return ERR_PTR(-ENOMEM);
326 * Preallocate a bio that's always going to be used for flushing device
327 * barriers and matches the device lifespan
329 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
330 if (!dev->flush_bio) {
332 return ERR_PTR(-ENOMEM);
335 INIT_LIST_HEAD(&dev->dev_list);
336 INIT_LIST_HEAD(&dev->dev_alloc_list);
337 INIT_LIST_HEAD(&dev->resized_list);
339 spin_lock_init(&dev->io_lock);
341 atomic_set(&dev->reada_in_flight, 0);
342 atomic_set(&dev->dev_stats_ccnt, 0);
343 btrfs_device_data_ordered_init(dev);
344 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
345 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
351 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
354 * If devid and uuid are both specified, the match must be exact, otherwise
355 * only devid is used.
357 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
358 u64 devid, const u8 *uuid)
360 struct btrfs_device *dev;
362 list_for_each_entry(dev, &fs_devices->devices, dev_list) {
363 if (dev->devid == devid &&
364 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
371 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
373 struct btrfs_fs_devices *fs_devices;
375 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
376 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
383 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
384 int flush, struct block_device **bdev,
385 struct buffer_head **bh)
389 *bdev = blkdev_get_by_path(device_path, flags, holder);
392 ret = PTR_ERR(*bdev);
397 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
398 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
400 blkdev_put(*bdev, flags);
403 invalidate_bdev(*bdev);
404 *bh = btrfs_read_dev_super(*bdev);
407 blkdev_put(*bdev, flags);
419 static void requeue_list(struct btrfs_pending_bios *pending_bios,
420 struct bio *head, struct bio *tail)
423 struct bio *old_head;
425 old_head = pending_bios->head;
426 pending_bios->head = head;
427 if (pending_bios->tail)
428 tail->bi_next = old_head;
430 pending_bios->tail = tail;
434 * we try to collect pending bios for a device so we don't get a large
435 * number of procs sending bios down to the same device. This greatly
436 * improves the schedulers ability to collect and merge the bios.
438 * But, it also turns into a long list of bios to process and that is sure
439 * to eventually make the worker thread block. The solution here is to
440 * make some progress and then put this work struct back at the end of
441 * the list if the block device is congested. This way, multiple devices
442 * can make progress from a single worker thread.
444 static noinline void run_scheduled_bios(struct btrfs_device *device)
446 struct btrfs_fs_info *fs_info = device->fs_info;
448 struct backing_dev_info *bdi;
449 struct btrfs_pending_bios *pending_bios;
453 unsigned long num_run;
454 unsigned long batch_run = 0;
455 unsigned long last_waited = 0;
457 int sync_pending = 0;
458 struct blk_plug plug;
461 * this function runs all the bios we've collected for
462 * a particular device. We don't want to wander off to
463 * another device without first sending all of these down.
464 * So, setup a plug here and finish it off before we return
466 blk_start_plug(&plug);
468 bdi = device->bdev->bd_bdi;
471 spin_lock(&device->io_lock);
476 /* take all the bios off the list at once and process them
477 * later on (without the lock held). But, remember the
478 * tail and other pointers so the bios can be properly reinserted
479 * into the list if we hit congestion
481 if (!force_reg && device->pending_sync_bios.head) {
482 pending_bios = &device->pending_sync_bios;
485 pending_bios = &device->pending_bios;
489 pending = pending_bios->head;
490 tail = pending_bios->tail;
491 WARN_ON(pending && !tail);
494 * if pending was null this time around, no bios need processing
495 * at all and we can stop. Otherwise it'll loop back up again
496 * and do an additional check so no bios are missed.
498 * device->running_pending is used to synchronize with the
501 if (device->pending_sync_bios.head == NULL &&
502 device->pending_bios.head == NULL) {
504 device->running_pending = 0;
507 device->running_pending = 1;
510 pending_bios->head = NULL;
511 pending_bios->tail = NULL;
513 spin_unlock(&device->io_lock);
518 /* we want to work on both lists, but do more bios on the
519 * sync list than the regular list
522 pending_bios != &device->pending_sync_bios &&
523 device->pending_sync_bios.head) ||
524 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
525 device->pending_bios.head)) {
526 spin_lock(&device->io_lock);
527 requeue_list(pending_bios, pending, tail);
532 pending = pending->bi_next;
535 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
538 * if we're doing the sync list, record that our
539 * plug has some sync requests on it
541 * If we're doing the regular list and there are
542 * sync requests sitting around, unplug before
545 if (pending_bios == &device->pending_sync_bios) {
547 } else if (sync_pending) {
548 blk_finish_plug(&plug);
549 blk_start_plug(&plug);
553 btrfsic_submit_bio(cur);
560 * we made progress, there is more work to do and the bdi
561 * is now congested. Back off and let other work structs
564 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
565 fs_info->fs_devices->open_devices > 1) {
566 struct io_context *ioc;
568 ioc = current->io_context;
571 * the main goal here is that we don't want to
572 * block if we're going to be able to submit
573 * more requests without blocking.
575 * This code does two great things, it pokes into
576 * the elevator code from a filesystem _and_
577 * it makes assumptions about how batching works.
579 if (ioc && ioc->nr_batch_requests > 0 &&
580 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
582 ioc->last_waited == last_waited)) {
584 * we want to go through our batch of
585 * requests and stop. So, we copy out
586 * the ioc->last_waited time and test
587 * against it before looping
589 last_waited = ioc->last_waited;
593 spin_lock(&device->io_lock);
594 requeue_list(pending_bios, pending, tail);
595 device->running_pending = 1;
597 spin_unlock(&device->io_lock);
598 btrfs_queue_work(fs_info->submit_workers,
608 spin_lock(&device->io_lock);
609 if (device->pending_bios.head || device->pending_sync_bios.head)
611 spin_unlock(&device->io_lock);
614 blk_finish_plug(&plug);
617 static void pending_bios_fn(struct btrfs_work *work)
619 struct btrfs_device *device;
621 device = container_of(work, struct btrfs_device, work);
622 run_scheduled_bios(device);
626 * Search and remove all stale (devices which are not mounted) devices.
627 * When both inputs are NULL, it will search and release all stale devices.
628 * path: Optional. When provided will it release all unmounted devices
629 * matching this path only.
630 * skip_dev: Optional. Will skip this device when searching for the stale
633 static void btrfs_free_stale_devices(const char *path,
634 struct btrfs_device *skip_device)
636 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
637 struct btrfs_device *device, *tmp_device;
639 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
640 mutex_lock(&fs_devices->device_list_mutex);
641 if (fs_devices->opened) {
642 mutex_unlock(&fs_devices->device_list_mutex);
646 list_for_each_entry_safe(device, tmp_device,
647 &fs_devices->devices, dev_list) {
650 if (skip_device && skip_device == device)
652 if (path && !device->name)
657 not_found = strcmp(rcu_str_deref(device->name),
663 /* delete the stale device */
664 fs_devices->num_devices--;
665 list_del(&device->dev_list);
666 btrfs_free_device(device);
668 if (fs_devices->num_devices == 0)
671 mutex_unlock(&fs_devices->device_list_mutex);
672 if (fs_devices->num_devices == 0) {
673 btrfs_sysfs_remove_fsid(fs_devices);
674 list_del(&fs_devices->fs_list);
675 free_fs_devices(fs_devices);
680 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
681 struct btrfs_device *device, fmode_t flags,
684 struct request_queue *q;
685 struct block_device *bdev;
686 struct buffer_head *bh;
687 struct btrfs_super_block *disk_super;
696 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
701 disk_super = (struct btrfs_super_block *)bh->b_data;
702 devid = btrfs_stack_device_id(&disk_super->dev_item);
703 if (devid != device->devid)
706 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
709 device->generation = btrfs_super_generation(disk_super);
711 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
712 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
713 fs_devices->seeding = 1;
715 if (bdev_read_only(bdev))
716 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
718 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
721 q = bdev_get_queue(bdev);
722 if (!blk_queue_nonrot(q))
723 fs_devices->rotating = 1;
726 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
727 device->mode = flags;
729 fs_devices->open_devices++;
730 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
731 device->devid != BTRFS_DEV_REPLACE_DEVID) {
732 fs_devices->rw_devices++;
733 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
741 blkdev_put(bdev, flags);
747 * Add new device to list of registered devices
750 * device pointer which was just added or updated when successful
751 * error pointer when failed
753 static noinline struct btrfs_device *device_list_add(const char *path,
754 struct btrfs_super_block *disk_super,
755 bool *new_device_added)
757 struct btrfs_device *device;
758 struct btrfs_fs_devices *fs_devices;
759 struct rcu_string *name;
760 u64 found_transid = btrfs_super_generation(disk_super);
761 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
763 fs_devices = find_fsid(disk_super->fsid);
765 fs_devices = alloc_fs_devices(disk_super->fsid);
766 if (IS_ERR(fs_devices))
767 return ERR_CAST(fs_devices);
769 mutex_lock(&fs_devices->device_list_mutex);
770 list_add(&fs_devices->fs_list, &fs_uuids);
774 mutex_lock(&fs_devices->device_list_mutex);
775 device = find_device(fs_devices, devid,
776 disk_super->dev_item.uuid);
780 if (fs_devices->opened) {
781 mutex_unlock(&fs_devices->device_list_mutex);
782 return ERR_PTR(-EBUSY);
785 device = btrfs_alloc_device(NULL, &devid,
786 disk_super->dev_item.uuid);
787 if (IS_ERR(device)) {
788 mutex_unlock(&fs_devices->device_list_mutex);
789 /* we can safely leave the fs_devices entry around */
793 name = rcu_string_strdup(path, GFP_NOFS);
795 btrfs_free_device(device);
796 mutex_unlock(&fs_devices->device_list_mutex);
797 return ERR_PTR(-ENOMEM);
799 rcu_assign_pointer(device->name, name);
801 list_add_rcu(&device->dev_list, &fs_devices->devices);
802 fs_devices->num_devices++;
804 device->fs_devices = fs_devices;
805 *new_device_added = true;
807 if (disk_super->label[0])
808 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
809 disk_super->label, devid, found_transid, path);
811 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
812 disk_super->fsid, devid, found_transid, path);
814 } else if (!device->name || strcmp(device->name->str, path)) {
816 * When FS is already mounted.
817 * 1. If you are here and if the device->name is NULL that
818 * means this device was missing at time of FS mount.
819 * 2. If you are here and if the device->name is different
820 * from 'path' that means either
821 * a. The same device disappeared and reappeared with
823 * b. The missing-disk-which-was-replaced, has
826 * We must allow 1 and 2a above. But 2b would be a spurious
829 * Further in case of 1 and 2a above, the disk at 'path'
830 * would have missed some transaction when it was away and
831 * in case of 2a the stale bdev has to be updated as well.
832 * 2b must not be allowed at all time.
836 * For now, we do allow update to btrfs_fs_device through the
837 * btrfs dev scan cli after FS has been mounted. We're still
838 * tracking a problem where systems fail mount by subvolume id
839 * when we reject replacement on a mounted FS.
841 if (!fs_devices->opened && found_transid < device->generation) {
843 * That is if the FS is _not_ mounted and if you
844 * are here, that means there is more than one
845 * disk with same uuid and devid.We keep the one
846 * with larger generation number or the last-in if
847 * generation are equal.
849 mutex_unlock(&fs_devices->device_list_mutex);
850 return ERR_PTR(-EEXIST);
853 name = rcu_string_strdup(path, GFP_NOFS);
855 mutex_unlock(&fs_devices->device_list_mutex);
856 return ERR_PTR(-ENOMEM);
858 rcu_string_free(device->name);
859 rcu_assign_pointer(device->name, name);
860 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
861 fs_devices->missing_devices--;
862 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
867 * Unmount does not free the btrfs_device struct but would zero
868 * generation along with most of the other members. So just update
869 * it back. We need it to pick the disk with largest generation
872 if (!fs_devices->opened)
873 device->generation = found_transid;
875 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
877 mutex_unlock(&fs_devices->device_list_mutex);
881 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
883 struct btrfs_fs_devices *fs_devices;
884 struct btrfs_device *device;
885 struct btrfs_device *orig_dev;
887 fs_devices = alloc_fs_devices(orig->fsid);
888 if (IS_ERR(fs_devices))
891 mutex_lock(&orig->device_list_mutex);
892 fs_devices->total_devices = orig->total_devices;
894 /* We have held the volume lock, it is safe to get the devices. */
895 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
896 struct rcu_string *name;
898 device = btrfs_alloc_device(NULL, &orig_dev->devid,
904 * This is ok to do without rcu read locked because we hold the
905 * uuid mutex so nothing we touch in here is going to disappear.
907 if (orig_dev->name) {
908 name = rcu_string_strdup(orig_dev->name->str,
911 btrfs_free_device(device);
914 rcu_assign_pointer(device->name, name);
917 list_add(&device->dev_list, &fs_devices->devices);
918 device->fs_devices = fs_devices;
919 fs_devices->num_devices++;
921 mutex_unlock(&orig->device_list_mutex);
924 mutex_unlock(&orig->device_list_mutex);
925 free_fs_devices(fs_devices);
926 return ERR_PTR(-ENOMEM);
930 * After we have read the system tree and know devids belonging to
931 * this filesystem, remove the device which does not belong there.
933 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
935 struct btrfs_device *device, *next;
936 struct btrfs_device *latest_dev = NULL;
938 mutex_lock(&uuid_mutex);
940 /* This is the initialized path, it is safe to release the devices. */
941 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
942 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
943 &device->dev_state)) {
944 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
945 &device->dev_state) &&
947 device->generation > latest_dev->generation)) {
953 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
955 * In the first step, keep the device which has
956 * the correct fsid and the devid that is used
957 * for the dev_replace procedure.
958 * In the second step, the dev_replace state is
959 * read from the device tree and it is known
960 * whether the procedure is really active or
961 * not, which means whether this device is
962 * used or whether it should be removed.
964 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
965 &device->dev_state)) {
970 blkdev_put(device->bdev, device->mode);
972 fs_devices->open_devices--;
974 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
975 list_del_init(&device->dev_alloc_list);
976 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
977 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
979 fs_devices->rw_devices--;
981 list_del_init(&device->dev_list);
982 fs_devices->num_devices--;
983 btrfs_free_device(device);
986 if (fs_devices->seed) {
987 fs_devices = fs_devices->seed;
991 fs_devices->latest_bdev = latest_dev->bdev;
993 mutex_unlock(&uuid_mutex);
996 static void free_device_rcu(struct rcu_head *head)
998 struct btrfs_device *device;
1000 device = container_of(head, struct btrfs_device, rcu);
1001 btrfs_free_device(device);
1004 static void btrfs_close_bdev(struct btrfs_device *device)
1009 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1010 sync_blockdev(device->bdev);
1011 invalidate_bdev(device->bdev);
1014 blkdev_put(device->bdev, device->mode);
1017 static void btrfs_close_one_device(struct btrfs_device *device)
1019 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1020 struct btrfs_device *new_device;
1021 struct rcu_string *name;
1024 fs_devices->open_devices--;
1026 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1027 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1028 list_del_init(&device->dev_alloc_list);
1029 fs_devices->rw_devices--;
1032 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1033 fs_devices->missing_devices--;
1035 btrfs_close_bdev(device);
1037 new_device = btrfs_alloc_device(NULL, &device->devid,
1039 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1041 /* Safe because we are under uuid_mutex */
1043 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1044 BUG_ON(!name); /* -ENOMEM */
1045 rcu_assign_pointer(new_device->name, name);
1048 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1049 new_device->fs_devices = device->fs_devices;
1051 call_rcu(&device->rcu, free_device_rcu);
1054 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1056 struct btrfs_device *device, *tmp;
1058 if (--fs_devices->opened > 0)
1061 mutex_lock(&fs_devices->device_list_mutex);
1062 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1063 btrfs_close_one_device(device);
1065 mutex_unlock(&fs_devices->device_list_mutex);
1067 WARN_ON(fs_devices->open_devices);
1068 WARN_ON(fs_devices->rw_devices);
1069 fs_devices->opened = 0;
1070 fs_devices->seeding = 0;
1075 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1077 struct btrfs_fs_devices *seed_devices = NULL;
1080 mutex_lock(&uuid_mutex);
1081 ret = close_fs_devices(fs_devices);
1082 if (!fs_devices->opened) {
1083 seed_devices = fs_devices->seed;
1084 fs_devices->seed = NULL;
1086 mutex_unlock(&uuid_mutex);
1088 while (seed_devices) {
1089 fs_devices = seed_devices;
1090 seed_devices = fs_devices->seed;
1091 close_fs_devices(fs_devices);
1092 free_fs_devices(fs_devices);
1097 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1098 fmode_t flags, void *holder)
1100 struct btrfs_device *device;
1101 struct btrfs_device *latest_dev = NULL;
1104 flags |= FMODE_EXCL;
1106 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1107 /* Just open everything we can; ignore failures here */
1108 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1112 device->generation > latest_dev->generation)
1113 latest_dev = device;
1115 if (fs_devices->open_devices == 0) {
1119 fs_devices->opened = 1;
1120 fs_devices->latest_bdev = latest_dev->bdev;
1121 fs_devices->total_rw_bytes = 0;
1126 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1128 struct btrfs_device *dev1, *dev2;
1130 dev1 = list_entry(a, struct btrfs_device, dev_list);
1131 dev2 = list_entry(b, struct btrfs_device, dev_list);
1133 if (dev1->devid < dev2->devid)
1135 else if (dev1->devid > dev2->devid)
1140 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1141 fmode_t flags, void *holder)
1145 mutex_lock(&uuid_mutex);
1146 mutex_lock(&fs_devices->device_list_mutex);
1147 if (fs_devices->opened) {
1148 fs_devices->opened++;
1151 list_sort(NULL, &fs_devices->devices, devid_cmp);
1152 ret = open_fs_devices(fs_devices, flags, holder);
1154 mutex_unlock(&fs_devices->device_list_mutex);
1155 mutex_unlock(&uuid_mutex);
1160 static void btrfs_release_disk_super(struct page *page)
1166 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1168 struct btrfs_super_block **disk_super)
1173 /* make sure our super fits in the device */
1174 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1177 /* make sure our super fits in the page */
1178 if (sizeof(**disk_super) > PAGE_SIZE)
1181 /* make sure our super doesn't straddle pages on disk */
1182 index = bytenr >> PAGE_SHIFT;
1183 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1186 /* pull in the page with our super */
1187 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1190 if (IS_ERR_OR_NULL(*page))
1195 /* align our pointer to the offset of the super block */
1196 *disk_super = p + (bytenr & ~PAGE_MASK);
1198 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1199 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1200 btrfs_release_disk_super(*page);
1204 if ((*disk_super)->label[0] &&
1205 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1206 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1212 * Look for a btrfs signature on a device. This may be called out of the mount path
1213 * and we are not allowed to call set_blocksize during the scan. The superblock
1214 * is read via pagecache
1216 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1217 struct btrfs_fs_devices **fs_devices_ret)
1219 struct btrfs_super_block *disk_super;
1220 bool new_device_added = false;
1221 struct btrfs_device *device;
1222 struct block_device *bdev;
1228 * we would like to check all the supers, but that would make
1229 * a btrfs mount succeed after a mkfs from a different FS.
1230 * So, we need to add a special mount option to scan for
1231 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1233 bytenr = btrfs_sb_offset(0);
1234 flags |= FMODE_EXCL;
1236 bdev = blkdev_get_by_path(path, flags, holder);
1238 return PTR_ERR(bdev);
1240 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1242 goto error_bdev_put;
1245 mutex_lock(&uuid_mutex);
1246 device = device_list_add(path, disk_super, &new_device_added);
1247 if (IS_ERR(device)) {
1248 ret = PTR_ERR(device);
1250 *fs_devices_ret = device->fs_devices;
1251 if (new_device_added)
1252 btrfs_free_stale_devices(path, device);
1254 mutex_unlock(&uuid_mutex);
1256 btrfs_release_disk_super(page);
1259 blkdev_put(bdev, flags);
1264 static int contains_pending_extent(struct btrfs_transaction *transaction,
1265 struct btrfs_device *device,
1266 u64 *start, u64 len)
1268 struct btrfs_fs_info *fs_info = device->fs_info;
1269 struct extent_map *em;
1270 struct list_head *search_list = &fs_info->pinned_chunks;
1272 u64 physical_start = *start;
1275 search_list = &transaction->pending_chunks;
1277 list_for_each_entry(em, search_list, list) {
1278 struct map_lookup *map;
1281 map = em->map_lookup;
1282 for (i = 0; i < map->num_stripes; i++) {
1285 if (map->stripes[i].dev != device)
1287 if (map->stripes[i].physical >= physical_start + len ||
1288 map->stripes[i].physical + em->orig_block_len <=
1292 * Make sure that while processing the pinned list we do
1293 * not override our *start with a lower value, because
1294 * we can have pinned chunks that fall within this
1295 * device hole and that have lower physical addresses
1296 * than the pending chunks we processed before. If we
1297 * do not take this special care we can end up getting
1298 * 2 pending chunks that start at the same physical
1299 * device offsets because the end offset of a pinned
1300 * chunk can be equal to the start offset of some
1303 end = map->stripes[i].physical + em->orig_block_len;
1310 if (search_list != &fs_info->pinned_chunks) {
1311 search_list = &fs_info->pinned_chunks;
1320 * find_free_dev_extent_start - find free space in the specified device
1321 * @device: the device which we search the free space in
1322 * @num_bytes: the size of the free space that we need
1323 * @search_start: the position from which to begin the search
1324 * @start: store the start of the free space.
1325 * @len: the size of the free space. that we find, or the size
1326 * of the max free space if we don't find suitable free space
1328 * this uses a pretty simple search, the expectation is that it is
1329 * called very infrequently and that a given device has a small number
1332 * @start is used to store the start of the free space if we find. But if we
1333 * don't find suitable free space, it will be used to store the start position
1334 * of the max free space.
1336 * @len is used to store the size of the free space that we find.
1337 * But if we don't find suitable free space, it is used to store the size of
1338 * the max free space.
1340 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1341 struct btrfs_device *device, u64 num_bytes,
1342 u64 search_start, u64 *start, u64 *len)
1344 struct btrfs_fs_info *fs_info = device->fs_info;
1345 struct btrfs_root *root = fs_info->dev_root;
1346 struct btrfs_key key;
1347 struct btrfs_dev_extent *dev_extent;
1348 struct btrfs_path *path;
1353 u64 search_end = device->total_bytes;
1356 struct extent_buffer *l;
1359 * We don't want to overwrite the superblock on the drive nor any area
1360 * used by the boot loader (grub for example), so we make sure to start
1361 * at an offset of at least 1MB.
1363 search_start = max_t(u64, search_start, SZ_1M);
1365 path = btrfs_alloc_path();
1369 max_hole_start = search_start;
1373 if (search_start >= search_end ||
1374 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1379 path->reada = READA_FORWARD;
1380 path->search_commit_root = 1;
1381 path->skip_locking = 1;
1383 key.objectid = device->devid;
1384 key.offset = search_start;
1385 key.type = BTRFS_DEV_EXTENT_KEY;
1387 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1391 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1398 slot = path->slots[0];
1399 if (slot >= btrfs_header_nritems(l)) {
1400 ret = btrfs_next_leaf(root, path);
1408 btrfs_item_key_to_cpu(l, &key, slot);
1410 if (key.objectid < device->devid)
1413 if (key.objectid > device->devid)
1416 if (key.type != BTRFS_DEV_EXTENT_KEY)
1419 if (key.offset > search_start) {
1420 hole_size = key.offset - search_start;
1423 * Have to check before we set max_hole_start, otherwise
1424 * we could end up sending back this offset anyway.
1426 if (contains_pending_extent(transaction, device,
1429 if (key.offset >= search_start) {
1430 hole_size = key.offset - search_start;
1437 if (hole_size > max_hole_size) {
1438 max_hole_start = search_start;
1439 max_hole_size = hole_size;
1443 * If this free space is greater than which we need,
1444 * it must be the max free space that we have found
1445 * until now, so max_hole_start must point to the start
1446 * of this free space and the length of this free space
1447 * is stored in max_hole_size. Thus, we return
1448 * max_hole_start and max_hole_size and go back to the
1451 if (hole_size >= num_bytes) {
1457 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1458 extent_end = key.offset + btrfs_dev_extent_length(l,
1460 if (extent_end > search_start)
1461 search_start = extent_end;
1468 * At this point, search_start should be the end of
1469 * allocated dev extents, and when shrinking the device,
1470 * search_end may be smaller than search_start.
1472 if (search_end > search_start) {
1473 hole_size = search_end - search_start;
1475 if (contains_pending_extent(transaction, device, &search_start,
1477 btrfs_release_path(path);
1481 if (hole_size > max_hole_size) {
1482 max_hole_start = search_start;
1483 max_hole_size = hole_size;
1488 if (max_hole_size < num_bytes)
1494 btrfs_free_path(path);
1495 *start = max_hole_start;
1497 *len = max_hole_size;
1501 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1502 struct btrfs_device *device, u64 num_bytes,
1503 u64 *start, u64 *len)
1505 /* FIXME use last free of some kind */
1506 return find_free_dev_extent_start(trans->transaction, device,
1507 num_bytes, 0, start, len);
1510 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1511 struct btrfs_device *device,
1512 u64 start, u64 *dev_extent_len)
1514 struct btrfs_fs_info *fs_info = device->fs_info;
1515 struct btrfs_root *root = fs_info->dev_root;
1517 struct btrfs_path *path;
1518 struct btrfs_key key;
1519 struct btrfs_key found_key;
1520 struct extent_buffer *leaf = NULL;
1521 struct btrfs_dev_extent *extent = NULL;
1523 path = btrfs_alloc_path();
1527 key.objectid = device->devid;
1529 key.type = BTRFS_DEV_EXTENT_KEY;
1531 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1533 ret = btrfs_previous_item(root, path, key.objectid,
1534 BTRFS_DEV_EXTENT_KEY);
1537 leaf = path->nodes[0];
1538 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1539 extent = btrfs_item_ptr(leaf, path->slots[0],
1540 struct btrfs_dev_extent);
1541 BUG_ON(found_key.offset > start || found_key.offset +
1542 btrfs_dev_extent_length(leaf, extent) < start);
1544 btrfs_release_path(path);
1546 } else if (ret == 0) {
1547 leaf = path->nodes[0];
1548 extent = btrfs_item_ptr(leaf, path->slots[0],
1549 struct btrfs_dev_extent);
1551 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1555 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1557 ret = btrfs_del_item(trans, root, path);
1559 btrfs_handle_fs_error(fs_info, ret,
1560 "Failed to remove dev extent item");
1562 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1565 btrfs_free_path(path);
1569 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1570 struct btrfs_device *device,
1571 u64 chunk_offset, u64 start, u64 num_bytes)
1574 struct btrfs_path *path;
1575 struct btrfs_fs_info *fs_info = device->fs_info;
1576 struct btrfs_root *root = fs_info->dev_root;
1577 struct btrfs_dev_extent *extent;
1578 struct extent_buffer *leaf;
1579 struct btrfs_key key;
1581 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1582 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1583 path = btrfs_alloc_path();
1587 key.objectid = device->devid;
1589 key.type = BTRFS_DEV_EXTENT_KEY;
1590 ret = btrfs_insert_empty_item(trans, root, path, &key,
1595 leaf = path->nodes[0];
1596 extent = btrfs_item_ptr(leaf, path->slots[0],
1597 struct btrfs_dev_extent);
1598 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1599 BTRFS_CHUNK_TREE_OBJECTID);
1600 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1601 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1602 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1604 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1605 btrfs_mark_buffer_dirty(leaf);
1607 btrfs_free_path(path);
1611 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1613 struct extent_map_tree *em_tree;
1614 struct extent_map *em;
1618 em_tree = &fs_info->mapping_tree.map_tree;
1619 read_lock(&em_tree->lock);
1620 n = rb_last(&em_tree->map);
1622 em = rb_entry(n, struct extent_map, rb_node);
1623 ret = em->start + em->len;
1625 read_unlock(&em_tree->lock);
1630 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1634 struct btrfs_key key;
1635 struct btrfs_key found_key;
1636 struct btrfs_path *path;
1638 path = btrfs_alloc_path();
1642 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1643 key.type = BTRFS_DEV_ITEM_KEY;
1644 key.offset = (u64)-1;
1646 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1650 BUG_ON(ret == 0); /* Corruption */
1652 ret = btrfs_previous_item(fs_info->chunk_root, path,
1653 BTRFS_DEV_ITEMS_OBJECTID,
1654 BTRFS_DEV_ITEM_KEY);
1658 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1660 *devid_ret = found_key.offset + 1;
1664 btrfs_free_path(path);
1669 * the device information is stored in the chunk root
1670 * the btrfs_device struct should be fully filled in
1672 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1673 struct btrfs_fs_info *fs_info,
1674 struct btrfs_device *device)
1676 struct btrfs_root *root = fs_info->chunk_root;
1678 struct btrfs_path *path;
1679 struct btrfs_dev_item *dev_item;
1680 struct extent_buffer *leaf;
1681 struct btrfs_key key;
1684 path = btrfs_alloc_path();
1688 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1689 key.type = BTRFS_DEV_ITEM_KEY;
1690 key.offset = device->devid;
1692 ret = btrfs_insert_empty_item(trans, root, path, &key,
1697 leaf = path->nodes[0];
1698 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1700 btrfs_set_device_id(leaf, dev_item, device->devid);
1701 btrfs_set_device_generation(leaf, dev_item, 0);
1702 btrfs_set_device_type(leaf, dev_item, device->type);
1703 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1704 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1705 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1706 btrfs_set_device_total_bytes(leaf, dev_item,
1707 btrfs_device_get_disk_total_bytes(device));
1708 btrfs_set_device_bytes_used(leaf, dev_item,
1709 btrfs_device_get_bytes_used(device));
1710 btrfs_set_device_group(leaf, dev_item, 0);
1711 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1712 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1713 btrfs_set_device_start_offset(leaf, dev_item, 0);
1715 ptr = btrfs_device_uuid(dev_item);
1716 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1717 ptr = btrfs_device_fsid(dev_item);
1718 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1719 btrfs_mark_buffer_dirty(leaf);
1723 btrfs_free_path(path);
1728 * Function to update ctime/mtime for a given device path.
1729 * Mainly used for ctime/mtime based probe like libblkid.
1731 static void update_dev_time(const char *path_name)
1735 filp = filp_open(path_name, O_RDWR, 0);
1738 file_update_time(filp);
1739 filp_close(filp, NULL);
1742 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1743 struct btrfs_device *device)
1745 struct btrfs_root *root = fs_info->chunk_root;
1747 struct btrfs_path *path;
1748 struct btrfs_key key;
1749 struct btrfs_trans_handle *trans;
1751 path = btrfs_alloc_path();
1755 trans = btrfs_start_transaction(root, 0);
1756 if (IS_ERR(trans)) {
1757 btrfs_free_path(path);
1758 return PTR_ERR(trans);
1760 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1761 key.type = BTRFS_DEV_ITEM_KEY;
1762 key.offset = device->devid;
1764 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1768 btrfs_abort_transaction(trans, ret);
1769 btrfs_end_transaction(trans);
1773 ret = btrfs_del_item(trans, root, path);
1775 btrfs_abort_transaction(trans, ret);
1776 btrfs_end_transaction(trans);
1780 btrfs_free_path(path);
1782 ret = btrfs_commit_transaction(trans);
1787 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1788 * filesystem. It's up to the caller to adjust that number regarding eg. device
1791 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1799 seq = read_seqbegin(&fs_info->profiles_lock);
1801 all_avail = fs_info->avail_data_alloc_bits |
1802 fs_info->avail_system_alloc_bits |
1803 fs_info->avail_metadata_alloc_bits;
1804 } while (read_seqretry(&fs_info->profiles_lock, seq));
1806 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1807 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1810 if (num_devices < btrfs_raid_array[i].devs_min) {
1811 int ret = btrfs_raid_array[i].mindev_error;
1821 static struct btrfs_device * btrfs_find_next_active_device(
1822 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1824 struct btrfs_device *next_device;
1826 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1827 if (next_device != device &&
1828 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1829 && next_device->bdev)
1837 * Helper function to check if the given device is part of s_bdev / latest_bdev
1838 * and replace it with the provided or the next active device, in the context
1839 * where this function called, there should be always be another device (or
1840 * this_dev) which is active.
1842 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1843 struct btrfs_device *device, struct btrfs_device *this_dev)
1845 struct btrfs_device *next_device;
1848 next_device = this_dev;
1850 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1852 ASSERT(next_device);
1854 if (fs_info->sb->s_bdev &&
1855 (fs_info->sb->s_bdev == device->bdev))
1856 fs_info->sb->s_bdev = next_device->bdev;
1858 if (fs_info->fs_devices->latest_bdev == device->bdev)
1859 fs_info->fs_devices->latest_bdev = next_device->bdev;
1862 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1865 struct btrfs_device *device;
1866 struct btrfs_fs_devices *cur_devices;
1867 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1871 mutex_lock(&uuid_mutex);
1873 num_devices = fs_devices->num_devices;
1874 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1875 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1876 WARN_ON(num_devices < 1);
1879 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1881 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1885 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1890 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1891 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1895 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1896 fs_info->fs_devices->rw_devices == 1) {
1897 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1901 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1902 mutex_lock(&fs_info->chunk_mutex);
1903 list_del_init(&device->dev_alloc_list);
1904 device->fs_devices->rw_devices--;
1905 mutex_unlock(&fs_info->chunk_mutex);
1908 mutex_unlock(&uuid_mutex);
1909 ret = btrfs_shrink_device(device, 0);
1910 mutex_lock(&uuid_mutex);
1915 * TODO: the superblock still includes this device in its num_devices
1916 * counter although write_all_supers() is not locked out. This
1917 * could give a filesystem state which requires a degraded mount.
1919 ret = btrfs_rm_dev_item(fs_info, device);
1923 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
1924 btrfs_scrub_cancel_dev(fs_info, device);
1927 * the device list mutex makes sure that we don't change
1928 * the device list while someone else is writing out all
1929 * the device supers. Whoever is writing all supers, should
1930 * lock the device list mutex before getting the number of
1931 * devices in the super block (super_copy). Conversely,
1932 * whoever updates the number of devices in the super block
1933 * (super_copy) should hold the device list mutex.
1937 * In normal cases the cur_devices == fs_devices. But in case
1938 * of deleting a seed device, the cur_devices should point to
1939 * its own fs_devices listed under the fs_devices->seed.
1941 cur_devices = device->fs_devices;
1942 mutex_lock(&fs_devices->device_list_mutex);
1943 list_del_rcu(&device->dev_list);
1945 cur_devices->num_devices--;
1946 cur_devices->total_devices--;
1947 /* Update total_devices of the parent fs_devices if it's seed */
1948 if (cur_devices != fs_devices)
1949 fs_devices->total_devices--;
1951 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1952 cur_devices->missing_devices--;
1954 btrfs_assign_next_active_device(fs_info, device, NULL);
1957 cur_devices->open_devices--;
1958 /* remove sysfs entry */
1959 btrfs_sysfs_rm_device_link(fs_devices, device);
1962 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1963 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
1964 mutex_unlock(&fs_devices->device_list_mutex);
1967 * at this point, the device is zero sized and detached from
1968 * the devices list. All that's left is to zero out the old
1969 * supers and free the device.
1971 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
1972 btrfs_scratch_superblocks(device->bdev, device->name->str);
1974 btrfs_close_bdev(device);
1975 call_rcu(&device->rcu, free_device_rcu);
1977 if (cur_devices->open_devices == 0) {
1978 while (fs_devices) {
1979 if (fs_devices->seed == cur_devices) {
1980 fs_devices->seed = cur_devices->seed;
1983 fs_devices = fs_devices->seed;
1985 cur_devices->seed = NULL;
1986 close_fs_devices(cur_devices);
1987 free_fs_devices(cur_devices);
1991 mutex_unlock(&uuid_mutex);
1995 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1996 mutex_lock(&fs_info->chunk_mutex);
1997 list_add(&device->dev_alloc_list,
1998 &fs_devices->alloc_list);
1999 device->fs_devices->rw_devices++;
2000 mutex_unlock(&fs_info->chunk_mutex);
2005 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2006 struct btrfs_device *srcdev)
2008 struct btrfs_fs_devices *fs_devices;
2010 lockdep_assert_held(&fs_info->fs_devices->device_list_mutex);
2013 * in case of fs with no seed, srcdev->fs_devices will point
2014 * to fs_devices of fs_info. However when the dev being replaced is
2015 * a seed dev it will point to the seed's local fs_devices. In short
2016 * srcdev will have its correct fs_devices in both the cases.
2018 fs_devices = srcdev->fs_devices;
2020 list_del_rcu(&srcdev->dev_list);
2021 list_del(&srcdev->dev_alloc_list);
2022 fs_devices->num_devices--;
2023 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2024 fs_devices->missing_devices--;
2026 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2027 fs_devices->rw_devices--;
2030 fs_devices->open_devices--;
2033 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2034 struct btrfs_device *srcdev)
2036 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2038 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2039 /* zero out the old super if it is writable */
2040 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2043 btrfs_close_bdev(srcdev);
2044 call_rcu(&srcdev->rcu, free_device_rcu);
2046 /* if this is no devs we rather delete the fs_devices */
2047 if (!fs_devices->num_devices) {
2048 struct btrfs_fs_devices *tmp_fs_devices;
2051 * On a mounted FS, num_devices can't be zero unless it's a
2052 * seed. In case of a seed device being replaced, the replace
2053 * target added to the sprout FS, so there will be no more
2054 * device left under the seed FS.
2056 ASSERT(fs_devices->seeding);
2058 tmp_fs_devices = fs_info->fs_devices;
2059 while (tmp_fs_devices) {
2060 if (tmp_fs_devices->seed == fs_devices) {
2061 tmp_fs_devices->seed = fs_devices->seed;
2064 tmp_fs_devices = tmp_fs_devices->seed;
2066 fs_devices->seed = NULL;
2067 close_fs_devices(fs_devices);
2068 free_fs_devices(fs_devices);
2072 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2073 struct btrfs_device *tgtdev)
2075 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2078 mutex_lock(&fs_devices->device_list_mutex);
2080 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2083 fs_devices->open_devices--;
2085 fs_devices->num_devices--;
2087 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2089 list_del_rcu(&tgtdev->dev_list);
2091 mutex_unlock(&fs_devices->device_list_mutex);
2094 * The update_dev_time() with in btrfs_scratch_superblocks()
2095 * may lead to a call to btrfs_show_devname() which will try
2096 * to hold device_list_mutex. And here this device
2097 * is already out of device list, so we don't have to hold
2098 * the device_list_mutex lock.
2100 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2102 btrfs_close_bdev(tgtdev);
2103 call_rcu(&tgtdev->rcu, free_device_rcu);
2106 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2107 const char *device_path,
2108 struct btrfs_device **device)
2111 struct btrfs_super_block *disk_super;
2114 struct block_device *bdev;
2115 struct buffer_head *bh;
2118 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2119 fs_info->bdev_holder, 0, &bdev, &bh);
2122 disk_super = (struct btrfs_super_block *)bh->b_data;
2123 devid = btrfs_stack_device_id(&disk_super->dev_item);
2124 dev_uuid = disk_super->dev_item.uuid;
2125 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2129 blkdev_put(bdev, FMODE_READ);
2133 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2134 const char *device_path,
2135 struct btrfs_device **device)
2138 if (strcmp(device_path, "missing") == 0) {
2139 struct list_head *devices;
2140 struct btrfs_device *tmp;
2142 devices = &fs_info->fs_devices->devices;
2143 list_for_each_entry(tmp, devices, dev_list) {
2144 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2145 &tmp->dev_state) && !tmp->bdev) {
2152 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2156 return btrfs_find_device_by_path(fs_info, device_path, device);
2161 * Lookup a device given by device id, or the path if the id is 0.
2163 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2164 const char *devpath,
2165 struct btrfs_device **device)
2171 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2175 if (!devpath || !devpath[0])
2178 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2185 * does all the dirty work required for changing file system's UUID.
2187 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2189 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2190 struct btrfs_fs_devices *old_devices;
2191 struct btrfs_fs_devices *seed_devices;
2192 struct btrfs_super_block *disk_super = fs_info->super_copy;
2193 struct btrfs_device *device;
2196 lockdep_assert_held(&uuid_mutex);
2197 if (!fs_devices->seeding)
2200 seed_devices = alloc_fs_devices(NULL);
2201 if (IS_ERR(seed_devices))
2202 return PTR_ERR(seed_devices);
2204 old_devices = clone_fs_devices(fs_devices);
2205 if (IS_ERR(old_devices)) {
2206 kfree(seed_devices);
2207 return PTR_ERR(old_devices);
2210 list_add(&old_devices->fs_list, &fs_uuids);
2212 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2213 seed_devices->opened = 1;
2214 INIT_LIST_HEAD(&seed_devices->devices);
2215 INIT_LIST_HEAD(&seed_devices->alloc_list);
2216 mutex_init(&seed_devices->device_list_mutex);
2218 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2219 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2221 list_for_each_entry(device, &seed_devices->devices, dev_list)
2222 device->fs_devices = seed_devices;
2224 mutex_lock(&fs_info->chunk_mutex);
2225 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2226 mutex_unlock(&fs_info->chunk_mutex);
2228 fs_devices->seeding = 0;
2229 fs_devices->num_devices = 0;
2230 fs_devices->open_devices = 0;
2231 fs_devices->missing_devices = 0;
2232 fs_devices->rotating = 0;
2233 fs_devices->seed = seed_devices;
2235 generate_random_uuid(fs_devices->fsid);
2236 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2237 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2238 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2240 super_flags = btrfs_super_flags(disk_super) &
2241 ~BTRFS_SUPER_FLAG_SEEDING;
2242 btrfs_set_super_flags(disk_super, super_flags);
2248 * Store the expected generation for seed devices in device items.
2250 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2251 struct btrfs_fs_info *fs_info)
2253 struct btrfs_root *root = fs_info->chunk_root;
2254 struct btrfs_path *path;
2255 struct extent_buffer *leaf;
2256 struct btrfs_dev_item *dev_item;
2257 struct btrfs_device *device;
2258 struct btrfs_key key;
2259 u8 fs_uuid[BTRFS_FSID_SIZE];
2260 u8 dev_uuid[BTRFS_UUID_SIZE];
2264 path = btrfs_alloc_path();
2268 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2270 key.type = BTRFS_DEV_ITEM_KEY;
2273 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2277 leaf = path->nodes[0];
2279 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2280 ret = btrfs_next_leaf(root, path);
2285 leaf = path->nodes[0];
2286 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2287 btrfs_release_path(path);
2291 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2292 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2293 key.type != BTRFS_DEV_ITEM_KEY)
2296 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2297 struct btrfs_dev_item);
2298 devid = btrfs_device_id(leaf, dev_item);
2299 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2301 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2303 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2304 BUG_ON(!device); /* Logic error */
2306 if (device->fs_devices->seeding) {
2307 btrfs_set_device_generation(leaf, dev_item,
2308 device->generation);
2309 btrfs_mark_buffer_dirty(leaf);
2317 btrfs_free_path(path);
2321 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2323 struct btrfs_root *root = fs_info->dev_root;
2324 struct request_queue *q;
2325 struct btrfs_trans_handle *trans;
2326 struct btrfs_device *device;
2327 struct block_device *bdev;
2328 struct super_block *sb = fs_info->sb;
2329 struct rcu_string *name;
2330 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2332 int seeding_dev = 0;
2334 bool unlocked = false;
2336 if (sb_rdonly(sb) && !fs_devices->seeding)
2339 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2340 fs_info->bdev_holder);
2342 return PTR_ERR(bdev);
2344 if (fs_devices->seeding) {
2346 down_write(&sb->s_umount);
2347 mutex_lock(&uuid_mutex);
2350 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2352 mutex_lock(&fs_devices->device_list_mutex);
2353 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2354 if (device->bdev == bdev) {
2357 &fs_devices->device_list_mutex);
2361 mutex_unlock(&fs_devices->device_list_mutex);
2363 device = btrfs_alloc_device(fs_info, NULL, NULL);
2364 if (IS_ERR(device)) {
2365 /* we can safely leave the fs_devices entry around */
2366 ret = PTR_ERR(device);
2370 name = rcu_string_strdup(device_path, GFP_KERNEL);
2373 goto error_free_device;
2375 rcu_assign_pointer(device->name, name);
2377 trans = btrfs_start_transaction(root, 0);
2378 if (IS_ERR(trans)) {
2379 ret = PTR_ERR(trans);
2380 goto error_free_device;
2383 q = bdev_get_queue(bdev);
2384 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2385 device->generation = trans->transid;
2386 device->io_width = fs_info->sectorsize;
2387 device->io_align = fs_info->sectorsize;
2388 device->sector_size = fs_info->sectorsize;
2389 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2390 fs_info->sectorsize);
2391 device->disk_total_bytes = device->total_bytes;
2392 device->commit_total_bytes = device->total_bytes;
2393 device->fs_info = fs_info;
2394 device->bdev = bdev;
2395 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2396 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2397 device->mode = FMODE_EXCL;
2398 device->dev_stats_valid = 1;
2399 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2402 sb->s_flags &= ~SB_RDONLY;
2403 ret = btrfs_prepare_sprout(fs_info);
2405 btrfs_abort_transaction(trans, ret);
2410 device->fs_devices = fs_devices;
2412 mutex_lock(&fs_devices->device_list_mutex);
2413 mutex_lock(&fs_info->chunk_mutex);
2414 list_add_rcu(&device->dev_list, &fs_devices->devices);
2415 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2416 fs_devices->num_devices++;
2417 fs_devices->open_devices++;
2418 fs_devices->rw_devices++;
2419 fs_devices->total_devices++;
2420 fs_devices->total_rw_bytes += device->total_bytes;
2422 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2424 if (!blk_queue_nonrot(q))
2425 fs_devices->rotating = 1;
2427 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2428 btrfs_set_super_total_bytes(fs_info->super_copy,
2429 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2431 tmp = btrfs_super_num_devices(fs_info->super_copy);
2432 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2434 /* add sysfs device entry */
2435 btrfs_sysfs_add_device_link(fs_devices, device);
2438 * we've got more storage, clear any full flags on the space
2441 btrfs_clear_space_info_full(fs_info);
2443 mutex_unlock(&fs_info->chunk_mutex);
2444 mutex_unlock(&fs_devices->device_list_mutex);
2447 mutex_lock(&fs_info->chunk_mutex);
2448 ret = init_first_rw_device(trans, fs_info);
2449 mutex_unlock(&fs_info->chunk_mutex);
2451 btrfs_abort_transaction(trans, ret);
2456 ret = btrfs_add_dev_item(trans, fs_info, device);
2458 btrfs_abort_transaction(trans, ret);
2463 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2465 ret = btrfs_finish_sprout(trans, fs_info);
2467 btrfs_abort_transaction(trans, ret);
2471 /* Sprouting would change fsid of the mounted root,
2472 * so rename the fsid on the sysfs
2474 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2476 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2478 "sysfs: failed to create fsid for sprout");
2481 ret = btrfs_commit_transaction(trans);
2484 mutex_unlock(&uuid_mutex);
2485 up_write(&sb->s_umount);
2488 if (ret) /* transaction commit */
2491 ret = btrfs_relocate_sys_chunks(fs_info);
2493 btrfs_handle_fs_error(fs_info, ret,
2494 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2495 trans = btrfs_attach_transaction(root);
2496 if (IS_ERR(trans)) {
2497 if (PTR_ERR(trans) == -ENOENT)
2499 ret = PTR_ERR(trans);
2503 ret = btrfs_commit_transaction(trans);
2506 /* Update ctime/mtime for libblkid */
2507 update_dev_time(device_path);
2511 btrfs_sysfs_rm_device_link(fs_devices, device);
2514 sb->s_flags |= SB_RDONLY;
2516 btrfs_end_transaction(trans);
2518 btrfs_free_device(device);
2520 blkdev_put(bdev, FMODE_EXCL);
2521 if (seeding_dev && !unlocked) {
2522 mutex_unlock(&uuid_mutex);
2523 up_write(&sb->s_umount);
2528 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2529 struct btrfs_device *device)
2532 struct btrfs_path *path;
2533 struct btrfs_root *root = device->fs_info->chunk_root;
2534 struct btrfs_dev_item *dev_item;
2535 struct extent_buffer *leaf;
2536 struct btrfs_key key;
2538 path = btrfs_alloc_path();
2542 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2543 key.type = BTRFS_DEV_ITEM_KEY;
2544 key.offset = device->devid;
2546 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2555 leaf = path->nodes[0];
2556 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2558 btrfs_set_device_id(leaf, dev_item, device->devid);
2559 btrfs_set_device_type(leaf, dev_item, device->type);
2560 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2561 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2562 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2563 btrfs_set_device_total_bytes(leaf, dev_item,
2564 btrfs_device_get_disk_total_bytes(device));
2565 btrfs_set_device_bytes_used(leaf, dev_item,
2566 btrfs_device_get_bytes_used(device));
2567 btrfs_mark_buffer_dirty(leaf);
2570 btrfs_free_path(path);
2574 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2575 struct btrfs_device *device, u64 new_size)
2577 struct btrfs_fs_info *fs_info = device->fs_info;
2578 struct btrfs_super_block *super_copy = fs_info->super_copy;
2579 struct btrfs_fs_devices *fs_devices;
2583 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2586 new_size = round_down(new_size, fs_info->sectorsize);
2588 mutex_lock(&fs_info->chunk_mutex);
2589 old_total = btrfs_super_total_bytes(super_copy);
2590 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2592 if (new_size <= device->total_bytes ||
2593 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2594 mutex_unlock(&fs_info->chunk_mutex);
2598 fs_devices = fs_info->fs_devices;
2600 btrfs_set_super_total_bytes(super_copy,
2601 round_down(old_total + diff, fs_info->sectorsize));
2602 device->fs_devices->total_rw_bytes += diff;
2604 btrfs_device_set_total_bytes(device, new_size);
2605 btrfs_device_set_disk_total_bytes(device, new_size);
2606 btrfs_clear_space_info_full(device->fs_info);
2607 if (list_empty(&device->resized_list))
2608 list_add_tail(&device->resized_list,
2609 &fs_devices->resized_devices);
2610 mutex_unlock(&fs_info->chunk_mutex);
2612 return btrfs_update_device(trans, device);
2615 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2616 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2618 struct btrfs_root *root = fs_info->chunk_root;
2620 struct btrfs_path *path;
2621 struct btrfs_key key;
2623 path = btrfs_alloc_path();
2627 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2628 key.offset = chunk_offset;
2629 key.type = BTRFS_CHUNK_ITEM_KEY;
2631 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2634 else if (ret > 0) { /* Logic error or corruption */
2635 btrfs_handle_fs_error(fs_info, -ENOENT,
2636 "Failed lookup while freeing chunk.");
2641 ret = btrfs_del_item(trans, root, path);
2643 btrfs_handle_fs_error(fs_info, ret,
2644 "Failed to delete chunk item.");
2646 btrfs_free_path(path);
2650 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2652 struct btrfs_super_block *super_copy = fs_info->super_copy;
2653 struct btrfs_disk_key *disk_key;
2654 struct btrfs_chunk *chunk;
2661 struct btrfs_key key;
2663 mutex_lock(&fs_info->chunk_mutex);
2664 array_size = btrfs_super_sys_array_size(super_copy);
2666 ptr = super_copy->sys_chunk_array;
2669 while (cur < array_size) {
2670 disk_key = (struct btrfs_disk_key *)ptr;
2671 btrfs_disk_key_to_cpu(&key, disk_key);
2673 len = sizeof(*disk_key);
2675 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2676 chunk = (struct btrfs_chunk *)(ptr + len);
2677 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2678 len += btrfs_chunk_item_size(num_stripes);
2683 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2684 key.offset == chunk_offset) {
2685 memmove(ptr, ptr + len, array_size - (cur + len));
2687 btrfs_set_super_sys_array_size(super_copy, array_size);
2693 mutex_unlock(&fs_info->chunk_mutex);
2697 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2698 u64 logical, u64 length)
2700 struct extent_map_tree *em_tree;
2701 struct extent_map *em;
2703 em_tree = &fs_info->mapping_tree.map_tree;
2704 read_lock(&em_tree->lock);
2705 em = lookup_extent_mapping(em_tree, logical, length);
2706 read_unlock(&em_tree->lock);
2709 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2711 return ERR_PTR(-EINVAL);
2714 if (em->start > logical || em->start + em->len < logical) {
2716 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2717 logical, length, em->start, em->start + em->len);
2718 free_extent_map(em);
2719 return ERR_PTR(-EINVAL);
2722 /* callers are responsible for dropping em's ref. */
2726 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2727 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2729 struct extent_map *em;
2730 struct map_lookup *map;
2731 u64 dev_extent_len = 0;
2733 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2735 em = get_chunk_map(fs_info, chunk_offset, 1);
2738 * This is a logic error, but we don't want to just rely on the
2739 * user having built with ASSERT enabled, so if ASSERT doesn't
2740 * do anything we still error out.
2745 map = em->map_lookup;
2746 mutex_lock(&fs_info->chunk_mutex);
2747 check_system_chunk(trans, map->type);
2748 mutex_unlock(&fs_info->chunk_mutex);
2751 * Take the device list mutex to prevent races with the final phase of
2752 * a device replace operation that replaces the device object associated
2753 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2755 mutex_lock(&fs_devices->device_list_mutex);
2756 for (i = 0; i < map->num_stripes; i++) {
2757 struct btrfs_device *device = map->stripes[i].dev;
2758 ret = btrfs_free_dev_extent(trans, device,
2759 map->stripes[i].physical,
2762 mutex_unlock(&fs_devices->device_list_mutex);
2763 btrfs_abort_transaction(trans, ret);
2767 if (device->bytes_used > 0) {
2768 mutex_lock(&fs_info->chunk_mutex);
2769 btrfs_device_set_bytes_used(device,
2770 device->bytes_used - dev_extent_len);
2771 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2772 btrfs_clear_space_info_full(fs_info);
2773 mutex_unlock(&fs_info->chunk_mutex);
2776 if (map->stripes[i].dev) {
2777 ret = btrfs_update_device(trans, map->stripes[i].dev);
2779 mutex_unlock(&fs_devices->device_list_mutex);
2780 btrfs_abort_transaction(trans, ret);
2785 mutex_unlock(&fs_devices->device_list_mutex);
2787 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2789 btrfs_abort_transaction(trans, ret);
2793 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2795 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2796 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2798 btrfs_abort_transaction(trans, ret);
2803 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2805 btrfs_abort_transaction(trans, ret);
2811 free_extent_map(em);
2815 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2817 struct btrfs_root *root = fs_info->chunk_root;
2818 struct btrfs_trans_handle *trans;
2822 * Prevent races with automatic removal of unused block groups.
2823 * After we relocate and before we remove the chunk with offset
2824 * chunk_offset, automatic removal of the block group can kick in,
2825 * resulting in a failure when calling btrfs_remove_chunk() below.
2827 * Make sure to acquire this mutex before doing a tree search (dev
2828 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2829 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2830 * we release the path used to search the chunk/dev tree and before
2831 * the current task acquires this mutex and calls us.
2833 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2835 ret = btrfs_can_relocate(fs_info, chunk_offset);
2839 /* step one, relocate all the extents inside this chunk */
2840 btrfs_scrub_pause(fs_info);
2841 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2842 btrfs_scrub_continue(fs_info);
2847 * We add the kobjects here (and after forcing data chunk creation)
2848 * since relocation is the only place we'll create chunks of a new
2849 * type at runtime. The only place where we'll remove the last
2850 * chunk of a type is the call immediately below this one. Even
2851 * so, we're protected against races with the cleaner thread since
2852 * we're covered by the delete_unused_bgs_mutex.
2854 btrfs_add_raid_kobjects(fs_info);
2856 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2858 if (IS_ERR(trans)) {
2859 ret = PTR_ERR(trans);
2860 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2865 * step two, delete the device extents and the
2866 * chunk tree entries
2868 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
2869 btrfs_end_transaction(trans);
2873 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2875 struct btrfs_root *chunk_root = fs_info->chunk_root;
2876 struct btrfs_path *path;
2877 struct extent_buffer *leaf;
2878 struct btrfs_chunk *chunk;
2879 struct btrfs_key key;
2880 struct btrfs_key found_key;
2882 bool retried = false;
2886 path = btrfs_alloc_path();
2891 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2892 key.offset = (u64)-1;
2893 key.type = BTRFS_CHUNK_ITEM_KEY;
2896 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2897 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2899 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2902 BUG_ON(ret == 0); /* Corruption */
2904 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2907 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2913 leaf = path->nodes[0];
2914 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2916 chunk = btrfs_item_ptr(leaf, path->slots[0],
2917 struct btrfs_chunk);
2918 chunk_type = btrfs_chunk_type(leaf, chunk);
2919 btrfs_release_path(path);
2921 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2922 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
2928 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2930 if (found_key.offset == 0)
2932 key.offset = found_key.offset - 1;
2935 if (failed && !retried) {
2939 } else if (WARN_ON(failed && retried)) {
2943 btrfs_free_path(path);
2948 * return 1 : allocate a data chunk successfully,
2949 * return <0: errors during allocating a data chunk,
2950 * return 0 : no need to allocate a data chunk.
2952 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
2955 struct btrfs_block_group_cache *cache;
2959 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2961 chunk_type = cache->flags;
2962 btrfs_put_block_group(cache);
2964 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
2965 spin_lock(&fs_info->data_sinfo->lock);
2966 bytes_used = fs_info->data_sinfo->bytes_used;
2967 spin_unlock(&fs_info->data_sinfo->lock);
2970 struct btrfs_trans_handle *trans;
2973 trans = btrfs_join_transaction(fs_info->tree_root);
2975 return PTR_ERR(trans);
2977 ret = btrfs_force_chunk_alloc(trans,
2978 BTRFS_BLOCK_GROUP_DATA);
2979 btrfs_end_transaction(trans);
2983 btrfs_add_raid_kobjects(fs_info);
2991 static int insert_balance_item(struct btrfs_fs_info *fs_info,
2992 struct btrfs_balance_control *bctl)
2994 struct btrfs_root *root = fs_info->tree_root;
2995 struct btrfs_trans_handle *trans;
2996 struct btrfs_balance_item *item;
2997 struct btrfs_disk_balance_args disk_bargs;
2998 struct btrfs_path *path;
2999 struct extent_buffer *leaf;
3000 struct btrfs_key key;
3003 path = btrfs_alloc_path();
3007 trans = btrfs_start_transaction(root, 0);
3008 if (IS_ERR(trans)) {
3009 btrfs_free_path(path);
3010 return PTR_ERR(trans);
3013 key.objectid = BTRFS_BALANCE_OBJECTID;
3014 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3017 ret = btrfs_insert_empty_item(trans, root, path, &key,
3022 leaf = path->nodes[0];
3023 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3025 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3027 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3028 btrfs_set_balance_data(leaf, item, &disk_bargs);
3029 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3030 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3031 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3032 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3034 btrfs_set_balance_flags(leaf, item, bctl->flags);
3036 btrfs_mark_buffer_dirty(leaf);
3038 btrfs_free_path(path);
3039 err = btrfs_commit_transaction(trans);
3045 static int del_balance_item(struct btrfs_fs_info *fs_info)
3047 struct btrfs_root *root = fs_info->tree_root;
3048 struct btrfs_trans_handle *trans;
3049 struct btrfs_path *path;
3050 struct btrfs_key key;
3053 path = btrfs_alloc_path();
3057 trans = btrfs_start_transaction(root, 0);
3058 if (IS_ERR(trans)) {
3059 btrfs_free_path(path);
3060 return PTR_ERR(trans);
3063 key.objectid = BTRFS_BALANCE_OBJECTID;
3064 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3067 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3075 ret = btrfs_del_item(trans, root, path);
3077 btrfs_free_path(path);
3078 err = btrfs_commit_transaction(trans);
3085 * This is a heuristic used to reduce the number of chunks balanced on
3086 * resume after balance was interrupted.
3088 static void update_balance_args(struct btrfs_balance_control *bctl)
3091 * Turn on soft mode for chunk types that were being converted.
3093 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3094 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3095 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3096 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3097 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3098 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3101 * Turn on usage filter if is not already used. The idea is
3102 * that chunks that we have already balanced should be
3103 * reasonably full. Don't do it for chunks that are being
3104 * converted - that will keep us from relocating unconverted
3105 * (albeit full) chunks.
3107 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3108 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3109 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3110 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3111 bctl->data.usage = 90;
3113 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3114 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3115 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3116 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3117 bctl->sys.usage = 90;
3119 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3120 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3121 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3122 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3123 bctl->meta.usage = 90;
3128 * Clear the balance status in fs_info and delete the balance item from disk.
3130 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3132 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3135 BUG_ON(!fs_info->balance_ctl);
3137 spin_lock(&fs_info->balance_lock);
3138 fs_info->balance_ctl = NULL;
3139 spin_unlock(&fs_info->balance_lock);
3142 ret = del_balance_item(fs_info);
3144 btrfs_handle_fs_error(fs_info, ret, NULL);
3148 * Balance filters. Return 1 if chunk should be filtered out
3149 * (should not be balanced).
3151 static int chunk_profiles_filter(u64 chunk_type,
3152 struct btrfs_balance_args *bargs)
3154 chunk_type = chunk_to_extended(chunk_type) &
3155 BTRFS_EXTENDED_PROFILE_MASK;
3157 if (bargs->profiles & chunk_type)
3163 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3164 struct btrfs_balance_args *bargs)
3166 struct btrfs_block_group_cache *cache;
3168 u64 user_thresh_min;
3169 u64 user_thresh_max;
3172 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3173 chunk_used = btrfs_block_group_used(&cache->item);
3175 if (bargs->usage_min == 0)
3176 user_thresh_min = 0;
3178 user_thresh_min = div_factor_fine(cache->key.offset,
3181 if (bargs->usage_max == 0)
3182 user_thresh_max = 1;
3183 else if (bargs->usage_max > 100)
3184 user_thresh_max = cache->key.offset;
3186 user_thresh_max = div_factor_fine(cache->key.offset,
3189 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3192 btrfs_put_block_group(cache);
3196 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3197 u64 chunk_offset, struct btrfs_balance_args *bargs)
3199 struct btrfs_block_group_cache *cache;
3200 u64 chunk_used, user_thresh;
3203 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3204 chunk_used = btrfs_block_group_used(&cache->item);
3206 if (bargs->usage_min == 0)
3208 else if (bargs->usage > 100)
3209 user_thresh = cache->key.offset;
3211 user_thresh = div_factor_fine(cache->key.offset,
3214 if (chunk_used < user_thresh)
3217 btrfs_put_block_group(cache);
3221 static int chunk_devid_filter(struct extent_buffer *leaf,
3222 struct btrfs_chunk *chunk,
3223 struct btrfs_balance_args *bargs)
3225 struct btrfs_stripe *stripe;
3226 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3229 for (i = 0; i < num_stripes; i++) {
3230 stripe = btrfs_stripe_nr(chunk, i);
3231 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3238 /* [pstart, pend) */
3239 static int chunk_drange_filter(struct extent_buffer *leaf,
3240 struct btrfs_chunk *chunk,
3241 struct btrfs_balance_args *bargs)
3243 struct btrfs_stripe *stripe;
3244 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3250 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3253 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3254 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3255 factor = num_stripes / 2;
3256 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3257 factor = num_stripes - 1;
3258 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3259 factor = num_stripes - 2;
3261 factor = num_stripes;
3264 for (i = 0; i < num_stripes; i++) {
3265 stripe = btrfs_stripe_nr(chunk, i);
3266 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3269 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3270 stripe_length = btrfs_chunk_length(leaf, chunk);
3271 stripe_length = div_u64(stripe_length, factor);
3273 if (stripe_offset < bargs->pend &&
3274 stripe_offset + stripe_length > bargs->pstart)
3281 /* [vstart, vend) */
3282 static int chunk_vrange_filter(struct extent_buffer *leaf,
3283 struct btrfs_chunk *chunk,
3285 struct btrfs_balance_args *bargs)
3287 if (chunk_offset < bargs->vend &&
3288 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3289 /* at least part of the chunk is inside this vrange */
3295 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3296 struct btrfs_chunk *chunk,
3297 struct btrfs_balance_args *bargs)
3299 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3301 if (bargs->stripes_min <= num_stripes
3302 && num_stripes <= bargs->stripes_max)
3308 static int chunk_soft_convert_filter(u64 chunk_type,
3309 struct btrfs_balance_args *bargs)
3311 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3314 chunk_type = chunk_to_extended(chunk_type) &
3315 BTRFS_EXTENDED_PROFILE_MASK;
3317 if (bargs->target == chunk_type)
3323 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3324 struct extent_buffer *leaf,
3325 struct btrfs_chunk *chunk, u64 chunk_offset)
3327 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3328 struct btrfs_balance_args *bargs = NULL;
3329 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3332 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3333 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3337 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3338 bargs = &bctl->data;
3339 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3341 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3342 bargs = &bctl->meta;
3344 /* profiles filter */
3345 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3346 chunk_profiles_filter(chunk_type, bargs)) {
3351 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3352 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3354 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3355 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3360 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3361 chunk_devid_filter(leaf, chunk, bargs)) {
3365 /* drange filter, makes sense only with devid filter */
3366 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3367 chunk_drange_filter(leaf, chunk, bargs)) {
3372 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3373 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3377 /* stripes filter */
3378 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3379 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3383 /* soft profile changing mode */
3384 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3385 chunk_soft_convert_filter(chunk_type, bargs)) {
3390 * limited by count, must be the last filter
3392 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3393 if (bargs->limit == 0)
3397 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3399 * Same logic as the 'limit' filter; the minimum cannot be
3400 * determined here because we do not have the global information
3401 * about the count of all chunks that satisfy the filters.
3403 if (bargs->limit_max == 0)
3412 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3414 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3415 struct btrfs_root *chunk_root = fs_info->chunk_root;
3416 struct btrfs_root *dev_root = fs_info->dev_root;
3417 struct list_head *devices;
3418 struct btrfs_device *device;
3422 struct btrfs_chunk *chunk;
3423 struct btrfs_path *path = NULL;
3424 struct btrfs_key key;
3425 struct btrfs_key found_key;
3426 struct btrfs_trans_handle *trans;
3427 struct extent_buffer *leaf;
3430 int enospc_errors = 0;
3431 bool counting = true;
3432 /* The single value limit and min/max limits use the same bytes in the */
3433 u64 limit_data = bctl->data.limit;
3434 u64 limit_meta = bctl->meta.limit;
3435 u64 limit_sys = bctl->sys.limit;
3439 int chunk_reserved = 0;
3441 /* step one make some room on all the devices */
3442 devices = &fs_info->fs_devices->devices;
3443 list_for_each_entry(device, devices, dev_list) {
3444 old_size = btrfs_device_get_total_bytes(device);
3445 size_to_free = div_factor(old_size, 1);
3446 size_to_free = min_t(u64, size_to_free, SZ_1M);
3447 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3448 btrfs_device_get_total_bytes(device) -
3449 btrfs_device_get_bytes_used(device) > size_to_free ||
3450 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3453 ret = btrfs_shrink_device(device, old_size - size_to_free);
3457 /* btrfs_shrink_device never returns ret > 0 */
3462 trans = btrfs_start_transaction(dev_root, 0);
3463 if (IS_ERR(trans)) {
3464 ret = PTR_ERR(trans);
3465 btrfs_info_in_rcu(fs_info,
3466 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3467 rcu_str_deref(device->name), ret,
3468 old_size, old_size - size_to_free);
3472 ret = btrfs_grow_device(trans, device, old_size);
3474 btrfs_end_transaction(trans);
3475 /* btrfs_grow_device never returns ret > 0 */
3477 btrfs_info_in_rcu(fs_info,
3478 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3479 rcu_str_deref(device->name), ret,
3480 old_size, old_size - size_to_free);
3484 btrfs_end_transaction(trans);
3487 /* step two, relocate all the chunks */
3488 path = btrfs_alloc_path();
3494 /* zero out stat counters */
3495 spin_lock(&fs_info->balance_lock);
3496 memset(&bctl->stat, 0, sizeof(bctl->stat));
3497 spin_unlock(&fs_info->balance_lock);
3501 * The single value limit and min/max limits use the same bytes
3504 bctl->data.limit = limit_data;
3505 bctl->meta.limit = limit_meta;
3506 bctl->sys.limit = limit_sys;
3508 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3509 key.offset = (u64)-1;
3510 key.type = BTRFS_CHUNK_ITEM_KEY;
3513 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3514 atomic_read(&fs_info->balance_cancel_req)) {
3519 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3520 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3522 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3527 * this shouldn't happen, it means the last relocate
3531 BUG(); /* FIXME break ? */
3533 ret = btrfs_previous_item(chunk_root, path, 0,
3534 BTRFS_CHUNK_ITEM_KEY);
3536 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3541 leaf = path->nodes[0];
3542 slot = path->slots[0];
3543 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3545 if (found_key.objectid != key.objectid) {
3546 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3550 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3551 chunk_type = btrfs_chunk_type(leaf, chunk);
3554 spin_lock(&fs_info->balance_lock);
3555 bctl->stat.considered++;
3556 spin_unlock(&fs_info->balance_lock);
3559 ret = should_balance_chunk(fs_info, leaf, chunk,
3562 btrfs_release_path(path);
3564 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3569 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3570 spin_lock(&fs_info->balance_lock);
3571 bctl->stat.expected++;
3572 spin_unlock(&fs_info->balance_lock);
3574 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3576 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3578 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3585 * Apply limit_min filter, no need to check if the LIMITS
3586 * filter is used, limit_min is 0 by default
3588 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3589 count_data < bctl->data.limit_min)
3590 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3591 count_meta < bctl->meta.limit_min)
3592 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3593 count_sys < bctl->sys.limit_min)) {
3594 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3598 if (!chunk_reserved) {
3600 * We may be relocating the only data chunk we have,
3601 * which could potentially end up with losing data's
3602 * raid profile, so lets allocate an empty one in
3605 ret = btrfs_may_alloc_data_chunk(fs_info,
3608 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3610 } else if (ret == 1) {
3615 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3616 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3617 if (ret && ret != -ENOSPC)
3619 if (ret == -ENOSPC) {
3622 spin_lock(&fs_info->balance_lock);
3623 bctl->stat.completed++;
3624 spin_unlock(&fs_info->balance_lock);
3627 if (found_key.offset == 0)
3629 key.offset = found_key.offset - 1;
3633 btrfs_release_path(path);
3638 btrfs_free_path(path);
3639 if (enospc_errors) {
3640 btrfs_info(fs_info, "%d enospc errors during balance",
3650 * alloc_profile_is_valid - see if a given profile is valid and reduced
3651 * @flags: profile to validate
3652 * @extended: if true @flags is treated as an extended profile
3654 static int alloc_profile_is_valid(u64 flags, int extended)
3656 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3657 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3659 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3661 /* 1) check that all other bits are zeroed */
3665 /* 2) see if profile is reduced */
3667 return !extended; /* "0" is valid for usual profiles */
3669 /* true if exactly one bit set */
3670 return (flags & (flags - 1)) == 0;
3673 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3675 /* cancel requested || normal exit path */
3676 return atomic_read(&fs_info->balance_cancel_req) ||
3677 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3678 atomic_read(&fs_info->balance_cancel_req) == 0);
3681 /* Non-zero return value signifies invalidity */
3682 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3685 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3686 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3687 (bctl_arg->target & ~allowed)));
3691 * Should be called with balance mutexe held
3693 int btrfs_balance(struct btrfs_fs_info *fs_info,
3694 struct btrfs_balance_control *bctl,
3695 struct btrfs_ioctl_balance_args *bargs)
3697 u64 meta_target, data_target;
3704 if (btrfs_fs_closing(fs_info) ||
3705 atomic_read(&fs_info->balance_pause_req) ||
3706 atomic_read(&fs_info->balance_cancel_req)) {
3711 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3712 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3716 * In case of mixed groups both data and meta should be picked,
3717 * and identical options should be given for both of them.
3719 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3720 if (mixed && (bctl->flags & allowed)) {
3721 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3722 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3723 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3725 "balance: mixed groups data and metadata options must be the same");
3731 num_devices = fs_info->fs_devices->num_devices;
3732 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
3733 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3734 BUG_ON(num_devices < 1);
3737 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
3738 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3739 if (num_devices > 1)
3740 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3741 if (num_devices > 2)
3742 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3743 if (num_devices > 3)
3744 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3745 BTRFS_BLOCK_GROUP_RAID6);
3746 if (validate_convert_profile(&bctl->data, allowed)) {
3747 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
3750 "balance: invalid convert data profile %s",
3751 get_raid_name(index));
3755 if (validate_convert_profile(&bctl->meta, allowed)) {
3756 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
3759 "balance: invalid convert metadata profile %s",
3760 get_raid_name(index));
3764 if (validate_convert_profile(&bctl->sys, allowed)) {
3765 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
3768 "balance: invalid convert system profile %s",
3769 get_raid_name(index));
3774 /* allow to reduce meta or sys integrity only if force set */
3775 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3776 BTRFS_BLOCK_GROUP_RAID10 |
3777 BTRFS_BLOCK_GROUP_RAID5 |
3778 BTRFS_BLOCK_GROUP_RAID6;
3780 seq = read_seqbegin(&fs_info->profiles_lock);
3782 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3783 (fs_info->avail_system_alloc_bits & allowed) &&
3784 !(bctl->sys.target & allowed)) ||
3785 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3786 (fs_info->avail_metadata_alloc_bits & allowed) &&
3787 !(bctl->meta.target & allowed))) {
3788 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3790 "balance: force reducing metadata integrity");
3793 "balance: reduces metadata integrity, use --force if you want this");
3798 } while (read_seqretry(&fs_info->profiles_lock, seq));
3800 /* if we're not converting, the target field is uninitialized */
3801 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3802 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3803 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3804 bctl->data.target : fs_info->avail_data_alloc_bits;
3805 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3806 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3807 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
3808 int data_index = btrfs_bg_flags_to_raid_index(data_target);
3811 "balance: metadata profile %s has lower redundancy than data profile %s",
3812 get_raid_name(meta_index), get_raid_name(data_index));
3815 ret = insert_balance_item(fs_info, bctl);
3816 if (ret && ret != -EEXIST)
3819 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3820 BUG_ON(ret == -EEXIST);
3821 BUG_ON(fs_info->balance_ctl);
3822 spin_lock(&fs_info->balance_lock);
3823 fs_info->balance_ctl = bctl;
3824 spin_unlock(&fs_info->balance_lock);
3826 BUG_ON(ret != -EEXIST);
3827 spin_lock(&fs_info->balance_lock);
3828 update_balance_args(bctl);
3829 spin_unlock(&fs_info->balance_lock);
3832 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
3833 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3834 mutex_unlock(&fs_info->balance_mutex);
3836 ret = __btrfs_balance(fs_info);
3838 mutex_lock(&fs_info->balance_mutex);
3839 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3842 memset(bargs, 0, sizeof(*bargs));
3843 btrfs_update_ioctl_balance_args(fs_info, bargs);
3846 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3847 balance_need_close(fs_info)) {
3848 reset_balance_state(fs_info);
3849 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3852 wake_up(&fs_info->balance_wait_q);
3856 if (bctl->flags & BTRFS_BALANCE_RESUME)
3857 reset_balance_state(fs_info);
3860 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3865 static int balance_kthread(void *data)
3867 struct btrfs_fs_info *fs_info = data;
3870 mutex_lock(&fs_info->balance_mutex);
3871 if (fs_info->balance_ctl) {
3872 btrfs_info(fs_info, "balance: resuming");
3873 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
3875 mutex_unlock(&fs_info->balance_mutex);
3880 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3882 struct task_struct *tsk;
3884 mutex_lock(&fs_info->balance_mutex);
3885 if (!fs_info->balance_ctl) {
3886 mutex_unlock(&fs_info->balance_mutex);
3889 mutex_unlock(&fs_info->balance_mutex);
3891 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
3892 btrfs_info(fs_info, "balance: resume skipped");
3897 * A ro->rw remount sequence should continue with the paused balance
3898 * regardless of who pauses it, system or the user as of now, so set
3901 spin_lock(&fs_info->balance_lock);
3902 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
3903 spin_unlock(&fs_info->balance_lock);
3905 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3906 return PTR_ERR_OR_ZERO(tsk);
3909 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3911 struct btrfs_balance_control *bctl;
3912 struct btrfs_balance_item *item;
3913 struct btrfs_disk_balance_args disk_bargs;
3914 struct btrfs_path *path;
3915 struct extent_buffer *leaf;
3916 struct btrfs_key key;
3919 path = btrfs_alloc_path();
3923 key.objectid = BTRFS_BALANCE_OBJECTID;
3924 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3927 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3930 if (ret > 0) { /* ret = -ENOENT; */
3935 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3941 leaf = path->nodes[0];
3942 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3944 bctl->flags = btrfs_balance_flags(leaf, item);
3945 bctl->flags |= BTRFS_BALANCE_RESUME;
3947 btrfs_balance_data(leaf, item, &disk_bargs);
3948 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3949 btrfs_balance_meta(leaf, item, &disk_bargs);
3950 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3951 btrfs_balance_sys(leaf, item, &disk_bargs);
3952 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3955 * This should never happen, as the paused balance state is recovered
3956 * during mount without any chance of other exclusive ops to collide.
3958 * This gives the exclusive op status to balance and keeps in paused
3959 * state until user intervention (cancel or umount). If the ownership
3960 * cannot be assigned, show a message but do not fail. The balance
3961 * is in a paused state and must have fs_info::balance_ctl properly
3964 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
3966 "balance: cannot set exclusive op status, resume manually");
3968 mutex_lock(&fs_info->balance_mutex);
3969 BUG_ON(fs_info->balance_ctl);
3970 spin_lock(&fs_info->balance_lock);
3971 fs_info->balance_ctl = bctl;
3972 spin_unlock(&fs_info->balance_lock);
3973 mutex_unlock(&fs_info->balance_mutex);
3975 btrfs_free_path(path);
3979 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3983 mutex_lock(&fs_info->balance_mutex);
3984 if (!fs_info->balance_ctl) {
3985 mutex_unlock(&fs_info->balance_mutex);
3989 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
3990 atomic_inc(&fs_info->balance_pause_req);
3991 mutex_unlock(&fs_info->balance_mutex);
3993 wait_event(fs_info->balance_wait_q,
3994 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
3996 mutex_lock(&fs_info->balance_mutex);
3997 /* we are good with balance_ctl ripped off from under us */
3998 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
3999 atomic_dec(&fs_info->balance_pause_req);
4004 mutex_unlock(&fs_info->balance_mutex);
4008 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4010 mutex_lock(&fs_info->balance_mutex);
4011 if (!fs_info->balance_ctl) {
4012 mutex_unlock(&fs_info->balance_mutex);
4017 * A paused balance with the item stored on disk can be resumed at
4018 * mount time if the mount is read-write. Otherwise it's still paused
4019 * and we must not allow cancelling as it deletes the item.
4021 if (sb_rdonly(fs_info->sb)) {
4022 mutex_unlock(&fs_info->balance_mutex);
4026 atomic_inc(&fs_info->balance_cancel_req);
4028 * if we are running just wait and return, balance item is
4029 * deleted in btrfs_balance in this case
4031 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4032 mutex_unlock(&fs_info->balance_mutex);
4033 wait_event(fs_info->balance_wait_q,
4034 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4035 mutex_lock(&fs_info->balance_mutex);
4037 mutex_unlock(&fs_info->balance_mutex);
4039 * Lock released to allow other waiters to continue, we'll
4040 * reexamine the status again.
4042 mutex_lock(&fs_info->balance_mutex);
4044 if (fs_info->balance_ctl) {
4045 reset_balance_state(fs_info);
4046 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4047 btrfs_info(fs_info, "balance: canceled");
4051 BUG_ON(fs_info->balance_ctl ||
4052 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4053 atomic_dec(&fs_info->balance_cancel_req);
4054 mutex_unlock(&fs_info->balance_mutex);
4058 static int btrfs_uuid_scan_kthread(void *data)
4060 struct btrfs_fs_info *fs_info = data;
4061 struct btrfs_root *root = fs_info->tree_root;
4062 struct btrfs_key key;
4063 struct btrfs_path *path = NULL;
4065 struct extent_buffer *eb;
4067 struct btrfs_root_item root_item;
4069 struct btrfs_trans_handle *trans = NULL;
4071 path = btrfs_alloc_path();
4078 key.type = BTRFS_ROOT_ITEM_KEY;
4082 ret = btrfs_search_forward(root, &key, path,
4083 BTRFS_OLDEST_GENERATION);
4090 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4091 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4092 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4093 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4096 eb = path->nodes[0];
4097 slot = path->slots[0];
4098 item_size = btrfs_item_size_nr(eb, slot);
4099 if (item_size < sizeof(root_item))
4102 read_extent_buffer(eb, &root_item,
4103 btrfs_item_ptr_offset(eb, slot),
4104 (int)sizeof(root_item));
4105 if (btrfs_root_refs(&root_item) == 0)
4108 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4109 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4113 btrfs_release_path(path);
4115 * 1 - subvol uuid item
4116 * 1 - received_subvol uuid item
4118 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4119 if (IS_ERR(trans)) {
4120 ret = PTR_ERR(trans);
4128 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4129 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4130 BTRFS_UUID_KEY_SUBVOL,
4133 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4139 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4140 ret = btrfs_uuid_tree_add(trans,
4141 root_item.received_uuid,
4142 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4145 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4153 ret = btrfs_end_transaction(trans);
4159 btrfs_release_path(path);
4160 if (key.offset < (u64)-1) {
4162 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4164 key.type = BTRFS_ROOT_ITEM_KEY;
4165 } else if (key.objectid < (u64)-1) {
4167 key.type = BTRFS_ROOT_ITEM_KEY;
4176 btrfs_free_path(path);
4177 if (trans && !IS_ERR(trans))
4178 btrfs_end_transaction(trans);
4180 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4182 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4183 up(&fs_info->uuid_tree_rescan_sem);
4188 * Callback for btrfs_uuid_tree_iterate().
4190 * 0 check succeeded, the entry is not outdated.
4191 * < 0 if an error occurred.
4192 * > 0 if the check failed, which means the caller shall remove the entry.
4194 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4195 u8 *uuid, u8 type, u64 subid)
4197 struct btrfs_key key;
4199 struct btrfs_root *subvol_root;
4201 if (type != BTRFS_UUID_KEY_SUBVOL &&
4202 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4205 key.objectid = subid;
4206 key.type = BTRFS_ROOT_ITEM_KEY;
4207 key.offset = (u64)-1;
4208 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4209 if (IS_ERR(subvol_root)) {
4210 ret = PTR_ERR(subvol_root);
4217 case BTRFS_UUID_KEY_SUBVOL:
4218 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4221 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4222 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4232 static int btrfs_uuid_rescan_kthread(void *data)
4234 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4238 * 1st step is to iterate through the existing UUID tree and
4239 * to delete all entries that contain outdated data.
4240 * 2nd step is to add all missing entries to the UUID tree.
4242 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4244 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4245 up(&fs_info->uuid_tree_rescan_sem);
4248 return btrfs_uuid_scan_kthread(data);
4251 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4253 struct btrfs_trans_handle *trans;
4254 struct btrfs_root *tree_root = fs_info->tree_root;
4255 struct btrfs_root *uuid_root;
4256 struct task_struct *task;
4263 trans = btrfs_start_transaction(tree_root, 2);
4265 return PTR_ERR(trans);
4267 uuid_root = btrfs_create_tree(trans, fs_info,
4268 BTRFS_UUID_TREE_OBJECTID);
4269 if (IS_ERR(uuid_root)) {
4270 ret = PTR_ERR(uuid_root);
4271 btrfs_abort_transaction(trans, ret);
4272 btrfs_end_transaction(trans);
4276 fs_info->uuid_root = uuid_root;
4278 ret = btrfs_commit_transaction(trans);
4282 down(&fs_info->uuid_tree_rescan_sem);
4283 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4285 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4286 btrfs_warn(fs_info, "failed to start uuid_scan task");
4287 up(&fs_info->uuid_tree_rescan_sem);
4288 return PTR_ERR(task);
4294 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4296 struct task_struct *task;
4298 down(&fs_info->uuid_tree_rescan_sem);
4299 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4301 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4302 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4303 up(&fs_info->uuid_tree_rescan_sem);
4304 return PTR_ERR(task);
4311 * shrinking a device means finding all of the device extents past
4312 * the new size, and then following the back refs to the chunks.
4313 * The chunk relocation code actually frees the device extent
4315 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4317 struct btrfs_fs_info *fs_info = device->fs_info;
4318 struct btrfs_root *root = fs_info->dev_root;
4319 struct btrfs_trans_handle *trans;
4320 struct btrfs_dev_extent *dev_extent = NULL;
4321 struct btrfs_path *path;
4327 bool retried = false;
4328 bool checked_pending_chunks = false;
4329 struct extent_buffer *l;
4330 struct btrfs_key key;
4331 struct btrfs_super_block *super_copy = fs_info->super_copy;
4332 u64 old_total = btrfs_super_total_bytes(super_copy);
4333 u64 old_size = btrfs_device_get_total_bytes(device);
4336 new_size = round_down(new_size, fs_info->sectorsize);
4337 diff = round_down(old_size - new_size, fs_info->sectorsize);
4339 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4342 path = btrfs_alloc_path();
4346 path->reada = READA_BACK;
4348 mutex_lock(&fs_info->chunk_mutex);
4350 btrfs_device_set_total_bytes(device, new_size);
4351 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4352 device->fs_devices->total_rw_bytes -= diff;
4353 atomic64_sub(diff, &fs_info->free_chunk_space);
4355 mutex_unlock(&fs_info->chunk_mutex);
4358 key.objectid = device->devid;
4359 key.offset = (u64)-1;
4360 key.type = BTRFS_DEV_EXTENT_KEY;
4363 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4364 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4366 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4370 ret = btrfs_previous_item(root, path, 0, key.type);
4372 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4377 btrfs_release_path(path);
4382 slot = path->slots[0];
4383 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4385 if (key.objectid != device->devid) {
4386 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4387 btrfs_release_path(path);
4391 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4392 length = btrfs_dev_extent_length(l, dev_extent);
4394 if (key.offset + length <= new_size) {
4395 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4396 btrfs_release_path(path);
4400 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4401 btrfs_release_path(path);
4404 * We may be relocating the only data chunk we have,
4405 * which could potentially end up with losing data's
4406 * raid profile, so lets allocate an empty one in
4409 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4411 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4415 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4416 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4417 if (ret && ret != -ENOSPC)
4421 } while (key.offset-- > 0);
4423 if (failed && !retried) {
4427 } else if (failed && retried) {
4432 /* Shrinking succeeded, else we would be at "done". */
4433 trans = btrfs_start_transaction(root, 0);
4434 if (IS_ERR(trans)) {
4435 ret = PTR_ERR(trans);
4439 mutex_lock(&fs_info->chunk_mutex);
4442 * We checked in the above loop all device extents that were already in
4443 * the device tree. However before we have updated the device's
4444 * total_bytes to the new size, we might have had chunk allocations that
4445 * have not complete yet (new block groups attached to transaction
4446 * handles), and therefore their device extents were not yet in the
4447 * device tree and we missed them in the loop above. So if we have any
4448 * pending chunk using a device extent that overlaps the device range
4449 * that we can not use anymore, commit the current transaction and
4450 * repeat the search on the device tree - this way we guarantee we will
4451 * not have chunks using device extents that end beyond 'new_size'.
4453 if (!checked_pending_chunks) {
4454 u64 start = new_size;
4455 u64 len = old_size - new_size;
4457 if (contains_pending_extent(trans->transaction, device,
4459 mutex_unlock(&fs_info->chunk_mutex);
4460 checked_pending_chunks = true;
4463 ret = btrfs_commit_transaction(trans);
4470 btrfs_device_set_disk_total_bytes(device, new_size);
4471 if (list_empty(&device->resized_list))
4472 list_add_tail(&device->resized_list,
4473 &fs_info->fs_devices->resized_devices);
4475 WARN_ON(diff > old_total);
4476 btrfs_set_super_total_bytes(super_copy,
4477 round_down(old_total - diff, fs_info->sectorsize));
4478 mutex_unlock(&fs_info->chunk_mutex);
4480 /* Now btrfs_update_device() will change the on-disk size. */
4481 ret = btrfs_update_device(trans, device);
4482 btrfs_end_transaction(trans);
4484 btrfs_free_path(path);
4486 mutex_lock(&fs_info->chunk_mutex);
4487 btrfs_device_set_total_bytes(device, old_size);
4488 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4489 device->fs_devices->total_rw_bytes += diff;
4490 atomic64_add(diff, &fs_info->free_chunk_space);
4491 mutex_unlock(&fs_info->chunk_mutex);
4496 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4497 struct btrfs_key *key,
4498 struct btrfs_chunk *chunk, int item_size)
4500 struct btrfs_super_block *super_copy = fs_info->super_copy;
4501 struct btrfs_disk_key disk_key;
4505 mutex_lock(&fs_info->chunk_mutex);
4506 array_size = btrfs_super_sys_array_size(super_copy);
4507 if (array_size + item_size + sizeof(disk_key)
4508 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4509 mutex_unlock(&fs_info->chunk_mutex);
4513 ptr = super_copy->sys_chunk_array + array_size;
4514 btrfs_cpu_key_to_disk(&disk_key, key);
4515 memcpy(ptr, &disk_key, sizeof(disk_key));
4516 ptr += sizeof(disk_key);
4517 memcpy(ptr, chunk, item_size);
4518 item_size += sizeof(disk_key);
4519 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4520 mutex_unlock(&fs_info->chunk_mutex);
4526 * sort the devices in descending order by max_avail, total_avail
4528 static int btrfs_cmp_device_info(const void *a, const void *b)
4530 const struct btrfs_device_info *di_a = a;
4531 const struct btrfs_device_info *di_b = b;
4533 if (di_a->max_avail > di_b->max_avail)
4535 if (di_a->max_avail < di_b->max_avail)
4537 if (di_a->total_avail > di_b->total_avail)
4539 if (di_a->total_avail < di_b->total_avail)
4544 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4546 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4549 btrfs_set_fs_incompat(info, RAID56);
4552 #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \
4553 - sizeof(struct btrfs_chunk)) \
4554 / sizeof(struct btrfs_stripe) + 1)
4556 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4557 - 2 * sizeof(struct btrfs_disk_key) \
4558 - 2 * sizeof(struct btrfs_chunk)) \
4559 / sizeof(struct btrfs_stripe) + 1)
4561 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4562 u64 start, u64 type)
4564 struct btrfs_fs_info *info = trans->fs_info;
4565 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4566 struct btrfs_device *device;
4567 struct map_lookup *map = NULL;
4568 struct extent_map_tree *em_tree;
4569 struct extent_map *em;
4570 struct btrfs_device_info *devices_info = NULL;
4572 int num_stripes; /* total number of stripes to allocate */
4573 int data_stripes; /* number of stripes that count for
4575 int sub_stripes; /* sub_stripes info for map */
4576 int dev_stripes; /* stripes per dev */
4577 int devs_max; /* max devs to use */
4578 int devs_min; /* min devs needed */
4579 int devs_increment; /* ndevs has to be a multiple of this */
4580 int ncopies; /* how many copies to data has */
4582 u64 max_stripe_size;
4591 BUG_ON(!alloc_profile_is_valid(type, 0));
4593 if (list_empty(&fs_devices->alloc_list)) {
4594 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4595 btrfs_debug(info, "%s: no writable device", __func__);
4599 index = btrfs_bg_flags_to_raid_index(type);
4601 sub_stripes = btrfs_raid_array[index].sub_stripes;
4602 dev_stripes = btrfs_raid_array[index].dev_stripes;
4603 devs_max = btrfs_raid_array[index].devs_max;
4604 devs_min = btrfs_raid_array[index].devs_min;
4605 devs_increment = btrfs_raid_array[index].devs_increment;
4606 ncopies = btrfs_raid_array[index].ncopies;
4608 if (type & BTRFS_BLOCK_GROUP_DATA) {
4609 max_stripe_size = SZ_1G;
4610 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4612 devs_max = BTRFS_MAX_DEVS(info);
4613 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4614 /* for larger filesystems, use larger metadata chunks */
4615 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4616 max_stripe_size = SZ_1G;
4618 max_stripe_size = SZ_256M;
4619 max_chunk_size = max_stripe_size;
4621 devs_max = BTRFS_MAX_DEVS(info);
4622 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4623 max_stripe_size = SZ_32M;
4624 max_chunk_size = 2 * max_stripe_size;
4626 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4628 btrfs_err(info, "invalid chunk type 0x%llx requested",
4633 /* we don't want a chunk larger than 10% of writeable space */
4634 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4637 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4643 * in the first pass through the devices list, we gather information
4644 * about the available holes on each device.
4647 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4651 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4653 "BTRFS: read-only device in alloc_list\n");
4657 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4658 &device->dev_state) ||
4659 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4662 if (device->total_bytes > device->bytes_used)
4663 total_avail = device->total_bytes - device->bytes_used;
4667 /* If there is no space on this device, skip it. */
4668 if (total_avail == 0)
4671 ret = find_free_dev_extent(trans, device,
4672 max_stripe_size * dev_stripes,
4673 &dev_offset, &max_avail);
4674 if (ret && ret != -ENOSPC)
4678 max_avail = max_stripe_size * dev_stripes;
4680 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4681 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4683 "%s: devid %llu has no free space, have=%llu want=%u",
4684 __func__, device->devid, max_avail,
4685 BTRFS_STRIPE_LEN * dev_stripes);
4689 if (ndevs == fs_devices->rw_devices) {
4690 WARN(1, "%s: found more than %llu devices\n",
4691 __func__, fs_devices->rw_devices);
4694 devices_info[ndevs].dev_offset = dev_offset;
4695 devices_info[ndevs].max_avail = max_avail;
4696 devices_info[ndevs].total_avail = total_avail;
4697 devices_info[ndevs].dev = device;
4702 * now sort the devices by hole size / available space
4704 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4705 btrfs_cmp_device_info, NULL);
4707 /* round down to number of usable stripes */
4708 ndevs = round_down(ndevs, devs_increment);
4710 if (ndevs < devs_min) {
4712 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4714 "%s: not enough devices with free space: have=%d minimum required=%d",
4715 __func__, ndevs, devs_min);
4720 ndevs = min(ndevs, devs_max);
4723 * The primary goal is to maximize the number of stripes, so use as
4724 * many devices as possible, even if the stripes are not maximum sized.
4726 * The DUP profile stores more than one stripe per device, the
4727 * max_avail is the total size so we have to adjust.
4729 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4730 num_stripes = ndevs * dev_stripes;
4733 * this will have to be fixed for RAID1 and RAID10 over
4736 data_stripes = num_stripes / ncopies;
4738 if (type & BTRFS_BLOCK_GROUP_RAID5)
4739 data_stripes = num_stripes - 1;
4741 if (type & BTRFS_BLOCK_GROUP_RAID6)
4742 data_stripes = num_stripes - 2;
4745 * Use the number of data stripes to figure out how big this chunk
4746 * is really going to be in terms of logical address space,
4747 * and compare that answer with the max chunk size
4749 if (stripe_size * data_stripes > max_chunk_size) {
4750 stripe_size = div_u64(max_chunk_size, data_stripes);
4752 /* bump the answer up to a 16MB boundary */
4753 stripe_size = round_up(stripe_size, SZ_16M);
4756 * But don't go higher than the limits we found while searching
4759 stripe_size = min(devices_info[ndevs - 1].max_avail,
4763 /* align to BTRFS_STRIPE_LEN */
4764 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4766 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4771 map->num_stripes = num_stripes;
4773 for (i = 0; i < ndevs; ++i) {
4774 for (j = 0; j < dev_stripes; ++j) {
4775 int s = i * dev_stripes + j;
4776 map->stripes[s].dev = devices_info[i].dev;
4777 map->stripes[s].physical = devices_info[i].dev_offset +
4781 map->stripe_len = BTRFS_STRIPE_LEN;
4782 map->io_align = BTRFS_STRIPE_LEN;
4783 map->io_width = BTRFS_STRIPE_LEN;
4785 map->sub_stripes = sub_stripes;
4787 num_bytes = stripe_size * data_stripes;
4789 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4791 em = alloc_extent_map();
4797 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4798 em->map_lookup = map;
4800 em->len = num_bytes;
4801 em->block_start = 0;
4802 em->block_len = em->len;
4803 em->orig_block_len = stripe_size;
4805 em_tree = &info->mapping_tree.map_tree;
4806 write_lock(&em_tree->lock);
4807 ret = add_extent_mapping(em_tree, em, 0);
4809 write_unlock(&em_tree->lock);
4810 free_extent_map(em);
4814 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4815 refcount_inc(&em->refs);
4816 write_unlock(&em_tree->lock);
4818 ret = btrfs_make_block_group(trans, 0, type, start, num_bytes);
4820 goto error_del_extent;
4822 for (i = 0; i < map->num_stripes; i++) {
4823 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4824 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4827 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4829 free_extent_map(em);
4830 check_raid56_incompat_flag(info, type);
4832 kfree(devices_info);
4836 write_lock(&em_tree->lock);
4837 remove_extent_mapping(em_tree, em);
4838 write_unlock(&em_tree->lock);
4840 /* One for our allocation */
4841 free_extent_map(em);
4842 /* One for the tree reference */
4843 free_extent_map(em);
4844 /* One for the pending_chunks list reference */
4845 free_extent_map(em);
4847 kfree(devices_info);
4851 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4852 struct btrfs_fs_info *fs_info,
4853 u64 chunk_offset, u64 chunk_size)
4855 struct btrfs_root *extent_root = fs_info->extent_root;
4856 struct btrfs_root *chunk_root = fs_info->chunk_root;
4857 struct btrfs_key key;
4858 struct btrfs_device *device;
4859 struct btrfs_chunk *chunk;
4860 struct btrfs_stripe *stripe;
4861 struct extent_map *em;
4862 struct map_lookup *map;
4869 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4873 map = em->map_lookup;
4874 item_size = btrfs_chunk_item_size(map->num_stripes);
4875 stripe_size = em->orig_block_len;
4877 chunk = kzalloc(item_size, GFP_NOFS);
4884 * Take the device list mutex to prevent races with the final phase of
4885 * a device replace operation that replaces the device object associated
4886 * with the map's stripes, because the device object's id can change
4887 * at any time during that final phase of the device replace operation
4888 * (dev-replace.c:btrfs_dev_replace_finishing()).
4890 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4891 for (i = 0; i < map->num_stripes; i++) {
4892 device = map->stripes[i].dev;
4893 dev_offset = map->stripes[i].physical;
4895 ret = btrfs_update_device(trans, device);
4898 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
4899 dev_offset, stripe_size);
4904 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4908 stripe = &chunk->stripe;
4909 for (i = 0; i < map->num_stripes; i++) {
4910 device = map->stripes[i].dev;
4911 dev_offset = map->stripes[i].physical;
4913 btrfs_set_stack_stripe_devid(stripe, device->devid);
4914 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4915 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4918 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4920 btrfs_set_stack_chunk_length(chunk, chunk_size);
4921 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4922 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4923 btrfs_set_stack_chunk_type(chunk, map->type);
4924 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4925 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4926 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4927 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
4928 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4930 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4931 key.type = BTRFS_CHUNK_ITEM_KEY;
4932 key.offset = chunk_offset;
4934 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4935 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4937 * TODO: Cleanup of inserted chunk root in case of
4940 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
4945 free_extent_map(em);
4950 * Chunk allocation falls into two parts. The first part does works
4951 * that make the new allocated chunk useable, but not do any operation
4952 * that modifies the chunk tree. The second part does the works that
4953 * require modifying the chunk tree. This division is important for the
4954 * bootstrap process of adding storage to a seed btrfs.
4956 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
4960 lockdep_assert_held(&trans->fs_info->chunk_mutex);
4961 chunk_offset = find_next_chunk(trans->fs_info);
4962 return __btrfs_alloc_chunk(trans, chunk_offset, type);
4965 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4966 struct btrfs_fs_info *fs_info)
4969 u64 sys_chunk_offset;
4973 chunk_offset = find_next_chunk(fs_info);
4974 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
4975 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
4979 sys_chunk_offset = find_next_chunk(fs_info);
4980 alloc_profile = btrfs_system_alloc_profile(fs_info);
4981 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
4985 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
4989 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
4990 BTRFS_BLOCK_GROUP_RAID10 |
4991 BTRFS_BLOCK_GROUP_RAID5 |
4992 BTRFS_BLOCK_GROUP_DUP)) {
4994 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5003 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5005 struct extent_map *em;
5006 struct map_lookup *map;
5011 em = get_chunk_map(fs_info, chunk_offset, 1);
5015 map = em->map_lookup;
5016 for (i = 0; i < map->num_stripes; i++) {
5017 if (test_bit(BTRFS_DEV_STATE_MISSING,
5018 &map->stripes[i].dev->dev_state)) {
5022 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5023 &map->stripes[i].dev->dev_state)) {
5030 * If the number of missing devices is larger than max errors,
5031 * we can not write the data into that chunk successfully, so
5034 if (miss_ndevs > btrfs_chunk_max_errors(map))
5037 free_extent_map(em);
5041 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5043 extent_map_tree_init(&tree->map_tree);
5046 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5048 struct extent_map *em;
5051 write_lock(&tree->map_tree.lock);
5052 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5054 remove_extent_mapping(&tree->map_tree, em);
5055 write_unlock(&tree->map_tree.lock);
5059 free_extent_map(em);
5060 /* once for the tree */
5061 free_extent_map(em);
5065 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5067 struct extent_map *em;
5068 struct map_lookup *map;
5071 em = get_chunk_map(fs_info, logical, len);
5074 * We could return errors for these cases, but that could get
5075 * ugly and we'd probably do the same thing which is just not do
5076 * anything else and exit, so return 1 so the callers don't try
5077 * to use other copies.
5081 map = em->map_lookup;
5082 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5083 ret = map->num_stripes;
5084 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5085 ret = map->sub_stripes;
5086 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5088 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5090 * There could be two corrupted data stripes, we need
5091 * to loop retry in order to rebuild the correct data.
5093 * Fail a stripe at a time on every retry except the
5094 * stripe under reconstruction.
5096 ret = map->num_stripes;
5099 free_extent_map(em);
5101 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
5102 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5103 fs_info->dev_replace.tgtdev)
5105 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
5110 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5113 struct extent_map *em;
5114 struct map_lookup *map;
5115 unsigned long len = fs_info->sectorsize;
5117 em = get_chunk_map(fs_info, logical, len);
5119 if (!WARN_ON(IS_ERR(em))) {
5120 map = em->map_lookup;
5121 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5122 len = map->stripe_len * nr_data_stripes(map);
5123 free_extent_map(em);
5128 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5130 struct extent_map *em;
5131 struct map_lookup *map;
5134 em = get_chunk_map(fs_info, logical, len);
5136 if(!WARN_ON(IS_ERR(em))) {
5137 map = em->map_lookup;
5138 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5140 free_extent_map(em);
5145 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5146 struct map_lookup *map, int first,
5147 int dev_replace_is_ongoing)
5151 int preferred_mirror;
5153 struct btrfs_device *srcdev;
5156 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5158 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5159 num_stripes = map->sub_stripes;
5161 num_stripes = map->num_stripes;
5163 preferred_mirror = first + current->pid % num_stripes;
5165 if (dev_replace_is_ongoing &&
5166 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5167 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5168 srcdev = fs_info->dev_replace.srcdev;
5173 * try to avoid the drive that is the source drive for a
5174 * dev-replace procedure, only choose it if no other non-missing
5175 * mirror is available
5177 for (tolerance = 0; tolerance < 2; tolerance++) {
5178 if (map->stripes[preferred_mirror].dev->bdev &&
5179 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5180 return preferred_mirror;
5181 for (i = first; i < first + num_stripes; i++) {
5182 if (map->stripes[i].dev->bdev &&
5183 (tolerance || map->stripes[i].dev != srcdev))
5188 /* we couldn't find one that doesn't fail. Just return something
5189 * and the io error handling code will clean up eventually
5191 return preferred_mirror;
5194 static inline int parity_smaller(u64 a, u64 b)
5199 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5200 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5202 struct btrfs_bio_stripe s;
5209 for (i = 0; i < num_stripes - 1; i++) {
5210 if (parity_smaller(bbio->raid_map[i],
5211 bbio->raid_map[i+1])) {
5212 s = bbio->stripes[i];
5213 l = bbio->raid_map[i];
5214 bbio->stripes[i] = bbio->stripes[i+1];
5215 bbio->raid_map[i] = bbio->raid_map[i+1];
5216 bbio->stripes[i+1] = s;
5217 bbio->raid_map[i+1] = l;
5225 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5227 struct btrfs_bio *bbio = kzalloc(
5228 /* the size of the btrfs_bio */
5229 sizeof(struct btrfs_bio) +
5230 /* plus the variable array for the stripes */
5231 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5232 /* plus the variable array for the tgt dev */
5233 sizeof(int) * (real_stripes) +
5235 * plus the raid_map, which includes both the tgt dev
5238 sizeof(u64) * (total_stripes),
5239 GFP_NOFS|__GFP_NOFAIL);
5241 atomic_set(&bbio->error, 0);
5242 refcount_set(&bbio->refs, 1);
5247 void btrfs_get_bbio(struct btrfs_bio *bbio)
5249 WARN_ON(!refcount_read(&bbio->refs));
5250 refcount_inc(&bbio->refs);
5253 void btrfs_put_bbio(struct btrfs_bio *bbio)
5257 if (refcount_dec_and_test(&bbio->refs))
5261 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5263 * Please note that, discard won't be sent to target device of device
5266 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5267 u64 logical, u64 length,
5268 struct btrfs_bio **bbio_ret)
5270 struct extent_map *em;
5271 struct map_lookup *map;
5272 struct btrfs_bio *bbio;
5276 u64 stripe_end_offset;
5283 u32 sub_stripes = 0;
5284 u64 stripes_per_dev = 0;
5285 u32 remaining_stripes = 0;
5286 u32 last_stripe = 0;
5290 /* discard always return a bbio */
5293 em = get_chunk_map(fs_info, logical, length);
5297 map = em->map_lookup;
5298 /* we don't discard raid56 yet */
5299 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5304 offset = logical - em->start;
5305 length = min_t(u64, em->len - offset, length);
5307 stripe_len = map->stripe_len;
5309 * stripe_nr counts the total number of stripes we have to stride
5310 * to get to this block
5312 stripe_nr = div64_u64(offset, stripe_len);
5314 /* stripe_offset is the offset of this block in its stripe */
5315 stripe_offset = offset - stripe_nr * stripe_len;
5317 stripe_nr_end = round_up(offset + length, map->stripe_len);
5318 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5319 stripe_cnt = stripe_nr_end - stripe_nr;
5320 stripe_end_offset = stripe_nr_end * map->stripe_len -
5323 * after this, stripe_nr is the number of stripes on this
5324 * device we have to walk to find the data, and stripe_index is
5325 * the number of our device in the stripe array
5329 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5330 BTRFS_BLOCK_GROUP_RAID10)) {
5331 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5334 sub_stripes = map->sub_stripes;
5336 factor = map->num_stripes / sub_stripes;
5337 num_stripes = min_t(u64, map->num_stripes,
5338 sub_stripes * stripe_cnt);
5339 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5340 stripe_index *= sub_stripes;
5341 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5342 &remaining_stripes);
5343 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5344 last_stripe *= sub_stripes;
5345 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5346 BTRFS_BLOCK_GROUP_DUP)) {
5347 num_stripes = map->num_stripes;
5349 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5353 bbio = alloc_btrfs_bio(num_stripes, 0);
5359 for (i = 0; i < num_stripes; i++) {
5360 bbio->stripes[i].physical =
5361 map->stripes[stripe_index].physical +
5362 stripe_offset + stripe_nr * map->stripe_len;
5363 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5365 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5366 BTRFS_BLOCK_GROUP_RAID10)) {
5367 bbio->stripes[i].length = stripes_per_dev *
5370 if (i / sub_stripes < remaining_stripes)
5371 bbio->stripes[i].length +=
5375 * Special for the first stripe and
5378 * |-------|...|-------|
5382 if (i < sub_stripes)
5383 bbio->stripes[i].length -=
5386 if (stripe_index >= last_stripe &&
5387 stripe_index <= (last_stripe +
5389 bbio->stripes[i].length -=
5392 if (i == sub_stripes - 1)
5395 bbio->stripes[i].length = length;
5399 if (stripe_index == map->num_stripes) {
5406 bbio->map_type = map->type;
5407 bbio->num_stripes = num_stripes;
5409 free_extent_map(em);
5414 * In dev-replace case, for repair case (that's the only case where the mirror
5415 * is selected explicitly when calling btrfs_map_block), blocks left of the
5416 * left cursor can also be read from the target drive.
5418 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5420 * For READ, it also needs to be supported using the same mirror number.
5422 * If the requested block is not left of the left cursor, EIO is returned. This
5423 * can happen because btrfs_num_copies() returns one more in the dev-replace
5426 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5427 u64 logical, u64 length,
5428 u64 srcdev_devid, int *mirror_num,
5431 struct btrfs_bio *bbio = NULL;
5433 int index_srcdev = 0;
5435 u64 physical_of_found = 0;
5439 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5440 logical, &length, &bbio, 0, 0);
5442 ASSERT(bbio == NULL);
5446 num_stripes = bbio->num_stripes;
5447 if (*mirror_num > num_stripes) {
5449 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5450 * that means that the requested area is not left of the left
5453 btrfs_put_bbio(bbio);
5458 * process the rest of the function using the mirror_num of the source
5459 * drive. Therefore look it up first. At the end, patch the device
5460 * pointer to the one of the target drive.
5462 for (i = 0; i < num_stripes; i++) {
5463 if (bbio->stripes[i].dev->devid != srcdev_devid)
5467 * In case of DUP, in order to keep it simple, only add the
5468 * mirror with the lowest physical address
5471 physical_of_found <= bbio->stripes[i].physical)
5476 physical_of_found = bbio->stripes[i].physical;
5479 btrfs_put_bbio(bbio);
5485 *mirror_num = index_srcdev + 1;
5486 *physical = physical_of_found;
5490 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5491 struct btrfs_bio **bbio_ret,
5492 struct btrfs_dev_replace *dev_replace,
5493 int *num_stripes_ret, int *max_errors_ret)
5495 struct btrfs_bio *bbio = *bbio_ret;
5496 u64 srcdev_devid = dev_replace->srcdev->devid;
5497 int tgtdev_indexes = 0;
5498 int num_stripes = *num_stripes_ret;
5499 int max_errors = *max_errors_ret;
5502 if (op == BTRFS_MAP_WRITE) {
5503 int index_where_to_add;
5506 * duplicate the write operations while the dev replace
5507 * procedure is running. Since the copying of the old disk to
5508 * the new disk takes place at run time while the filesystem is
5509 * mounted writable, the regular write operations to the old
5510 * disk have to be duplicated to go to the new disk as well.
5512 * Note that device->missing is handled by the caller, and that
5513 * the write to the old disk is already set up in the stripes
5516 index_where_to_add = num_stripes;
5517 for (i = 0; i < num_stripes; i++) {
5518 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5519 /* write to new disk, too */
5520 struct btrfs_bio_stripe *new =
5521 bbio->stripes + index_where_to_add;
5522 struct btrfs_bio_stripe *old =
5525 new->physical = old->physical;
5526 new->length = old->length;
5527 new->dev = dev_replace->tgtdev;
5528 bbio->tgtdev_map[i] = index_where_to_add;
5529 index_where_to_add++;
5534 num_stripes = index_where_to_add;
5535 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5536 int index_srcdev = 0;
5538 u64 physical_of_found = 0;
5541 * During the dev-replace procedure, the target drive can also
5542 * be used to read data in case it is needed to repair a corrupt
5543 * block elsewhere. This is possible if the requested area is
5544 * left of the left cursor. In this area, the target drive is a
5545 * full copy of the source drive.
5547 for (i = 0; i < num_stripes; i++) {
5548 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5550 * In case of DUP, in order to keep it simple,
5551 * only add the mirror with the lowest physical
5555 physical_of_found <=
5556 bbio->stripes[i].physical)
5560 physical_of_found = bbio->stripes[i].physical;
5564 struct btrfs_bio_stripe *tgtdev_stripe =
5565 bbio->stripes + num_stripes;
5567 tgtdev_stripe->physical = physical_of_found;
5568 tgtdev_stripe->length =
5569 bbio->stripes[index_srcdev].length;
5570 tgtdev_stripe->dev = dev_replace->tgtdev;
5571 bbio->tgtdev_map[index_srcdev] = num_stripes;
5578 *num_stripes_ret = num_stripes;
5579 *max_errors_ret = max_errors;
5580 bbio->num_tgtdevs = tgtdev_indexes;
5584 static bool need_full_stripe(enum btrfs_map_op op)
5586 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5589 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5590 enum btrfs_map_op op,
5591 u64 logical, u64 *length,
5592 struct btrfs_bio **bbio_ret,
5593 int mirror_num, int need_raid_map)
5595 struct extent_map *em;
5596 struct map_lookup *map;
5606 int tgtdev_indexes = 0;
5607 struct btrfs_bio *bbio = NULL;
5608 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5609 int dev_replace_is_ongoing = 0;
5610 int num_alloc_stripes;
5611 int patch_the_first_stripe_for_dev_replace = 0;
5612 u64 physical_to_patch_in_first_stripe = 0;
5613 u64 raid56_full_stripe_start = (u64)-1;
5615 if (op == BTRFS_MAP_DISCARD)
5616 return __btrfs_map_block_for_discard(fs_info, logical,
5619 em = get_chunk_map(fs_info, logical, *length);
5623 map = em->map_lookup;
5624 offset = logical - em->start;
5626 stripe_len = map->stripe_len;
5629 * stripe_nr counts the total number of stripes we have to stride
5630 * to get to this block
5632 stripe_nr = div64_u64(stripe_nr, stripe_len);
5634 stripe_offset = stripe_nr * stripe_len;
5635 if (offset < stripe_offset) {
5637 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5638 stripe_offset, offset, em->start, logical,
5640 free_extent_map(em);
5644 /* stripe_offset is the offset of this block in its stripe*/
5645 stripe_offset = offset - stripe_offset;
5647 /* if we're here for raid56, we need to know the stripe aligned start */
5648 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5649 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5650 raid56_full_stripe_start = offset;
5652 /* allow a write of a full stripe, but make sure we don't
5653 * allow straddling of stripes
5655 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5657 raid56_full_stripe_start *= full_stripe_len;
5660 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5662 /* For writes to RAID[56], allow a full stripeset across all disks.
5663 For other RAID types and for RAID[56] reads, just allow a single
5664 stripe (on a single disk). */
5665 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5666 (op == BTRFS_MAP_WRITE)) {
5667 max_len = stripe_len * nr_data_stripes(map) -
5668 (offset - raid56_full_stripe_start);
5670 /* we limit the length of each bio to what fits in a stripe */
5671 max_len = stripe_len - stripe_offset;
5673 *length = min_t(u64, em->len - offset, max_len);
5675 *length = em->len - offset;
5678 /* This is for when we're called from btrfs_merge_bio_hook() and all
5679 it cares about is the length */
5683 btrfs_dev_replace_read_lock(dev_replace);
5684 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5685 if (!dev_replace_is_ongoing)
5686 btrfs_dev_replace_read_unlock(dev_replace);
5688 btrfs_dev_replace_set_lock_blocking(dev_replace);
5690 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5691 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5692 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5693 dev_replace->srcdev->devid,
5695 &physical_to_patch_in_first_stripe);
5699 patch_the_first_stripe_for_dev_replace = 1;
5700 } else if (mirror_num > map->num_stripes) {
5706 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5707 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5709 if (!need_full_stripe(op))
5711 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5712 if (need_full_stripe(op))
5713 num_stripes = map->num_stripes;
5714 else if (mirror_num)
5715 stripe_index = mirror_num - 1;
5717 stripe_index = find_live_mirror(fs_info, map, 0,
5718 dev_replace_is_ongoing);
5719 mirror_num = stripe_index + 1;
5722 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5723 if (need_full_stripe(op)) {
5724 num_stripes = map->num_stripes;
5725 } else if (mirror_num) {
5726 stripe_index = mirror_num - 1;
5731 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5732 u32 factor = map->num_stripes / map->sub_stripes;
5734 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5735 stripe_index *= map->sub_stripes;
5737 if (need_full_stripe(op))
5738 num_stripes = map->sub_stripes;
5739 else if (mirror_num)
5740 stripe_index += mirror_num - 1;
5742 int old_stripe_index = stripe_index;
5743 stripe_index = find_live_mirror(fs_info, map,
5745 dev_replace_is_ongoing);
5746 mirror_num = stripe_index - old_stripe_index + 1;
5749 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5750 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5751 /* push stripe_nr back to the start of the full stripe */
5752 stripe_nr = div64_u64(raid56_full_stripe_start,
5753 stripe_len * nr_data_stripes(map));
5755 /* RAID[56] write or recovery. Return all stripes */
5756 num_stripes = map->num_stripes;
5757 max_errors = nr_parity_stripes(map);
5759 *length = map->stripe_len;
5764 * Mirror #0 or #1 means the original data block.
5765 * Mirror #2 is RAID5 parity block.
5766 * Mirror #3 is RAID6 Q block.
5768 stripe_nr = div_u64_rem(stripe_nr,
5769 nr_data_stripes(map), &stripe_index);
5771 stripe_index = nr_data_stripes(map) +
5774 /* We distribute the parity blocks across stripes */
5775 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5777 if (!need_full_stripe(op) && mirror_num <= 1)
5782 * after this, stripe_nr is the number of stripes on this
5783 * device we have to walk to find the data, and stripe_index is
5784 * the number of our device in the stripe array
5786 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5788 mirror_num = stripe_index + 1;
5790 if (stripe_index >= map->num_stripes) {
5792 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5793 stripe_index, map->num_stripes);
5798 num_alloc_stripes = num_stripes;
5799 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5800 if (op == BTRFS_MAP_WRITE)
5801 num_alloc_stripes <<= 1;
5802 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5803 num_alloc_stripes++;
5804 tgtdev_indexes = num_stripes;
5807 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5812 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5813 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5815 /* build raid_map */
5816 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5817 (need_full_stripe(op) || mirror_num > 1)) {
5821 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5822 sizeof(struct btrfs_bio_stripe) *
5824 sizeof(int) * tgtdev_indexes);
5826 /* Work out the disk rotation on this stripe-set */
5827 div_u64_rem(stripe_nr, num_stripes, &rot);
5829 /* Fill in the logical address of each stripe */
5830 tmp = stripe_nr * nr_data_stripes(map);
5831 for (i = 0; i < nr_data_stripes(map); i++)
5832 bbio->raid_map[(i+rot) % num_stripes] =
5833 em->start + (tmp + i) * map->stripe_len;
5835 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5836 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5837 bbio->raid_map[(i+rot+1) % num_stripes] =
5842 for (i = 0; i < num_stripes; i++) {
5843 bbio->stripes[i].physical =
5844 map->stripes[stripe_index].physical +
5846 stripe_nr * map->stripe_len;
5847 bbio->stripes[i].dev =
5848 map->stripes[stripe_index].dev;
5852 if (need_full_stripe(op))
5853 max_errors = btrfs_chunk_max_errors(map);
5856 sort_parity_stripes(bbio, num_stripes);
5858 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5859 need_full_stripe(op)) {
5860 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5865 bbio->map_type = map->type;
5866 bbio->num_stripes = num_stripes;
5867 bbio->max_errors = max_errors;
5868 bbio->mirror_num = mirror_num;
5871 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5872 * mirror_num == num_stripes + 1 && dev_replace target drive is
5873 * available as a mirror
5875 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5876 WARN_ON(num_stripes > 1);
5877 bbio->stripes[0].dev = dev_replace->tgtdev;
5878 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5879 bbio->mirror_num = map->num_stripes + 1;
5882 if (dev_replace_is_ongoing) {
5883 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5884 btrfs_dev_replace_read_unlock(dev_replace);
5886 free_extent_map(em);
5890 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5891 u64 logical, u64 *length,
5892 struct btrfs_bio **bbio_ret, int mirror_num)
5894 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
5898 /* For Scrub/replace */
5899 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5900 u64 logical, u64 *length,
5901 struct btrfs_bio **bbio_ret)
5903 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
5906 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
5907 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
5909 struct extent_map *em;
5910 struct map_lookup *map;
5918 em = get_chunk_map(fs_info, chunk_start, 1);
5922 map = em->map_lookup;
5924 rmap_len = map->stripe_len;
5926 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5927 length = div_u64(length, map->num_stripes / map->sub_stripes);
5928 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5929 length = div_u64(length, map->num_stripes);
5930 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5931 length = div_u64(length, nr_data_stripes(map));
5932 rmap_len = map->stripe_len * nr_data_stripes(map);
5935 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5936 BUG_ON(!buf); /* -ENOMEM */
5938 for (i = 0; i < map->num_stripes; i++) {
5939 if (map->stripes[i].physical > physical ||
5940 map->stripes[i].physical + length <= physical)
5943 stripe_nr = physical - map->stripes[i].physical;
5944 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
5946 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5947 stripe_nr = stripe_nr * map->num_stripes + i;
5948 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
5949 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5950 stripe_nr = stripe_nr * map->num_stripes + i;
5951 } /* else if RAID[56], multiply by nr_data_stripes().
5952 * Alternatively, just use rmap_len below instead of
5953 * map->stripe_len */
5955 bytenr = chunk_start + stripe_nr * rmap_len;
5956 WARN_ON(nr >= map->num_stripes);
5957 for (j = 0; j < nr; j++) {
5958 if (buf[j] == bytenr)
5962 WARN_ON(nr >= map->num_stripes);
5969 *stripe_len = rmap_len;
5971 free_extent_map(em);
5975 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
5977 bio->bi_private = bbio->private;
5978 bio->bi_end_io = bbio->end_io;
5981 btrfs_put_bbio(bbio);
5984 static void btrfs_end_bio(struct bio *bio)
5986 struct btrfs_bio *bbio = bio->bi_private;
5987 int is_orig_bio = 0;
5989 if (bio->bi_status) {
5990 atomic_inc(&bbio->error);
5991 if (bio->bi_status == BLK_STS_IOERR ||
5992 bio->bi_status == BLK_STS_TARGET) {
5993 unsigned int stripe_index =
5994 btrfs_io_bio(bio)->stripe_index;
5995 struct btrfs_device *dev;
5997 BUG_ON(stripe_index >= bbio->num_stripes);
5998 dev = bbio->stripes[stripe_index].dev;
6000 if (bio_op(bio) == REQ_OP_WRITE)
6001 btrfs_dev_stat_inc_and_print(dev,
6002 BTRFS_DEV_STAT_WRITE_ERRS);
6004 btrfs_dev_stat_inc_and_print(dev,
6005 BTRFS_DEV_STAT_READ_ERRS);
6006 if (bio->bi_opf & REQ_PREFLUSH)
6007 btrfs_dev_stat_inc_and_print(dev,
6008 BTRFS_DEV_STAT_FLUSH_ERRS);
6013 if (bio == bbio->orig_bio)
6016 btrfs_bio_counter_dec(bbio->fs_info);
6018 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6021 bio = bbio->orig_bio;
6024 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6025 /* only send an error to the higher layers if it is
6026 * beyond the tolerance of the btrfs bio
6028 if (atomic_read(&bbio->error) > bbio->max_errors) {
6029 bio->bi_status = BLK_STS_IOERR;
6032 * this bio is actually up to date, we didn't
6033 * go over the max number of errors
6035 bio->bi_status = BLK_STS_OK;
6038 btrfs_end_bbio(bbio, bio);
6039 } else if (!is_orig_bio) {
6045 * see run_scheduled_bios for a description of why bios are collected for
6048 * This will add one bio to the pending list for a device and make sure
6049 * the work struct is scheduled.
6051 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6054 struct btrfs_fs_info *fs_info = device->fs_info;
6055 int should_queue = 1;
6056 struct btrfs_pending_bios *pending_bios;
6058 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state) ||
6064 /* don't bother with additional async steps for reads, right now */
6065 if (bio_op(bio) == REQ_OP_READ) {
6066 btrfsic_submit_bio(bio);
6070 WARN_ON(bio->bi_next);
6071 bio->bi_next = NULL;
6073 spin_lock(&device->io_lock);
6074 if (op_is_sync(bio->bi_opf))
6075 pending_bios = &device->pending_sync_bios;
6077 pending_bios = &device->pending_bios;
6079 if (pending_bios->tail)
6080 pending_bios->tail->bi_next = bio;
6082 pending_bios->tail = bio;
6083 if (!pending_bios->head)
6084 pending_bios->head = bio;
6085 if (device->running_pending)
6088 spin_unlock(&device->io_lock);
6091 btrfs_queue_work(fs_info->submit_workers, &device->work);
6094 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6095 u64 physical, int dev_nr, int async)
6097 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6098 struct btrfs_fs_info *fs_info = bbio->fs_info;
6100 bio->bi_private = bbio;
6101 btrfs_io_bio(bio)->stripe_index = dev_nr;
6102 bio->bi_end_io = btrfs_end_bio;
6103 bio->bi_iter.bi_sector = physical >> 9;
6106 struct rcu_string *name;
6109 name = rcu_dereference(dev->name);
6110 btrfs_debug(fs_info,
6111 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6112 bio_op(bio), bio->bi_opf,
6113 (u64)bio->bi_iter.bi_sector,
6114 (u_long)dev->bdev->bd_dev, name->str, dev->devid,
6115 bio->bi_iter.bi_size);
6119 bio_set_dev(bio, dev->bdev);
6121 btrfs_bio_counter_inc_noblocked(fs_info);
6124 btrfs_schedule_bio(dev, bio);
6126 btrfsic_submit_bio(bio);
6129 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6131 atomic_inc(&bbio->error);
6132 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6133 /* Should be the original bio. */
6134 WARN_ON(bio != bbio->orig_bio);
6136 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6137 bio->bi_iter.bi_sector = logical >> 9;
6138 if (atomic_read(&bbio->error) > bbio->max_errors)
6139 bio->bi_status = BLK_STS_IOERR;
6141 bio->bi_status = BLK_STS_OK;
6142 btrfs_end_bbio(bbio, bio);
6146 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6147 int mirror_num, int async_submit)
6149 struct btrfs_device *dev;
6150 struct bio *first_bio = bio;
6151 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6157 struct btrfs_bio *bbio = NULL;
6159 length = bio->bi_iter.bi_size;
6160 map_length = length;
6162 btrfs_bio_counter_inc_blocked(fs_info);
6163 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6164 &map_length, &bbio, mirror_num, 1);
6166 btrfs_bio_counter_dec(fs_info);
6167 return errno_to_blk_status(ret);
6170 total_devs = bbio->num_stripes;
6171 bbio->orig_bio = first_bio;
6172 bbio->private = first_bio->bi_private;
6173 bbio->end_io = first_bio->bi_end_io;
6174 bbio->fs_info = fs_info;
6175 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6177 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6178 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6179 /* In this case, map_length has been set to the length of
6180 a single stripe; not the whole write */
6181 if (bio_op(bio) == REQ_OP_WRITE) {
6182 ret = raid56_parity_write(fs_info, bio, bbio,
6185 ret = raid56_parity_recover(fs_info, bio, bbio,
6186 map_length, mirror_num, 1);
6189 btrfs_bio_counter_dec(fs_info);
6190 return errno_to_blk_status(ret);
6193 if (map_length < length) {
6195 "mapping failed logical %llu bio len %llu len %llu",
6196 logical, length, map_length);
6200 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6201 dev = bbio->stripes[dev_nr].dev;
6202 if (!dev || !dev->bdev ||
6203 (bio_op(first_bio) == REQ_OP_WRITE &&
6204 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6205 bbio_error(bbio, first_bio, logical);
6209 if (dev_nr < total_devs - 1)
6210 bio = btrfs_bio_clone(first_bio);
6214 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6215 dev_nr, async_submit);
6217 btrfs_bio_counter_dec(fs_info);
6221 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6224 struct btrfs_device *device;
6225 struct btrfs_fs_devices *cur_devices;
6227 cur_devices = fs_info->fs_devices;
6228 while (cur_devices) {
6230 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6231 device = find_device(cur_devices, devid, uuid);
6235 cur_devices = cur_devices->seed;
6240 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6241 u64 devid, u8 *dev_uuid)
6243 struct btrfs_device *device;
6245 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6249 list_add(&device->dev_list, &fs_devices->devices);
6250 device->fs_devices = fs_devices;
6251 fs_devices->num_devices++;
6253 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6254 fs_devices->missing_devices++;
6260 * btrfs_alloc_device - allocate struct btrfs_device
6261 * @fs_info: used only for generating a new devid, can be NULL if
6262 * devid is provided (i.e. @devid != NULL).
6263 * @devid: a pointer to devid for this device. If NULL a new devid
6265 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6268 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6269 * on error. Returned struct is not linked onto any lists and must be
6270 * destroyed with btrfs_free_device.
6272 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6276 struct btrfs_device *dev;
6279 if (WARN_ON(!devid && !fs_info))
6280 return ERR_PTR(-EINVAL);
6282 dev = __alloc_device();
6291 ret = find_next_devid(fs_info, &tmp);
6293 btrfs_free_device(dev);
6294 return ERR_PTR(ret);
6300 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6302 generate_random_uuid(dev->uuid);
6304 btrfs_init_work(&dev->work, btrfs_submit_helper,
6305 pending_bios_fn, NULL, NULL);
6310 /* Return -EIO if any error, otherwise return 0. */
6311 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6312 struct extent_buffer *leaf,
6313 struct btrfs_chunk *chunk, u64 logical)
6321 length = btrfs_chunk_length(leaf, chunk);
6322 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6323 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6324 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6325 type = btrfs_chunk_type(leaf, chunk);
6328 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6332 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6333 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6336 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6337 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6338 btrfs_chunk_sector_size(leaf, chunk));
6341 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6342 btrfs_err(fs_info, "invalid chunk length %llu", length);
6345 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6346 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6350 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6352 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6353 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6354 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6355 btrfs_chunk_type(leaf, chunk));
6358 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6359 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6360 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6361 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6362 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6363 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6364 num_stripes != 1)) {
6366 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6367 num_stripes, sub_stripes,
6368 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6375 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6376 u64 devid, u8 *uuid, bool error)
6379 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6382 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6386 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6387 struct extent_buffer *leaf,
6388 struct btrfs_chunk *chunk)
6390 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6391 struct map_lookup *map;
6392 struct extent_map *em;
6396 u8 uuid[BTRFS_UUID_SIZE];
6401 logical = key->offset;
6402 length = btrfs_chunk_length(leaf, chunk);
6403 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6405 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6409 read_lock(&map_tree->map_tree.lock);
6410 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6411 read_unlock(&map_tree->map_tree.lock);
6413 /* already mapped? */
6414 if (em && em->start <= logical && em->start + em->len > logical) {
6415 free_extent_map(em);
6418 free_extent_map(em);
6421 em = alloc_extent_map();
6424 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6426 free_extent_map(em);
6430 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6431 em->map_lookup = map;
6432 em->start = logical;
6435 em->block_start = 0;
6436 em->block_len = em->len;
6438 map->num_stripes = num_stripes;
6439 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6440 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6441 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6442 map->type = btrfs_chunk_type(leaf, chunk);
6443 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6444 for (i = 0; i < num_stripes; i++) {
6445 map->stripes[i].physical =
6446 btrfs_stripe_offset_nr(leaf, chunk, i);
6447 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6448 read_extent_buffer(leaf, uuid, (unsigned long)
6449 btrfs_stripe_dev_uuid_nr(chunk, i),
6451 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6453 if (!map->stripes[i].dev &&
6454 !btrfs_test_opt(fs_info, DEGRADED)) {
6455 free_extent_map(em);
6456 btrfs_report_missing_device(fs_info, devid, uuid, true);
6459 if (!map->stripes[i].dev) {
6460 map->stripes[i].dev =
6461 add_missing_dev(fs_info->fs_devices, devid,
6463 if (IS_ERR(map->stripes[i].dev)) {
6464 free_extent_map(em);
6466 "failed to init missing dev %llu: %ld",
6467 devid, PTR_ERR(map->stripes[i].dev));
6468 return PTR_ERR(map->stripes[i].dev);
6470 btrfs_report_missing_device(fs_info, devid, uuid, false);
6472 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6473 &(map->stripes[i].dev->dev_state));
6477 write_lock(&map_tree->map_tree.lock);
6478 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6479 write_unlock(&map_tree->map_tree.lock);
6480 BUG_ON(ret); /* Tree corruption */
6481 free_extent_map(em);
6486 static void fill_device_from_item(struct extent_buffer *leaf,
6487 struct btrfs_dev_item *dev_item,
6488 struct btrfs_device *device)
6492 device->devid = btrfs_device_id(leaf, dev_item);
6493 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6494 device->total_bytes = device->disk_total_bytes;
6495 device->commit_total_bytes = device->disk_total_bytes;
6496 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6497 device->commit_bytes_used = device->bytes_used;
6498 device->type = btrfs_device_type(leaf, dev_item);
6499 device->io_align = btrfs_device_io_align(leaf, dev_item);
6500 device->io_width = btrfs_device_io_width(leaf, dev_item);
6501 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6502 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6503 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6505 ptr = btrfs_device_uuid(dev_item);
6506 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6509 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6512 struct btrfs_fs_devices *fs_devices;
6515 lockdep_assert_held(&uuid_mutex);
6518 fs_devices = fs_info->fs_devices->seed;
6519 while (fs_devices) {
6520 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6523 fs_devices = fs_devices->seed;
6526 fs_devices = find_fsid(fsid);
6528 if (!btrfs_test_opt(fs_info, DEGRADED))
6529 return ERR_PTR(-ENOENT);
6531 fs_devices = alloc_fs_devices(fsid);
6532 if (IS_ERR(fs_devices))
6535 fs_devices->seeding = 1;
6536 fs_devices->opened = 1;
6540 fs_devices = clone_fs_devices(fs_devices);
6541 if (IS_ERR(fs_devices))
6544 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6546 free_fs_devices(fs_devices);
6547 fs_devices = ERR_PTR(ret);
6551 if (!fs_devices->seeding) {
6552 close_fs_devices(fs_devices);
6553 free_fs_devices(fs_devices);
6554 fs_devices = ERR_PTR(-EINVAL);
6558 fs_devices->seed = fs_info->fs_devices->seed;
6559 fs_info->fs_devices->seed = fs_devices;
6564 static int read_one_dev(struct btrfs_fs_info *fs_info,
6565 struct extent_buffer *leaf,
6566 struct btrfs_dev_item *dev_item)
6568 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6569 struct btrfs_device *device;
6572 u8 fs_uuid[BTRFS_FSID_SIZE];
6573 u8 dev_uuid[BTRFS_UUID_SIZE];
6575 devid = btrfs_device_id(leaf, dev_item);
6576 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6578 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6581 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6582 fs_devices = open_seed_devices(fs_info, fs_uuid);
6583 if (IS_ERR(fs_devices))
6584 return PTR_ERR(fs_devices);
6587 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6589 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6590 btrfs_report_missing_device(fs_info, devid,
6595 device = add_missing_dev(fs_devices, devid, dev_uuid);
6596 if (IS_ERR(device)) {
6598 "failed to add missing dev %llu: %ld",
6599 devid, PTR_ERR(device));
6600 return PTR_ERR(device);
6602 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6604 if (!device->bdev) {
6605 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6606 btrfs_report_missing_device(fs_info,
6607 devid, dev_uuid, true);
6610 btrfs_report_missing_device(fs_info, devid,
6614 if (!device->bdev &&
6615 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6617 * this happens when a device that was properly setup
6618 * in the device info lists suddenly goes bad.
6619 * device->bdev is NULL, and so we have to set
6620 * device->missing to one here
6622 device->fs_devices->missing_devices++;
6623 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6626 /* Move the device to its own fs_devices */
6627 if (device->fs_devices != fs_devices) {
6628 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6629 &device->dev_state));
6631 list_move(&device->dev_list, &fs_devices->devices);
6632 device->fs_devices->num_devices--;
6633 fs_devices->num_devices++;
6635 device->fs_devices->missing_devices--;
6636 fs_devices->missing_devices++;
6638 device->fs_devices = fs_devices;
6642 if (device->fs_devices != fs_info->fs_devices) {
6643 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6644 if (device->generation !=
6645 btrfs_device_generation(leaf, dev_item))
6649 fill_device_from_item(leaf, dev_item, device);
6650 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6651 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6652 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6653 device->fs_devices->total_rw_bytes += device->total_bytes;
6654 atomic64_add(device->total_bytes - device->bytes_used,
6655 &fs_info->free_chunk_space);
6661 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6663 struct btrfs_root *root = fs_info->tree_root;
6664 struct btrfs_super_block *super_copy = fs_info->super_copy;
6665 struct extent_buffer *sb;
6666 struct btrfs_disk_key *disk_key;
6667 struct btrfs_chunk *chunk;
6669 unsigned long sb_array_offset;
6676 struct btrfs_key key;
6678 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6680 * This will create extent buffer of nodesize, superblock size is
6681 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6682 * overallocate but we can keep it as-is, only the first page is used.
6684 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6687 set_extent_buffer_uptodate(sb);
6688 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6690 * The sb extent buffer is artificial and just used to read the system array.
6691 * set_extent_buffer_uptodate() call does not properly mark all it's
6692 * pages up-to-date when the page is larger: extent does not cover the
6693 * whole page and consequently check_page_uptodate does not find all
6694 * the page's extents up-to-date (the hole beyond sb),
6695 * write_extent_buffer then triggers a WARN_ON.
6697 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6698 * but sb spans only this function. Add an explicit SetPageUptodate call
6699 * to silence the warning eg. on PowerPC 64.
6701 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6702 SetPageUptodate(sb->pages[0]);
6704 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6705 array_size = btrfs_super_sys_array_size(super_copy);
6707 array_ptr = super_copy->sys_chunk_array;
6708 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6711 while (cur_offset < array_size) {
6712 disk_key = (struct btrfs_disk_key *)array_ptr;
6713 len = sizeof(*disk_key);
6714 if (cur_offset + len > array_size)
6715 goto out_short_read;
6717 btrfs_disk_key_to_cpu(&key, disk_key);
6720 sb_array_offset += len;
6723 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6724 chunk = (struct btrfs_chunk *)sb_array_offset;
6726 * At least one btrfs_chunk with one stripe must be
6727 * present, exact stripe count check comes afterwards
6729 len = btrfs_chunk_item_size(1);
6730 if (cur_offset + len > array_size)
6731 goto out_short_read;
6733 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6736 "invalid number of stripes %u in sys_array at offset %u",
6737 num_stripes, cur_offset);
6742 type = btrfs_chunk_type(sb, chunk);
6743 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6745 "invalid chunk type %llu in sys_array at offset %u",
6751 len = btrfs_chunk_item_size(num_stripes);
6752 if (cur_offset + len > array_size)
6753 goto out_short_read;
6755 ret = read_one_chunk(fs_info, &key, sb, chunk);
6760 "unexpected item type %u in sys_array at offset %u",
6761 (u32)key.type, cur_offset);
6766 sb_array_offset += len;
6769 clear_extent_buffer_uptodate(sb);
6770 free_extent_buffer_stale(sb);
6774 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6776 clear_extent_buffer_uptodate(sb);
6777 free_extent_buffer_stale(sb);
6782 * Check if all chunks in the fs are OK for read-write degraded mount
6784 * If the @failing_dev is specified, it's accounted as missing.
6786 * Return true if all chunks meet the minimal RW mount requirements.
6787 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6789 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6790 struct btrfs_device *failing_dev)
6792 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6793 struct extent_map *em;
6797 read_lock(&map_tree->map_tree.lock);
6798 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6799 read_unlock(&map_tree->map_tree.lock);
6800 /* No chunk at all? Return false anyway */
6806 struct map_lookup *map;
6811 map = em->map_lookup;
6813 btrfs_get_num_tolerated_disk_barrier_failures(
6815 for (i = 0; i < map->num_stripes; i++) {
6816 struct btrfs_device *dev = map->stripes[i].dev;
6818 if (!dev || !dev->bdev ||
6819 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6820 dev->last_flush_error)
6822 else if (failing_dev && failing_dev == dev)
6825 if (missing > max_tolerated) {
6828 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6829 em->start, missing, max_tolerated);
6830 free_extent_map(em);
6834 next_start = extent_map_end(em);
6835 free_extent_map(em);
6837 read_lock(&map_tree->map_tree.lock);
6838 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6839 (u64)(-1) - next_start);
6840 read_unlock(&map_tree->map_tree.lock);
6846 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6848 struct btrfs_root *root = fs_info->chunk_root;
6849 struct btrfs_path *path;
6850 struct extent_buffer *leaf;
6851 struct btrfs_key key;
6852 struct btrfs_key found_key;
6857 path = btrfs_alloc_path();
6862 * uuid_mutex is needed only if we are mounting a sprout FS
6863 * otherwise we don't need it.
6865 mutex_lock(&uuid_mutex);
6866 mutex_lock(&fs_info->chunk_mutex);
6869 * Read all device items, and then all the chunk items. All
6870 * device items are found before any chunk item (their object id
6871 * is smaller than the lowest possible object id for a chunk
6872 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6874 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6877 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6881 leaf = path->nodes[0];
6882 slot = path->slots[0];
6883 if (slot >= btrfs_header_nritems(leaf)) {
6884 ret = btrfs_next_leaf(root, path);
6891 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6892 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6893 struct btrfs_dev_item *dev_item;
6894 dev_item = btrfs_item_ptr(leaf, slot,
6895 struct btrfs_dev_item);
6896 ret = read_one_dev(fs_info, leaf, dev_item);
6900 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6901 struct btrfs_chunk *chunk;
6902 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6903 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
6911 * After loading chunk tree, we've got all device information,
6912 * do another round of validation checks.
6914 if (total_dev != fs_info->fs_devices->total_devices) {
6916 "super_num_devices %llu mismatch with num_devices %llu found here",
6917 btrfs_super_num_devices(fs_info->super_copy),
6922 if (btrfs_super_total_bytes(fs_info->super_copy) <
6923 fs_info->fs_devices->total_rw_bytes) {
6925 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
6926 btrfs_super_total_bytes(fs_info->super_copy),
6927 fs_info->fs_devices->total_rw_bytes);
6933 mutex_unlock(&fs_info->chunk_mutex);
6934 mutex_unlock(&uuid_mutex);
6936 btrfs_free_path(path);
6940 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6942 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6943 struct btrfs_device *device;
6945 while (fs_devices) {
6946 mutex_lock(&fs_devices->device_list_mutex);
6947 list_for_each_entry(device, &fs_devices->devices, dev_list)
6948 device->fs_info = fs_info;
6949 mutex_unlock(&fs_devices->device_list_mutex);
6951 fs_devices = fs_devices->seed;
6955 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6959 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6960 btrfs_dev_stat_reset(dev, i);
6963 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6965 struct btrfs_key key;
6966 struct btrfs_key found_key;
6967 struct btrfs_root *dev_root = fs_info->dev_root;
6968 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6969 struct extent_buffer *eb;
6972 struct btrfs_device *device;
6973 struct btrfs_path *path = NULL;
6976 path = btrfs_alloc_path();
6982 mutex_lock(&fs_devices->device_list_mutex);
6983 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6985 struct btrfs_dev_stats_item *ptr;
6987 key.objectid = BTRFS_DEV_STATS_OBJECTID;
6988 key.type = BTRFS_PERSISTENT_ITEM_KEY;
6989 key.offset = device->devid;
6990 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6992 __btrfs_reset_dev_stats(device);
6993 device->dev_stats_valid = 1;
6994 btrfs_release_path(path);
6997 slot = path->slots[0];
6998 eb = path->nodes[0];
6999 btrfs_item_key_to_cpu(eb, &found_key, slot);
7000 item_size = btrfs_item_size_nr(eb, slot);
7002 ptr = btrfs_item_ptr(eb, slot,
7003 struct btrfs_dev_stats_item);
7005 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7006 if (item_size >= (1 + i) * sizeof(__le64))
7007 btrfs_dev_stat_set(device, i,
7008 btrfs_dev_stats_value(eb, ptr, i));
7010 btrfs_dev_stat_reset(device, i);
7013 device->dev_stats_valid = 1;
7014 btrfs_dev_stat_print_on_load(device);
7015 btrfs_release_path(path);
7017 mutex_unlock(&fs_devices->device_list_mutex);
7020 btrfs_free_path(path);
7021 return ret < 0 ? ret : 0;
7024 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7025 struct btrfs_fs_info *fs_info,
7026 struct btrfs_device *device)
7028 struct btrfs_root *dev_root = fs_info->dev_root;
7029 struct btrfs_path *path;
7030 struct btrfs_key key;
7031 struct extent_buffer *eb;
7032 struct btrfs_dev_stats_item *ptr;
7036 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7037 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7038 key.offset = device->devid;
7040 path = btrfs_alloc_path();
7043 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7045 btrfs_warn_in_rcu(fs_info,
7046 "error %d while searching for dev_stats item for device %s",
7047 ret, rcu_str_deref(device->name));
7052 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7053 /* need to delete old one and insert a new one */
7054 ret = btrfs_del_item(trans, dev_root, path);
7056 btrfs_warn_in_rcu(fs_info,
7057 "delete too small dev_stats item for device %s failed %d",
7058 rcu_str_deref(device->name), ret);
7065 /* need to insert a new item */
7066 btrfs_release_path(path);
7067 ret = btrfs_insert_empty_item(trans, dev_root, path,
7068 &key, sizeof(*ptr));
7070 btrfs_warn_in_rcu(fs_info,
7071 "insert dev_stats item for device %s failed %d",
7072 rcu_str_deref(device->name), ret);
7077 eb = path->nodes[0];
7078 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7079 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7080 btrfs_set_dev_stats_value(eb, ptr, i,
7081 btrfs_dev_stat_read(device, i));
7082 btrfs_mark_buffer_dirty(eb);
7085 btrfs_free_path(path);
7090 * called from commit_transaction. Writes all changed device stats to disk.
7092 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7093 struct btrfs_fs_info *fs_info)
7095 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7096 struct btrfs_device *device;
7100 mutex_lock(&fs_devices->device_list_mutex);
7101 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7102 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7103 if (!device->dev_stats_valid || stats_cnt == 0)
7108 * There is a LOAD-LOAD control dependency between the value of
7109 * dev_stats_ccnt and updating the on-disk values which requires
7110 * reading the in-memory counters. Such control dependencies
7111 * require explicit read memory barriers.
7113 * This memory barriers pairs with smp_mb__before_atomic in
7114 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7115 * barrier implied by atomic_xchg in
7116 * btrfs_dev_stats_read_and_reset
7120 ret = update_dev_stat_item(trans, fs_info, device);
7122 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7124 mutex_unlock(&fs_devices->device_list_mutex);
7129 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7131 btrfs_dev_stat_inc(dev, index);
7132 btrfs_dev_stat_print_on_error(dev);
7135 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7137 if (!dev->dev_stats_valid)
7139 btrfs_err_rl_in_rcu(dev->fs_info,
7140 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7141 rcu_str_deref(dev->name),
7142 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7143 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7144 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7145 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7146 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7149 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7153 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7154 if (btrfs_dev_stat_read(dev, i) != 0)
7156 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7157 return; /* all values == 0, suppress message */
7159 btrfs_info_in_rcu(dev->fs_info,
7160 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7161 rcu_str_deref(dev->name),
7162 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7163 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7164 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7165 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7166 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7169 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7170 struct btrfs_ioctl_get_dev_stats *stats)
7172 struct btrfs_device *dev;
7173 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7176 mutex_lock(&fs_devices->device_list_mutex);
7177 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7178 mutex_unlock(&fs_devices->device_list_mutex);
7181 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7183 } else if (!dev->dev_stats_valid) {
7184 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7186 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7187 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7188 if (stats->nr_items > i)
7190 btrfs_dev_stat_read_and_reset(dev, i);
7192 btrfs_dev_stat_reset(dev, i);
7195 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7196 if (stats->nr_items > i)
7197 stats->values[i] = btrfs_dev_stat_read(dev, i);
7199 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7200 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7204 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7206 struct buffer_head *bh;
7207 struct btrfs_super_block *disk_super;
7213 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7216 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7219 disk_super = (struct btrfs_super_block *)bh->b_data;
7221 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7222 set_buffer_dirty(bh);
7223 sync_dirty_buffer(bh);
7227 /* Notify udev that device has changed */
7228 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7230 /* Update ctime/mtime for device path for libblkid */
7231 update_dev_time(device_path);
7235 * Update the size of all devices, which is used for writing out the
7238 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7240 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7241 struct btrfs_device *curr, *next;
7243 if (list_empty(&fs_devices->resized_devices))
7246 mutex_lock(&fs_devices->device_list_mutex);
7247 mutex_lock(&fs_info->chunk_mutex);
7248 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7250 list_del_init(&curr->resized_list);
7251 curr->commit_total_bytes = curr->disk_total_bytes;
7253 mutex_unlock(&fs_info->chunk_mutex);
7254 mutex_unlock(&fs_devices->device_list_mutex);
7257 /* Must be invoked during the transaction commit */
7258 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7260 struct btrfs_fs_info *fs_info = trans->fs_info;
7261 struct extent_map *em;
7262 struct map_lookup *map;
7263 struct btrfs_device *dev;
7266 if (list_empty(&trans->pending_chunks))
7269 /* In order to kick the device replace finish process */
7270 mutex_lock(&fs_info->chunk_mutex);
7271 list_for_each_entry(em, &trans->pending_chunks, list) {
7272 map = em->map_lookup;
7274 for (i = 0; i < map->num_stripes; i++) {
7275 dev = map->stripes[i].dev;
7276 dev->commit_bytes_used = dev->bytes_used;
7279 mutex_unlock(&fs_info->chunk_mutex);
7282 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7284 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7285 while (fs_devices) {
7286 fs_devices->fs_info = fs_info;
7287 fs_devices = fs_devices->seed;
7291 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7293 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7294 while (fs_devices) {
7295 fs_devices->fs_info = NULL;
7296 fs_devices = fs_devices->seed;