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_dev)
636 struct btrfs_fs_devices *fs_devs, *tmp_fs_devs;
637 struct btrfs_device *dev, *tmp_dev;
639 list_for_each_entry_safe(fs_devs, tmp_fs_devs, &fs_uuids, fs_list) {
644 list_for_each_entry_safe(dev, tmp_dev,
645 &fs_devs->devices, dev_list) {
648 if (skip_dev && skip_dev == dev)
650 if (path && !dev->name)
655 not_found = strcmp(rcu_str_deref(dev->name),
661 /* delete the stale device */
662 if (fs_devs->num_devices == 1) {
663 btrfs_sysfs_remove_fsid(fs_devs);
664 list_del(&fs_devs->fs_list);
665 free_fs_devices(fs_devs);
668 fs_devs->num_devices--;
669 list_del(&dev->dev_list);
670 btrfs_free_device(dev);
676 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
677 struct btrfs_device *device, fmode_t flags,
680 struct request_queue *q;
681 struct block_device *bdev;
682 struct buffer_head *bh;
683 struct btrfs_super_block *disk_super;
692 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
697 disk_super = (struct btrfs_super_block *)bh->b_data;
698 devid = btrfs_stack_device_id(&disk_super->dev_item);
699 if (devid != device->devid)
702 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
705 device->generation = btrfs_super_generation(disk_super);
707 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
708 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
709 fs_devices->seeding = 1;
711 if (bdev_read_only(bdev))
712 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
714 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
717 q = bdev_get_queue(bdev);
718 if (!blk_queue_nonrot(q))
719 fs_devices->rotating = 1;
722 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
723 device->mode = flags;
725 fs_devices->open_devices++;
726 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
727 device->devid != BTRFS_DEV_REPLACE_DEVID) {
728 fs_devices->rw_devices++;
729 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
737 blkdev_put(bdev, flags);
743 * Add new device to list of registered devices
746 * device pointer which was just added or updated when successful
747 * error pointer when failed
749 static noinline struct btrfs_device *device_list_add(const char *path,
750 struct btrfs_super_block *disk_super)
752 struct btrfs_device *device;
753 struct btrfs_fs_devices *fs_devices;
754 struct rcu_string *name;
755 u64 found_transid = btrfs_super_generation(disk_super);
756 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
758 fs_devices = find_fsid(disk_super->fsid);
760 fs_devices = alloc_fs_devices(disk_super->fsid);
761 if (IS_ERR(fs_devices))
762 return ERR_CAST(fs_devices);
764 list_add(&fs_devices->fs_list, &fs_uuids);
768 device = find_device(fs_devices, devid,
769 disk_super->dev_item.uuid);
773 if (fs_devices->opened)
774 return ERR_PTR(-EBUSY);
776 device = btrfs_alloc_device(NULL, &devid,
777 disk_super->dev_item.uuid);
778 if (IS_ERR(device)) {
779 /* we can safely leave the fs_devices entry around */
783 name = rcu_string_strdup(path, GFP_NOFS);
785 btrfs_free_device(device);
786 return ERR_PTR(-ENOMEM);
788 rcu_assign_pointer(device->name, name);
790 mutex_lock(&fs_devices->device_list_mutex);
791 list_add_rcu(&device->dev_list, &fs_devices->devices);
792 fs_devices->num_devices++;
793 mutex_unlock(&fs_devices->device_list_mutex);
795 device->fs_devices = fs_devices;
796 btrfs_free_stale_devices(path, device);
798 if (disk_super->label[0])
799 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
800 disk_super->label, devid, found_transid, path);
802 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
803 disk_super->fsid, devid, found_transid, path);
805 } else if (!device->name || strcmp(device->name->str, path)) {
807 * When FS is already mounted.
808 * 1. If you are here and if the device->name is NULL that
809 * means this device was missing at time of FS mount.
810 * 2. If you are here and if the device->name is different
811 * from 'path' that means either
812 * a. The same device disappeared and reappeared with
814 * b. The missing-disk-which-was-replaced, has
817 * We must allow 1 and 2a above. But 2b would be a spurious
820 * Further in case of 1 and 2a above, the disk at 'path'
821 * would have missed some transaction when it was away and
822 * in case of 2a the stale bdev has to be updated as well.
823 * 2b must not be allowed at all time.
827 * For now, we do allow update to btrfs_fs_device through the
828 * btrfs dev scan cli after FS has been mounted. We're still
829 * tracking a problem where systems fail mount by subvolume id
830 * when we reject replacement on a mounted FS.
832 if (!fs_devices->opened && found_transid < device->generation) {
834 * That is if the FS is _not_ mounted and if you
835 * are here, that means there is more than one
836 * disk with same uuid and devid.We keep the one
837 * with larger generation number or the last-in if
838 * generation are equal.
840 return ERR_PTR(-EEXIST);
843 name = rcu_string_strdup(path, GFP_NOFS);
845 return ERR_PTR(-ENOMEM);
846 rcu_string_free(device->name);
847 rcu_assign_pointer(device->name, name);
848 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
849 fs_devices->missing_devices--;
850 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
855 * Unmount does not free the btrfs_device struct but would zero
856 * generation along with most of the other members. So just update
857 * it back. We need it to pick the disk with largest generation
860 if (!fs_devices->opened)
861 device->generation = found_transid;
863 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
868 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
870 struct btrfs_fs_devices *fs_devices;
871 struct btrfs_device *device;
872 struct btrfs_device *orig_dev;
874 fs_devices = alloc_fs_devices(orig->fsid);
875 if (IS_ERR(fs_devices))
878 mutex_lock(&orig->device_list_mutex);
879 fs_devices->total_devices = orig->total_devices;
881 /* We have held the volume lock, it is safe to get the devices. */
882 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
883 struct rcu_string *name;
885 device = btrfs_alloc_device(NULL, &orig_dev->devid,
891 * This is ok to do without rcu read locked because we hold the
892 * uuid mutex so nothing we touch in here is going to disappear.
894 if (orig_dev->name) {
895 name = rcu_string_strdup(orig_dev->name->str,
898 btrfs_free_device(device);
901 rcu_assign_pointer(device->name, name);
904 list_add(&device->dev_list, &fs_devices->devices);
905 device->fs_devices = fs_devices;
906 fs_devices->num_devices++;
908 mutex_unlock(&orig->device_list_mutex);
911 mutex_unlock(&orig->device_list_mutex);
912 free_fs_devices(fs_devices);
913 return ERR_PTR(-ENOMEM);
917 * After we have read the system tree and know devids belonging to
918 * this filesystem, remove the device which does not belong there.
920 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
922 struct btrfs_device *device, *next;
923 struct btrfs_device *latest_dev = NULL;
925 mutex_lock(&uuid_mutex);
927 /* This is the initialized path, it is safe to release the devices. */
928 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
929 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
930 &device->dev_state)) {
931 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
932 &device->dev_state) &&
934 device->generation > latest_dev->generation)) {
940 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
942 * In the first step, keep the device which has
943 * the correct fsid and the devid that is used
944 * for the dev_replace procedure.
945 * In the second step, the dev_replace state is
946 * read from the device tree and it is known
947 * whether the procedure is really active or
948 * not, which means whether this device is
949 * used or whether it should be removed.
951 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
952 &device->dev_state)) {
957 blkdev_put(device->bdev, device->mode);
959 fs_devices->open_devices--;
961 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
962 list_del_init(&device->dev_alloc_list);
963 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
964 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
966 fs_devices->rw_devices--;
968 list_del_init(&device->dev_list);
969 fs_devices->num_devices--;
970 btrfs_free_device(device);
973 if (fs_devices->seed) {
974 fs_devices = fs_devices->seed;
978 fs_devices->latest_bdev = latest_dev->bdev;
980 mutex_unlock(&uuid_mutex);
983 static void free_device_rcu(struct rcu_head *head)
985 struct btrfs_device *device;
987 device = container_of(head, struct btrfs_device, rcu);
988 btrfs_free_device(device);
991 static void btrfs_close_bdev(struct btrfs_device *device)
996 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
997 sync_blockdev(device->bdev);
998 invalidate_bdev(device->bdev);
1001 blkdev_put(device->bdev, device->mode);
1004 static void btrfs_prepare_close_one_device(struct btrfs_device *device)
1006 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1007 struct btrfs_device *new_device;
1008 struct rcu_string *name;
1011 fs_devices->open_devices--;
1013 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1014 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1015 list_del_init(&device->dev_alloc_list);
1016 fs_devices->rw_devices--;
1019 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1020 fs_devices->missing_devices--;
1022 new_device = btrfs_alloc_device(NULL, &device->devid,
1024 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1026 /* Safe because we are under uuid_mutex */
1028 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1029 BUG_ON(!name); /* -ENOMEM */
1030 rcu_assign_pointer(new_device->name, name);
1033 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1034 new_device->fs_devices = device->fs_devices;
1037 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1039 struct btrfs_device *device, *tmp;
1040 struct list_head pending_put;
1042 INIT_LIST_HEAD(&pending_put);
1044 if (--fs_devices->opened > 0)
1047 mutex_lock(&fs_devices->device_list_mutex);
1048 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1049 btrfs_prepare_close_one_device(device);
1050 list_add(&device->dev_list, &pending_put);
1052 mutex_unlock(&fs_devices->device_list_mutex);
1055 * btrfs_show_devname() is using the device_list_mutex,
1056 * sometimes call to blkdev_put() leads vfs calling
1057 * into this func. So do put outside of device_list_mutex,
1060 while (!list_empty(&pending_put)) {
1061 device = list_first_entry(&pending_put,
1062 struct btrfs_device, dev_list);
1063 list_del(&device->dev_list);
1064 btrfs_close_bdev(device);
1065 call_rcu(&device->rcu, free_device_rcu);
1068 WARN_ON(fs_devices->open_devices);
1069 WARN_ON(fs_devices->rw_devices);
1070 fs_devices->opened = 0;
1071 fs_devices->seeding = 0;
1076 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1078 struct btrfs_fs_devices *seed_devices = NULL;
1081 mutex_lock(&uuid_mutex);
1082 ret = close_fs_devices(fs_devices);
1083 if (!fs_devices->opened) {
1084 seed_devices = fs_devices->seed;
1085 fs_devices->seed = NULL;
1087 mutex_unlock(&uuid_mutex);
1089 while (seed_devices) {
1090 fs_devices = seed_devices;
1091 seed_devices = fs_devices->seed;
1092 close_fs_devices(fs_devices);
1093 free_fs_devices(fs_devices);
1098 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1099 fmode_t flags, void *holder)
1101 struct btrfs_device *device;
1102 struct btrfs_device *latest_dev = NULL;
1105 flags |= FMODE_EXCL;
1107 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1108 /* Just open everything we can; ignore failures here */
1109 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1113 device->generation > latest_dev->generation)
1114 latest_dev = device;
1116 if (fs_devices->open_devices == 0) {
1120 fs_devices->opened = 1;
1121 fs_devices->latest_bdev = latest_dev->bdev;
1122 fs_devices->total_rw_bytes = 0;
1127 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1129 struct btrfs_device *dev1, *dev2;
1131 dev1 = list_entry(a, struct btrfs_device, dev_list);
1132 dev2 = list_entry(b, struct btrfs_device, dev_list);
1134 if (dev1->devid < dev2->devid)
1136 else if (dev1->devid > dev2->devid)
1141 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1142 fmode_t flags, void *holder)
1146 mutex_lock(&uuid_mutex);
1147 mutex_lock(&fs_devices->device_list_mutex);
1148 if (fs_devices->opened) {
1149 fs_devices->opened++;
1152 list_sort(NULL, &fs_devices->devices, devid_cmp);
1153 ret = open_fs_devices(fs_devices, flags, holder);
1155 mutex_unlock(&fs_devices->device_list_mutex);
1156 mutex_unlock(&uuid_mutex);
1161 static void btrfs_release_disk_super(struct page *page)
1167 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1169 struct btrfs_super_block **disk_super)
1174 /* make sure our super fits in the device */
1175 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1178 /* make sure our super fits in the page */
1179 if (sizeof(**disk_super) > PAGE_SIZE)
1182 /* make sure our super doesn't straddle pages on disk */
1183 index = bytenr >> PAGE_SHIFT;
1184 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1187 /* pull in the page with our super */
1188 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1191 if (IS_ERR_OR_NULL(*page))
1196 /* align our pointer to the offset of the super block */
1197 *disk_super = p + (bytenr & ~PAGE_MASK);
1199 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1200 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1201 btrfs_release_disk_super(*page);
1205 if ((*disk_super)->label[0] &&
1206 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1207 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1213 * Look for a btrfs signature on a device. This may be called out of the mount path
1214 * and we are not allowed to call set_blocksize during the scan. The superblock
1215 * is read via pagecache
1217 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1218 struct btrfs_fs_devices **fs_devices_ret)
1220 struct btrfs_super_block *disk_super;
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);
1248 ret = PTR_ERR(device);
1250 *fs_devices_ret = device->fs_devices;
1251 mutex_unlock(&uuid_mutex);
1253 btrfs_release_disk_super(page);
1256 blkdev_put(bdev, flags);
1261 /* helper to account the used device space in the range */
1262 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1263 u64 end, u64 *length)
1265 struct btrfs_key key;
1266 struct btrfs_root *root = device->fs_info->dev_root;
1267 struct btrfs_dev_extent *dev_extent;
1268 struct btrfs_path *path;
1272 struct extent_buffer *l;
1276 if (start >= device->total_bytes ||
1277 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1280 path = btrfs_alloc_path();
1283 path->reada = READA_FORWARD;
1285 key.objectid = device->devid;
1287 key.type = BTRFS_DEV_EXTENT_KEY;
1289 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1293 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1300 slot = path->slots[0];
1301 if (slot >= btrfs_header_nritems(l)) {
1302 ret = btrfs_next_leaf(root, path);
1310 btrfs_item_key_to_cpu(l, &key, slot);
1312 if (key.objectid < device->devid)
1315 if (key.objectid > device->devid)
1318 if (key.type != BTRFS_DEV_EXTENT_KEY)
1321 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1322 extent_end = key.offset + btrfs_dev_extent_length(l,
1324 if (key.offset <= start && extent_end > end) {
1325 *length = end - start + 1;
1327 } else if (key.offset <= start && extent_end > start)
1328 *length += extent_end - start;
1329 else if (key.offset > start && extent_end <= end)
1330 *length += extent_end - key.offset;
1331 else if (key.offset > start && key.offset <= end) {
1332 *length += end - key.offset + 1;
1334 } else if (key.offset > end)
1342 btrfs_free_path(path);
1346 static int contains_pending_extent(struct btrfs_transaction *transaction,
1347 struct btrfs_device *device,
1348 u64 *start, u64 len)
1350 struct btrfs_fs_info *fs_info = device->fs_info;
1351 struct extent_map *em;
1352 struct list_head *search_list = &fs_info->pinned_chunks;
1354 u64 physical_start = *start;
1357 search_list = &transaction->pending_chunks;
1359 list_for_each_entry(em, search_list, list) {
1360 struct map_lookup *map;
1363 map = em->map_lookup;
1364 for (i = 0; i < map->num_stripes; i++) {
1367 if (map->stripes[i].dev != device)
1369 if (map->stripes[i].physical >= physical_start + len ||
1370 map->stripes[i].physical + em->orig_block_len <=
1374 * Make sure that while processing the pinned list we do
1375 * not override our *start with a lower value, because
1376 * we can have pinned chunks that fall within this
1377 * device hole and that have lower physical addresses
1378 * than the pending chunks we processed before. If we
1379 * do not take this special care we can end up getting
1380 * 2 pending chunks that start at the same physical
1381 * device offsets because the end offset of a pinned
1382 * chunk can be equal to the start offset of some
1385 end = map->stripes[i].physical + em->orig_block_len;
1392 if (search_list != &fs_info->pinned_chunks) {
1393 search_list = &fs_info->pinned_chunks;
1402 * find_free_dev_extent_start - find free space in the specified device
1403 * @device: the device which we search the free space in
1404 * @num_bytes: the size of the free space that we need
1405 * @search_start: the position from which to begin the search
1406 * @start: store the start of the free space.
1407 * @len: the size of the free space. that we find, or the size
1408 * of the max free space if we don't find suitable free space
1410 * this uses a pretty simple search, the expectation is that it is
1411 * called very infrequently and that a given device has a small number
1414 * @start is used to store the start of the free space if we find. But if we
1415 * don't find suitable free space, it will be used to store the start position
1416 * of the max free space.
1418 * @len is used to store the size of the free space that we find.
1419 * But if we don't find suitable free space, it is used to store the size of
1420 * the max free space.
1422 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1423 struct btrfs_device *device, u64 num_bytes,
1424 u64 search_start, u64 *start, u64 *len)
1426 struct btrfs_fs_info *fs_info = device->fs_info;
1427 struct btrfs_root *root = fs_info->dev_root;
1428 struct btrfs_key key;
1429 struct btrfs_dev_extent *dev_extent;
1430 struct btrfs_path *path;
1435 u64 search_end = device->total_bytes;
1438 struct extent_buffer *l;
1441 * We don't want to overwrite the superblock on the drive nor any area
1442 * used by the boot loader (grub for example), so we make sure to start
1443 * at an offset of at least 1MB.
1445 search_start = max_t(u64, search_start, SZ_1M);
1447 path = btrfs_alloc_path();
1451 max_hole_start = search_start;
1455 if (search_start >= search_end ||
1456 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1461 path->reada = READA_FORWARD;
1462 path->search_commit_root = 1;
1463 path->skip_locking = 1;
1465 key.objectid = device->devid;
1466 key.offset = search_start;
1467 key.type = BTRFS_DEV_EXTENT_KEY;
1469 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1473 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1480 slot = path->slots[0];
1481 if (slot >= btrfs_header_nritems(l)) {
1482 ret = btrfs_next_leaf(root, path);
1490 btrfs_item_key_to_cpu(l, &key, slot);
1492 if (key.objectid < device->devid)
1495 if (key.objectid > device->devid)
1498 if (key.type != BTRFS_DEV_EXTENT_KEY)
1501 if (key.offset > search_start) {
1502 hole_size = key.offset - search_start;
1505 * Have to check before we set max_hole_start, otherwise
1506 * we could end up sending back this offset anyway.
1508 if (contains_pending_extent(transaction, device,
1511 if (key.offset >= search_start) {
1512 hole_size = key.offset - search_start;
1519 if (hole_size > max_hole_size) {
1520 max_hole_start = search_start;
1521 max_hole_size = hole_size;
1525 * If this free space is greater than which we need,
1526 * it must be the max free space that we have found
1527 * until now, so max_hole_start must point to the start
1528 * of this free space and the length of this free space
1529 * is stored in max_hole_size. Thus, we return
1530 * max_hole_start and max_hole_size and go back to the
1533 if (hole_size >= num_bytes) {
1539 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1540 extent_end = key.offset + btrfs_dev_extent_length(l,
1542 if (extent_end > search_start)
1543 search_start = extent_end;
1550 * At this point, search_start should be the end of
1551 * allocated dev extents, and when shrinking the device,
1552 * search_end may be smaller than search_start.
1554 if (search_end > search_start) {
1555 hole_size = search_end - search_start;
1557 if (contains_pending_extent(transaction, device, &search_start,
1559 btrfs_release_path(path);
1563 if (hole_size > max_hole_size) {
1564 max_hole_start = search_start;
1565 max_hole_size = hole_size;
1570 if (max_hole_size < num_bytes)
1576 btrfs_free_path(path);
1577 *start = max_hole_start;
1579 *len = max_hole_size;
1583 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1584 struct btrfs_device *device, u64 num_bytes,
1585 u64 *start, u64 *len)
1587 /* FIXME use last free of some kind */
1588 return find_free_dev_extent_start(trans->transaction, device,
1589 num_bytes, 0, start, len);
1592 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1593 struct btrfs_device *device,
1594 u64 start, u64 *dev_extent_len)
1596 struct btrfs_fs_info *fs_info = device->fs_info;
1597 struct btrfs_root *root = fs_info->dev_root;
1599 struct btrfs_path *path;
1600 struct btrfs_key key;
1601 struct btrfs_key found_key;
1602 struct extent_buffer *leaf = NULL;
1603 struct btrfs_dev_extent *extent = NULL;
1605 path = btrfs_alloc_path();
1609 key.objectid = device->devid;
1611 key.type = BTRFS_DEV_EXTENT_KEY;
1613 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1615 ret = btrfs_previous_item(root, path, key.objectid,
1616 BTRFS_DEV_EXTENT_KEY);
1619 leaf = path->nodes[0];
1620 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1621 extent = btrfs_item_ptr(leaf, path->slots[0],
1622 struct btrfs_dev_extent);
1623 BUG_ON(found_key.offset > start || found_key.offset +
1624 btrfs_dev_extent_length(leaf, extent) < start);
1626 btrfs_release_path(path);
1628 } else if (ret == 0) {
1629 leaf = path->nodes[0];
1630 extent = btrfs_item_ptr(leaf, path->slots[0],
1631 struct btrfs_dev_extent);
1633 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1637 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1639 ret = btrfs_del_item(trans, root, path);
1641 btrfs_handle_fs_error(fs_info, ret,
1642 "Failed to remove dev extent item");
1644 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1647 btrfs_free_path(path);
1651 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1652 struct btrfs_device *device,
1653 u64 chunk_offset, u64 start, u64 num_bytes)
1656 struct btrfs_path *path;
1657 struct btrfs_fs_info *fs_info = device->fs_info;
1658 struct btrfs_root *root = fs_info->dev_root;
1659 struct btrfs_dev_extent *extent;
1660 struct extent_buffer *leaf;
1661 struct btrfs_key key;
1663 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1664 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1665 path = btrfs_alloc_path();
1669 key.objectid = device->devid;
1671 key.type = BTRFS_DEV_EXTENT_KEY;
1672 ret = btrfs_insert_empty_item(trans, root, path, &key,
1677 leaf = path->nodes[0];
1678 extent = btrfs_item_ptr(leaf, path->slots[0],
1679 struct btrfs_dev_extent);
1680 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1681 BTRFS_CHUNK_TREE_OBJECTID);
1682 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1683 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1684 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1686 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1687 btrfs_mark_buffer_dirty(leaf);
1689 btrfs_free_path(path);
1693 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1695 struct extent_map_tree *em_tree;
1696 struct extent_map *em;
1700 em_tree = &fs_info->mapping_tree.map_tree;
1701 read_lock(&em_tree->lock);
1702 n = rb_last(&em_tree->map);
1704 em = rb_entry(n, struct extent_map, rb_node);
1705 ret = em->start + em->len;
1707 read_unlock(&em_tree->lock);
1712 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1716 struct btrfs_key key;
1717 struct btrfs_key found_key;
1718 struct btrfs_path *path;
1720 path = btrfs_alloc_path();
1724 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1725 key.type = BTRFS_DEV_ITEM_KEY;
1726 key.offset = (u64)-1;
1728 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1732 BUG_ON(ret == 0); /* Corruption */
1734 ret = btrfs_previous_item(fs_info->chunk_root, path,
1735 BTRFS_DEV_ITEMS_OBJECTID,
1736 BTRFS_DEV_ITEM_KEY);
1740 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1742 *devid_ret = found_key.offset + 1;
1746 btrfs_free_path(path);
1751 * the device information is stored in the chunk root
1752 * the btrfs_device struct should be fully filled in
1754 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1755 struct btrfs_fs_info *fs_info,
1756 struct btrfs_device *device)
1758 struct btrfs_root *root = fs_info->chunk_root;
1760 struct btrfs_path *path;
1761 struct btrfs_dev_item *dev_item;
1762 struct extent_buffer *leaf;
1763 struct btrfs_key key;
1766 path = btrfs_alloc_path();
1770 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1771 key.type = BTRFS_DEV_ITEM_KEY;
1772 key.offset = device->devid;
1774 ret = btrfs_insert_empty_item(trans, root, path, &key,
1779 leaf = path->nodes[0];
1780 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1782 btrfs_set_device_id(leaf, dev_item, device->devid);
1783 btrfs_set_device_generation(leaf, dev_item, 0);
1784 btrfs_set_device_type(leaf, dev_item, device->type);
1785 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1786 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1787 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1788 btrfs_set_device_total_bytes(leaf, dev_item,
1789 btrfs_device_get_disk_total_bytes(device));
1790 btrfs_set_device_bytes_used(leaf, dev_item,
1791 btrfs_device_get_bytes_used(device));
1792 btrfs_set_device_group(leaf, dev_item, 0);
1793 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1794 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1795 btrfs_set_device_start_offset(leaf, dev_item, 0);
1797 ptr = btrfs_device_uuid(dev_item);
1798 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1799 ptr = btrfs_device_fsid(dev_item);
1800 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1801 btrfs_mark_buffer_dirty(leaf);
1805 btrfs_free_path(path);
1810 * Function to update ctime/mtime for a given device path.
1811 * Mainly used for ctime/mtime based probe like libblkid.
1813 static void update_dev_time(const char *path_name)
1817 filp = filp_open(path_name, O_RDWR, 0);
1820 file_update_time(filp);
1821 filp_close(filp, NULL);
1824 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1825 struct btrfs_device *device)
1827 struct btrfs_root *root = fs_info->chunk_root;
1829 struct btrfs_path *path;
1830 struct btrfs_key key;
1831 struct btrfs_trans_handle *trans;
1833 path = btrfs_alloc_path();
1837 trans = btrfs_start_transaction(root, 0);
1838 if (IS_ERR(trans)) {
1839 btrfs_free_path(path);
1840 return PTR_ERR(trans);
1842 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1843 key.type = BTRFS_DEV_ITEM_KEY;
1844 key.offset = device->devid;
1846 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1850 btrfs_abort_transaction(trans, ret);
1851 btrfs_end_transaction(trans);
1855 ret = btrfs_del_item(trans, root, path);
1857 btrfs_abort_transaction(trans, ret);
1858 btrfs_end_transaction(trans);
1862 btrfs_free_path(path);
1864 ret = btrfs_commit_transaction(trans);
1869 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1870 * filesystem. It's up to the caller to adjust that number regarding eg. device
1873 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1881 seq = read_seqbegin(&fs_info->profiles_lock);
1883 all_avail = fs_info->avail_data_alloc_bits |
1884 fs_info->avail_system_alloc_bits |
1885 fs_info->avail_metadata_alloc_bits;
1886 } while (read_seqretry(&fs_info->profiles_lock, seq));
1888 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1889 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1892 if (num_devices < btrfs_raid_array[i].devs_min) {
1893 int ret = btrfs_raid_array[i].mindev_error;
1903 static struct btrfs_device * btrfs_find_next_active_device(
1904 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1906 struct btrfs_device *next_device;
1908 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1909 if (next_device != device &&
1910 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1911 && next_device->bdev)
1919 * Helper function to check if the given device is part of s_bdev / latest_bdev
1920 * and replace it with the provided or the next active device, in the context
1921 * where this function called, there should be always be another device (or
1922 * this_dev) which is active.
1924 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1925 struct btrfs_device *device, struct btrfs_device *this_dev)
1927 struct btrfs_device *next_device;
1930 next_device = this_dev;
1932 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1934 ASSERT(next_device);
1936 if (fs_info->sb->s_bdev &&
1937 (fs_info->sb->s_bdev == device->bdev))
1938 fs_info->sb->s_bdev = next_device->bdev;
1940 if (fs_info->fs_devices->latest_bdev == device->bdev)
1941 fs_info->fs_devices->latest_bdev = next_device->bdev;
1944 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1947 struct btrfs_device *device;
1948 struct btrfs_fs_devices *cur_devices;
1949 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1953 mutex_lock(&uuid_mutex);
1955 num_devices = fs_devices->num_devices;
1956 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1957 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1958 WARN_ON(num_devices < 1);
1961 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1963 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1967 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1972 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1973 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1977 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1978 fs_info->fs_devices->rw_devices == 1) {
1979 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1983 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1984 mutex_lock(&fs_info->chunk_mutex);
1985 list_del_init(&device->dev_alloc_list);
1986 device->fs_devices->rw_devices--;
1987 mutex_unlock(&fs_info->chunk_mutex);
1990 mutex_unlock(&uuid_mutex);
1991 ret = btrfs_shrink_device(device, 0);
1992 mutex_lock(&uuid_mutex);
1997 * TODO: the superblock still includes this device in its num_devices
1998 * counter although write_all_supers() is not locked out. This
1999 * could give a filesystem state which requires a degraded mount.
2001 ret = btrfs_rm_dev_item(fs_info, device);
2005 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2006 btrfs_scrub_cancel_dev(fs_info, device);
2009 * the device list mutex makes sure that we don't change
2010 * the device list while someone else is writing out all
2011 * the device supers. Whoever is writing all supers, should
2012 * lock the device list mutex before getting the number of
2013 * devices in the super block (super_copy). Conversely,
2014 * whoever updates the number of devices in the super block
2015 * (super_copy) should hold the device list mutex.
2019 * In normal cases the cur_devices == fs_devices. But in case
2020 * of deleting a seed device, the cur_devices should point to
2021 * its own fs_devices listed under the fs_devices->seed.
2023 cur_devices = device->fs_devices;
2024 mutex_lock(&fs_devices->device_list_mutex);
2025 list_del_rcu(&device->dev_list);
2027 cur_devices->num_devices--;
2028 cur_devices->total_devices--;
2029 /* Update total_devices of the parent fs_devices if it's seed */
2030 if (cur_devices != fs_devices)
2031 fs_devices->total_devices--;
2033 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2034 cur_devices->missing_devices--;
2036 btrfs_assign_next_active_device(fs_info, device, NULL);
2039 cur_devices->open_devices--;
2040 /* remove sysfs entry */
2041 btrfs_sysfs_rm_device_link(fs_devices, device);
2044 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2045 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2046 mutex_unlock(&fs_devices->device_list_mutex);
2049 * at this point, the device is zero sized and detached from
2050 * the devices list. All that's left is to zero out the old
2051 * supers and free the device.
2053 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2054 btrfs_scratch_superblocks(device->bdev, device->name->str);
2056 btrfs_close_bdev(device);
2057 call_rcu(&device->rcu, free_device_rcu);
2059 if (cur_devices->open_devices == 0) {
2060 while (fs_devices) {
2061 if (fs_devices->seed == cur_devices) {
2062 fs_devices->seed = cur_devices->seed;
2065 fs_devices = fs_devices->seed;
2067 cur_devices->seed = NULL;
2068 close_fs_devices(cur_devices);
2069 free_fs_devices(cur_devices);
2073 mutex_unlock(&uuid_mutex);
2077 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2078 mutex_lock(&fs_info->chunk_mutex);
2079 list_add(&device->dev_alloc_list,
2080 &fs_devices->alloc_list);
2081 device->fs_devices->rw_devices++;
2082 mutex_unlock(&fs_info->chunk_mutex);
2087 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2088 struct btrfs_device *srcdev)
2090 struct btrfs_fs_devices *fs_devices;
2092 lockdep_assert_held(&fs_info->fs_devices->device_list_mutex);
2095 * in case of fs with no seed, srcdev->fs_devices will point
2096 * to fs_devices of fs_info. However when the dev being replaced is
2097 * a seed dev it will point to the seed's local fs_devices. In short
2098 * srcdev will have its correct fs_devices in both the cases.
2100 fs_devices = srcdev->fs_devices;
2102 list_del_rcu(&srcdev->dev_list);
2103 list_del(&srcdev->dev_alloc_list);
2104 fs_devices->num_devices--;
2105 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2106 fs_devices->missing_devices--;
2108 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2109 fs_devices->rw_devices--;
2112 fs_devices->open_devices--;
2115 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2116 struct btrfs_device *srcdev)
2118 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2120 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2121 /* zero out the old super if it is writable */
2122 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2125 btrfs_close_bdev(srcdev);
2126 call_rcu(&srcdev->rcu, free_device_rcu);
2128 /* if this is no devs we rather delete the fs_devices */
2129 if (!fs_devices->num_devices) {
2130 struct btrfs_fs_devices *tmp_fs_devices;
2133 * On a mounted FS, num_devices can't be zero unless it's a
2134 * seed. In case of a seed device being replaced, the replace
2135 * target added to the sprout FS, so there will be no more
2136 * device left under the seed FS.
2138 ASSERT(fs_devices->seeding);
2140 tmp_fs_devices = fs_info->fs_devices;
2141 while (tmp_fs_devices) {
2142 if (tmp_fs_devices->seed == fs_devices) {
2143 tmp_fs_devices->seed = fs_devices->seed;
2146 tmp_fs_devices = tmp_fs_devices->seed;
2148 fs_devices->seed = NULL;
2149 close_fs_devices(fs_devices);
2150 free_fs_devices(fs_devices);
2154 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2155 struct btrfs_device *tgtdev)
2157 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2160 mutex_lock(&fs_devices->device_list_mutex);
2162 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2165 fs_devices->open_devices--;
2167 fs_devices->num_devices--;
2169 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2171 list_del_rcu(&tgtdev->dev_list);
2173 mutex_unlock(&fs_devices->device_list_mutex);
2176 * The update_dev_time() with in btrfs_scratch_superblocks()
2177 * may lead to a call to btrfs_show_devname() which will try
2178 * to hold device_list_mutex. And here this device
2179 * is already out of device list, so we don't have to hold
2180 * the device_list_mutex lock.
2182 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2184 btrfs_close_bdev(tgtdev);
2185 call_rcu(&tgtdev->rcu, free_device_rcu);
2188 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2189 const char *device_path,
2190 struct btrfs_device **device)
2193 struct btrfs_super_block *disk_super;
2196 struct block_device *bdev;
2197 struct buffer_head *bh;
2200 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2201 fs_info->bdev_holder, 0, &bdev, &bh);
2204 disk_super = (struct btrfs_super_block *)bh->b_data;
2205 devid = btrfs_stack_device_id(&disk_super->dev_item);
2206 dev_uuid = disk_super->dev_item.uuid;
2207 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2211 blkdev_put(bdev, FMODE_READ);
2215 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2216 const char *device_path,
2217 struct btrfs_device **device)
2220 if (strcmp(device_path, "missing") == 0) {
2221 struct list_head *devices;
2222 struct btrfs_device *tmp;
2224 devices = &fs_info->fs_devices->devices;
2225 list_for_each_entry(tmp, devices, dev_list) {
2226 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2227 &tmp->dev_state) && !tmp->bdev) {
2234 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2238 return btrfs_find_device_by_path(fs_info, device_path, device);
2243 * Lookup a device given by device id, or the path if the id is 0.
2245 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2246 const char *devpath,
2247 struct btrfs_device **device)
2253 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2257 if (!devpath || !devpath[0])
2260 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2267 * does all the dirty work required for changing file system's UUID.
2269 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2271 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2272 struct btrfs_fs_devices *old_devices;
2273 struct btrfs_fs_devices *seed_devices;
2274 struct btrfs_super_block *disk_super = fs_info->super_copy;
2275 struct btrfs_device *device;
2278 lockdep_assert_held(&uuid_mutex);
2279 if (!fs_devices->seeding)
2282 seed_devices = alloc_fs_devices(NULL);
2283 if (IS_ERR(seed_devices))
2284 return PTR_ERR(seed_devices);
2286 old_devices = clone_fs_devices(fs_devices);
2287 if (IS_ERR(old_devices)) {
2288 kfree(seed_devices);
2289 return PTR_ERR(old_devices);
2292 list_add(&old_devices->fs_list, &fs_uuids);
2294 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2295 seed_devices->opened = 1;
2296 INIT_LIST_HEAD(&seed_devices->devices);
2297 INIT_LIST_HEAD(&seed_devices->alloc_list);
2298 mutex_init(&seed_devices->device_list_mutex);
2300 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2301 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2303 list_for_each_entry(device, &seed_devices->devices, dev_list)
2304 device->fs_devices = seed_devices;
2306 mutex_lock(&fs_info->chunk_mutex);
2307 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2308 mutex_unlock(&fs_info->chunk_mutex);
2310 fs_devices->seeding = 0;
2311 fs_devices->num_devices = 0;
2312 fs_devices->open_devices = 0;
2313 fs_devices->missing_devices = 0;
2314 fs_devices->rotating = 0;
2315 fs_devices->seed = seed_devices;
2317 generate_random_uuid(fs_devices->fsid);
2318 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2319 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2320 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2322 super_flags = btrfs_super_flags(disk_super) &
2323 ~BTRFS_SUPER_FLAG_SEEDING;
2324 btrfs_set_super_flags(disk_super, super_flags);
2330 * Store the expected generation for seed devices in device items.
2332 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2333 struct btrfs_fs_info *fs_info)
2335 struct btrfs_root *root = fs_info->chunk_root;
2336 struct btrfs_path *path;
2337 struct extent_buffer *leaf;
2338 struct btrfs_dev_item *dev_item;
2339 struct btrfs_device *device;
2340 struct btrfs_key key;
2341 u8 fs_uuid[BTRFS_FSID_SIZE];
2342 u8 dev_uuid[BTRFS_UUID_SIZE];
2346 path = btrfs_alloc_path();
2350 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2352 key.type = BTRFS_DEV_ITEM_KEY;
2355 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2359 leaf = path->nodes[0];
2361 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2362 ret = btrfs_next_leaf(root, path);
2367 leaf = path->nodes[0];
2368 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2369 btrfs_release_path(path);
2373 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2374 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2375 key.type != BTRFS_DEV_ITEM_KEY)
2378 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2379 struct btrfs_dev_item);
2380 devid = btrfs_device_id(leaf, dev_item);
2381 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2383 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2385 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2386 BUG_ON(!device); /* Logic error */
2388 if (device->fs_devices->seeding) {
2389 btrfs_set_device_generation(leaf, dev_item,
2390 device->generation);
2391 btrfs_mark_buffer_dirty(leaf);
2399 btrfs_free_path(path);
2403 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2405 struct btrfs_root *root = fs_info->dev_root;
2406 struct request_queue *q;
2407 struct btrfs_trans_handle *trans;
2408 struct btrfs_device *device;
2409 struct block_device *bdev;
2410 struct super_block *sb = fs_info->sb;
2411 struct rcu_string *name;
2412 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2414 int seeding_dev = 0;
2416 bool unlocked = false;
2418 if (sb_rdonly(sb) && !fs_devices->seeding)
2421 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2422 fs_info->bdev_holder);
2424 return PTR_ERR(bdev);
2426 if (fs_devices->seeding) {
2428 down_write(&sb->s_umount);
2429 mutex_lock(&uuid_mutex);
2432 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2434 mutex_lock(&fs_devices->device_list_mutex);
2435 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2436 if (device->bdev == bdev) {
2439 &fs_devices->device_list_mutex);
2443 mutex_unlock(&fs_devices->device_list_mutex);
2445 device = btrfs_alloc_device(fs_info, NULL, NULL);
2446 if (IS_ERR(device)) {
2447 /* we can safely leave the fs_devices entry around */
2448 ret = PTR_ERR(device);
2452 name = rcu_string_strdup(device_path, GFP_KERNEL);
2455 goto error_free_device;
2457 rcu_assign_pointer(device->name, name);
2459 trans = btrfs_start_transaction(root, 0);
2460 if (IS_ERR(trans)) {
2461 ret = PTR_ERR(trans);
2462 goto error_free_device;
2465 q = bdev_get_queue(bdev);
2466 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2467 device->generation = trans->transid;
2468 device->io_width = fs_info->sectorsize;
2469 device->io_align = fs_info->sectorsize;
2470 device->sector_size = fs_info->sectorsize;
2471 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2472 fs_info->sectorsize);
2473 device->disk_total_bytes = device->total_bytes;
2474 device->commit_total_bytes = device->total_bytes;
2475 device->fs_info = fs_info;
2476 device->bdev = bdev;
2477 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2478 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2479 device->mode = FMODE_EXCL;
2480 device->dev_stats_valid = 1;
2481 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2484 sb->s_flags &= ~SB_RDONLY;
2485 ret = btrfs_prepare_sprout(fs_info);
2487 btrfs_abort_transaction(trans, ret);
2492 device->fs_devices = fs_devices;
2494 mutex_lock(&fs_devices->device_list_mutex);
2495 mutex_lock(&fs_info->chunk_mutex);
2496 list_add_rcu(&device->dev_list, &fs_devices->devices);
2497 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2498 fs_devices->num_devices++;
2499 fs_devices->open_devices++;
2500 fs_devices->rw_devices++;
2501 fs_devices->total_devices++;
2502 fs_devices->total_rw_bytes += device->total_bytes;
2504 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2506 if (!blk_queue_nonrot(q))
2507 fs_devices->rotating = 1;
2509 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2510 btrfs_set_super_total_bytes(fs_info->super_copy,
2511 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2513 tmp = btrfs_super_num_devices(fs_info->super_copy);
2514 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2516 /* add sysfs device entry */
2517 btrfs_sysfs_add_device_link(fs_devices, device);
2520 * we've got more storage, clear any full flags on the space
2523 btrfs_clear_space_info_full(fs_info);
2525 mutex_unlock(&fs_info->chunk_mutex);
2526 mutex_unlock(&fs_devices->device_list_mutex);
2529 mutex_lock(&fs_info->chunk_mutex);
2530 ret = init_first_rw_device(trans, fs_info);
2531 mutex_unlock(&fs_info->chunk_mutex);
2533 btrfs_abort_transaction(trans, ret);
2538 ret = btrfs_add_dev_item(trans, fs_info, device);
2540 btrfs_abort_transaction(trans, ret);
2545 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2547 ret = btrfs_finish_sprout(trans, fs_info);
2549 btrfs_abort_transaction(trans, ret);
2553 /* Sprouting would change fsid of the mounted root,
2554 * so rename the fsid on the sysfs
2556 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2558 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2560 "sysfs: failed to create fsid for sprout");
2563 ret = btrfs_commit_transaction(trans);
2566 mutex_unlock(&uuid_mutex);
2567 up_write(&sb->s_umount);
2570 if (ret) /* transaction commit */
2573 ret = btrfs_relocate_sys_chunks(fs_info);
2575 btrfs_handle_fs_error(fs_info, ret,
2576 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2577 trans = btrfs_attach_transaction(root);
2578 if (IS_ERR(trans)) {
2579 if (PTR_ERR(trans) == -ENOENT)
2581 ret = PTR_ERR(trans);
2585 ret = btrfs_commit_transaction(trans);
2588 /* Update ctime/mtime for libblkid */
2589 update_dev_time(device_path);
2593 btrfs_sysfs_rm_device_link(fs_devices, device);
2596 sb->s_flags |= SB_RDONLY;
2598 btrfs_end_transaction(trans);
2600 btrfs_free_device(device);
2602 blkdev_put(bdev, FMODE_EXCL);
2603 if (seeding_dev && !unlocked) {
2604 mutex_unlock(&uuid_mutex);
2605 up_write(&sb->s_umount);
2610 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2611 struct btrfs_device *device)
2614 struct btrfs_path *path;
2615 struct btrfs_root *root = device->fs_info->chunk_root;
2616 struct btrfs_dev_item *dev_item;
2617 struct extent_buffer *leaf;
2618 struct btrfs_key key;
2620 path = btrfs_alloc_path();
2624 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2625 key.type = BTRFS_DEV_ITEM_KEY;
2626 key.offset = device->devid;
2628 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2637 leaf = path->nodes[0];
2638 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2640 btrfs_set_device_id(leaf, dev_item, device->devid);
2641 btrfs_set_device_type(leaf, dev_item, device->type);
2642 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2643 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2644 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2645 btrfs_set_device_total_bytes(leaf, dev_item,
2646 btrfs_device_get_disk_total_bytes(device));
2647 btrfs_set_device_bytes_used(leaf, dev_item,
2648 btrfs_device_get_bytes_used(device));
2649 btrfs_mark_buffer_dirty(leaf);
2652 btrfs_free_path(path);
2656 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2657 struct btrfs_device *device, u64 new_size)
2659 struct btrfs_fs_info *fs_info = device->fs_info;
2660 struct btrfs_super_block *super_copy = fs_info->super_copy;
2661 struct btrfs_fs_devices *fs_devices;
2665 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2668 new_size = round_down(new_size, fs_info->sectorsize);
2670 mutex_lock(&fs_info->chunk_mutex);
2671 old_total = btrfs_super_total_bytes(super_copy);
2672 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2674 if (new_size <= device->total_bytes ||
2675 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2676 mutex_unlock(&fs_info->chunk_mutex);
2680 fs_devices = fs_info->fs_devices;
2682 btrfs_set_super_total_bytes(super_copy,
2683 round_down(old_total + diff, fs_info->sectorsize));
2684 device->fs_devices->total_rw_bytes += diff;
2686 btrfs_device_set_total_bytes(device, new_size);
2687 btrfs_device_set_disk_total_bytes(device, new_size);
2688 btrfs_clear_space_info_full(device->fs_info);
2689 if (list_empty(&device->resized_list))
2690 list_add_tail(&device->resized_list,
2691 &fs_devices->resized_devices);
2692 mutex_unlock(&fs_info->chunk_mutex);
2694 return btrfs_update_device(trans, device);
2697 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2698 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2700 struct btrfs_root *root = fs_info->chunk_root;
2702 struct btrfs_path *path;
2703 struct btrfs_key key;
2705 path = btrfs_alloc_path();
2709 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2710 key.offset = chunk_offset;
2711 key.type = BTRFS_CHUNK_ITEM_KEY;
2713 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2716 else if (ret > 0) { /* Logic error or corruption */
2717 btrfs_handle_fs_error(fs_info, -ENOENT,
2718 "Failed lookup while freeing chunk.");
2723 ret = btrfs_del_item(trans, root, path);
2725 btrfs_handle_fs_error(fs_info, ret,
2726 "Failed to delete chunk item.");
2728 btrfs_free_path(path);
2732 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2734 struct btrfs_super_block *super_copy = fs_info->super_copy;
2735 struct btrfs_disk_key *disk_key;
2736 struct btrfs_chunk *chunk;
2743 struct btrfs_key key;
2745 mutex_lock(&fs_info->chunk_mutex);
2746 array_size = btrfs_super_sys_array_size(super_copy);
2748 ptr = super_copy->sys_chunk_array;
2751 while (cur < array_size) {
2752 disk_key = (struct btrfs_disk_key *)ptr;
2753 btrfs_disk_key_to_cpu(&key, disk_key);
2755 len = sizeof(*disk_key);
2757 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2758 chunk = (struct btrfs_chunk *)(ptr + len);
2759 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2760 len += btrfs_chunk_item_size(num_stripes);
2765 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2766 key.offset == chunk_offset) {
2767 memmove(ptr, ptr + len, array_size - (cur + len));
2769 btrfs_set_super_sys_array_size(super_copy, array_size);
2775 mutex_unlock(&fs_info->chunk_mutex);
2779 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2780 u64 logical, u64 length)
2782 struct extent_map_tree *em_tree;
2783 struct extent_map *em;
2785 em_tree = &fs_info->mapping_tree.map_tree;
2786 read_lock(&em_tree->lock);
2787 em = lookup_extent_mapping(em_tree, logical, length);
2788 read_unlock(&em_tree->lock);
2791 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2793 return ERR_PTR(-EINVAL);
2796 if (em->start > logical || em->start + em->len < logical) {
2798 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2799 logical, length, em->start, em->start + em->len);
2800 free_extent_map(em);
2801 return ERR_PTR(-EINVAL);
2804 /* callers are responsible for dropping em's ref. */
2808 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2809 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2811 struct extent_map *em;
2812 struct map_lookup *map;
2813 u64 dev_extent_len = 0;
2815 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2817 em = get_chunk_map(fs_info, chunk_offset, 1);
2820 * This is a logic error, but we don't want to just rely on the
2821 * user having built with ASSERT enabled, so if ASSERT doesn't
2822 * do anything we still error out.
2827 map = em->map_lookup;
2828 mutex_lock(&fs_info->chunk_mutex);
2829 check_system_chunk(trans, map->type);
2830 mutex_unlock(&fs_info->chunk_mutex);
2833 * Take the device list mutex to prevent races with the final phase of
2834 * a device replace operation that replaces the device object associated
2835 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2837 mutex_lock(&fs_devices->device_list_mutex);
2838 for (i = 0; i < map->num_stripes; i++) {
2839 struct btrfs_device *device = map->stripes[i].dev;
2840 ret = btrfs_free_dev_extent(trans, device,
2841 map->stripes[i].physical,
2844 mutex_unlock(&fs_devices->device_list_mutex);
2845 btrfs_abort_transaction(trans, ret);
2849 if (device->bytes_used > 0) {
2850 mutex_lock(&fs_info->chunk_mutex);
2851 btrfs_device_set_bytes_used(device,
2852 device->bytes_used - dev_extent_len);
2853 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2854 btrfs_clear_space_info_full(fs_info);
2855 mutex_unlock(&fs_info->chunk_mutex);
2858 if (map->stripes[i].dev) {
2859 ret = btrfs_update_device(trans, map->stripes[i].dev);
2861 mutex_unlock(&fs_devices->device_list_mutex);
2862 btrfs_abort_transaction(trans, ret);
2867 mutex_unlock(&fs_devices->device_list_mutex);
2869 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2871 btrfs_abort_transaction(trans, ret);
2875 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2877 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2878 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2880 btrfs_abort_transaction(trans, ret);
2885 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2887 btrfs_abort_transaction(trans, ret);
2893 free_extent_map(em);
2897 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2899 struct btrfs_root *root = fs_info->chunk_root;
2900 struct btrfs_trans_handle *trans;
2904 * Prevent races with automatic removal of unused block groups.
2905 * After we relocate and before we remove the chunk with offset
2906 * chunk_offset, automatic removal of the block group can kick in,
2907 * resulting in a failure when calling btrfs_remove_chunk() below.
2909 * Make sure to acquire this mutex before doing a tree search (dev
2910 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2911 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2912 * we release the path used to search the chunk/dev tree and before
2913 * the current task acquires this mutex and calls us.
2915 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2917 ret = btrfs_can_relocate(fs_info, chunk_offset);
2921 /* step one, relocate all the extents inside this chunk */
2922 btrfs_scrub_pause(fs_info);
2923 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2924 btrfs_scrub_continue(fs_info);
2929 * We add the kobjects here (and after forcing data chunk creation)
2930 * since relocation is the only place we'll create chunks of a new
2931 * type at runtime. The only place where we'll remove the last
2932 * chunk of a type is the call immediately below this one. Even
2933 * so, we're protected against races with the cleaner thread since
2934 * we're covered by the delete_unused_bgs_mutex.
2936 btrfs_add_raid_kobjects(fs_info);
2938 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2940 if (IS_ERR(trans)) {
2941 ret = PTR_ERR(trans);
2942 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2947 * step two, delete the device extents and the
2948 * chunk tree entries
2950 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
2951 btrfs_end_transaction(trans);
2955 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2957 struct btrfs_root *chunk_root = fs_info->chunk_root;
2958 struct btrfs_path *path;
2959 struct extent_buffer *leaf;
2960 struct btrfs_chunk *chunk;
2961 struct btrfs_key key;
2962 struct btrfs_key found_key;
2964 bool retried = false;
2968 path = btrfs_alloc_path();
2973 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2974 key.offset = (u64)-1;
2975 key.type = BTRFS_CHUNK_ITEM_KEY;
2978 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2979 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2981 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2984 BUG_ON(ret == 0); /* Corruption */
2986 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2989 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2995 leaf = path->nodes[0];
2996 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2998 chunk = btrfs_item_ptr(leaf, path->slots[0],
2999 struct btrfs_chunk);
3000 chunk_type = btrfs_chunk_type(leaf, chunk);
3001 btrfs_release_path(path);
3003 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3004 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3010 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3012 if (found_key.offset == 0)
3014 key.offset = found_key.offset - 1;
3017 if (failed && !retried) {
3021 } else if (WARN_ON(failed && retried)) {
3025 btrfs_free_path(path);
3030 * return 1 : allocate a data chunk successfully,
3031 * return <0: errors during allocating a data chunk,
3032 * return 0 : no need to allocate a data chunk.
3034 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3037 struct btrfs_block_group_cache *cache;
3041 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3043 chunk_type = cache->flags;
3044 btrfs_put_block_group(cache);
3046 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3047 spin_lock(&fs_info->data_sinfo->lock);
3048 bytes_used = fs_info->data_sinfo->bytes_used;
3049 spin_unlock(&fs_info->data_sinfo->lock);
3052 struct btrfs_trans_handle *trans;
3055 trans = btrfs_join_transaction(fs_info->tree_root);
3057 return PTR_ERR(trans);
3059 ret = btrfs_force_chunk_alloc(trans,
3060 BTRFS_BLOCK_GROUP_DATA);
3061 btrfs_end_transaction(trans);
3065 btrfs_add_raid_kobjects(fs_info);
3073 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3074 struct btrfs_balance_control *bctl)
3076 struct btrfs_root *root = fs_info->tree_root;
3077 struct btrfs_trans_handle *trans;
3078 struct btrfs_balance_item *item;
3079 struct btrfs_disk_balance_args disk_bargs;
3080 struct btrfs_path *path;
3081 struct extent_buffer *leaf;
3082 struct btrfs_key key;
3085 path = btrfs_alloc_path();
3089 trans = btrfs_start_transaction(root, 0);
3090 if (IS_ERR(trans)) {
3091 btrfs_free_path(path);
3092 return PTR_ERR(trans);
3095 key.objectid = BTRFS_BALANCE_OBJECTID;
3096 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3099 ret = btrfs_insert_empty_item(trans, root, path, &key,
3104 leaf = path->nodes[0];
3105 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3107 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3109 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3110 btrfs_set_balance_data(leaf, item, &disk_bargs);
3111 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3112 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3113 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3114 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3116 btrfs_set_balance_flags(leaf, item, bctl->flags);
3118 btrfs_mark_buffer_dirty(leaf);
3120 btrfs_free_path(path);
3121 err = btrfs_commit_transaction(trans);
3127 static int del_balance_item(struct btrfs_fs_info *fs_info)
3129 struct btrfs_root *root = fs_info->tree_root;
3130 struct btrfs_trans_handle *trans;
3131 struct btrfs_path *path;
3132 struct btrfs_key key;
3135 path = btrfs_alloc_path();
3139 trans = btrfs_start_transaction(root, 0);
3140 if (IS_ERR(trans)) {
3141 btrfs_free_path(path);
3142 return PTR_ERR(trans);
3145 key.objectid = BTRFS_BALANCE_OBJECTID;
3146 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3149 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3157 ret = btrfs_del_item(trans, root, path);
3159 btrfs_free_path(path);
3160 err = btrfs_commit_transaction(trans);
3167 * This is a heuristic used to reduce the number of chunks balanced on
3168 * resume after balance was interrupted.
3170 static void update_balance_args(struct btrfs_balance_control *bctl)
3173 * Turn on soft mode for chunk types that were being converted.
3175 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3176 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3177 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3178 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3179 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3180 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3183 * Turn on usage filter if is not already used. The idea is
3184 * that chunks that we have already balanced should be
3185 * reasonably full. Don't do it for chunks that are being
3186 * converted - that will keep us from relocating unconverted
3187 * (albeit full) chunks.
3189 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3190 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3191 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3192 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3193 bctl->data.usage = 90;
3195 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3196 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3197 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3198 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3199 bctl->sys.usage = 90;
3201 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3202 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3203 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3204 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3205 bctl->meta.usage = 90;
3210 * Clear the balance status in fs_info and delete the balance item from disk.
3212 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3214 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3217 BUG_ON(!fs_info->balance_ctl);
3219 spin_lock(&fs_info->balance_lock);
3220 fs_info->balance_ctl = NULL;
3221 spin_unlock(&fs_info->balance_lock);
3224 ret = del_balance_item(fs_info);
3226 btrfs_handle_fs_error(fs_info, ret, NULL);
3230 * Balance filters. Return 1 if chunk should be filtered out
3231 * (should not be balanced).
3233 static int chunk_profiles_filter(u64 chunk_type,
3234 struct btrfs_balance_args *bargs)
3236 chunk_type = chunk_to_extended(chunk_type) &
3237 BTRFS_EXTENDED_PROFILE_MASK;
3239 if (bargs->profiles & chunk_type)
3245 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3246 struct btrfs_balance_args *bargs)
3248 struct btrfs_block_group_cache *cache;
3250 u64 user_thresh_min;
3251 u64 user_thresh_max;
3254 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3255 chunk_used = btrfs_block_group_used(&cache->item);
3257 if (bargs->usage_min == 0)
3258 user_thresh_min = 0;
3260 user_thresh_min = div_factor_fine(cache->key.offset,
3263 if (bargs->usage_max == 0)
3264 user_thresh_max = 1;
3265 else if (bargs->usage_max > 100)
3266 user_thresh_max = cache->key.offset;
3268 user_thresh_max = div_factor_fine(cache->key.offset,
3271 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3274 btrfs_put_block_group(cache);
3278 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3279 u64 chunk_offset, struct btrfs_balance_args *bargs)
3281 struct btrfs_block_group_cache *cache;
3282 u64 chunk_used, user_thresh;
3285 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3286 chunk_used = btrfs_block_group_used(&cache->item);
3288 if (bargs->usage_min == 0)
3290 else if (bargs->usage > 100)
3291 user_thresh = cache->key.offset;
3293 user_thresh = div_factor_fine(cache->key.offset,
3296 if (chunk_used < user_thresh)
3299 btrfs_put_block_group(cache);
3303 static int chunk_devid_filter(struct extent_buffer *leaf,
3304 struct btrfs_chunk *chunk,
3305 struct btrfs_balance_args *bargs)
3307 struct btrfs_stripe *stripe;
3308 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3311 for (i = 0; i < num_stripes; i++) {
3312 stripe = btrfs_stripe_nr(chunk, i);
3313 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3320 /* [pstart, pend) */
3321 static int chunk_drange_filter(struct extent_buffer *leaf,
3322 struct btrfs_chunk *chunk,
3323 struct btrfs_balance_args *bargs)
3325 struct btrfs_stripe *stripe;
3326 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3332 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3335 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3336 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3337 factor = num_stripes / 2;
3338 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3339 factor = num_stripes - 1;
3340 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3341 factor = num_stripes - 2;
3343 factor = num_stripes;
3346 for (i = 0; i < num_stripes; i++) {
3347 stripe = btrfs_stripe_nr(chunk, i);
3348 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3351 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3352 stripe_length = btrfs_chunk_length(leaf, chunk);
3353 stripe_length = div_u64(stripe_length, factor);
3355 if (stripe_offset < bargs->pend &&
3356 stripe_offset + stripe_length > bargs->pstart)
3363 /* [vstart, vend) */
3364 static int chunk_vrange_filter(struct extent_buffer *leaf,
3365 struct btrfs_chunk *chunk,
3367 struct btrfs_balance_args *bargs)
3369 if (chunk_offset < bargs->vend &&
3370 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3371 /* at least part of the chunk is inside this vrange */
3377 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3378 struct btrfs_chunk *chunk,
3379 struct btrfs_balance_args *bargs)
3381 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3383 if (bargs->stripes_min <= num_stripes
3384 && num_stripes <= bargs->stripes_max)
3390 static int chunk_soft_convert_filter(u64 chunk_type,
3391 struct btrfs_balance_args *bargs)
3393 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3396 chunk_type = chunk_to_extended(chunk_type) &
3397 BTRFS_EXTENDED_PROFILE_MASK;
3399 if (bargs->target == chunk_type)
3405 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3406 struct extent_buffer *leaf,
3407 struct btrfs_chunk *chunk, u64 chunk_offset)
3409 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3410 struct btrfs_balance_args *bargs = NULL;
3411 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3414 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3415 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3419 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3420 bargs = &bctl->data;
3421 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3423 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3424 bargs = &bctl->meta;
3426 /* profiles filter */
3427 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3428 chunk_profiles_filter(chunk_type, bargs)) {
3433 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3434 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3436 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3437 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3442 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3443 chunk_devid_filter(leaf, chunk, bargs)) {
3447 /* drange filter, makes sense only with devid filter */
3448 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3449 chunk_drange_filter(leaf, chunk, bargs)) {
3454 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3455 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3459 /* stripes filter */
3460 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3461 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3465 /* soft profile changing mode */
3466 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3467 chunk_soft_convert_filter(chunk_type, bargs)) {
3472 * limited by count, must be the last filter
3474 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3475 if (bargs->limit == 0)
3479 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3481 * Same logic as the 'limit' filter; the minimum cannot be
3482 * determined here because we do not have the global information
3483 * about the count of all chunks that satisfy the filters.
3485 if (bargs->limit_max == 0)
3494 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3496 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3497 struct btrfs_root *chunk_root = fs_info->chunk_root;
3498 struct btrfs_root *dev_root = fs_info->dev_root;
3499 struct list_head *devices;
3500 struct btrfs_device *device;
3504 struct btrfs_chunk *chunk;
3505 struct btrfs_path *path = NULL;
3506 struct btrfs_key key;
3507 struct btrfs_key found_key;
3508 struct btrfs_trans_handle *trans;
3509 struct extent_buffer *leaf;
3512 int enospc_errors = 0;
3513 bool counting = true;
3514 /* The single value limit and min/max limits use the same bytes in the */
3515 u64 limit_data = bctl->data.limit;
3516 u64 limit_meta = bctl->meta.limit;
3517 u64 limit_sys = bctl->sys.limit;
3521 int chunk_reserved = 0;
3523 /* step one make some room on all the devices */
3524 devices = &fs_info->fs_devices->devices;
3525 list_for_each_entry(device, devices, dev_list) {
3526 old_size = btrfs_device_get_total_bytes(device);
3527 size_to_free = div_factor(old_size, 1);
3528 size_to_free = min_t(u64, size_to_free, SZ_1M);
3529 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3530 btrfs_device_get_total_bytes(device) -
3531 btrfs_device_get_bytes_used(device) > size_to_free ||
3532 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3535 ret = btrfs_shrink_device(device, old_size - size_to_free);
3539 /* btrfs_shrink_device never returns ret > 0 */
3544 trans = btrfs_start_transaction(dev_root, 0);
3545 if (IS_ERR(trans)) {
3546 ret = PTR_ERR(trans);
3547 btrfs_info_in_rcu(fs_info,
3548 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3549 rcu_str_deref(device->name), ret,
3550 old_size, old_size - size_to_free);
3554 ret = btrfs_grow_device(trans, device, old_size);
3556 btrfs_end_transaction(trans);
3557 /* btrfs_grow_device never returns ret > 0 */
3559 btrfs_info_in_rcu(fs_info,
3560 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3561 rcu_str_deref(device->name), ret,
3562 old_size, old_size - size_to_free);
3566 btrfs_end_transaction(trans);
3569 /* step two, relocate all the chunks */
3570 path = btrfs_alloc_path();
3576 /* zero out stat counters */
3577 spin_lock(&fs_info->balance_lock);
3578 memset(&bctl->stat, 0, sizeof(bctl->stat));
3579 spin_unlock(&fs_info->balance_lock);
3583 * The single value limit and min/max limits use the same bytes
3586 bctl->data.limit = limit_data;
3587 bctl->meta.limit = limit_meta;
3588 bctl->sys.limit = limit_sys;
3590 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3591 key.offset = (u64)-1;
3592 key.type = BTRFS_CHUNK_ITEM_KEY;
3595 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3596 atomic_read(&fs_info->balance_cancel_req)) {
3601 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3602 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3604 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3609 * this shouldn't happen, it means the last relocate
3613 BUG(); /* FIXME break ? */
3615 ret = btrfs_previous_item(chunk_root, path, 0,
3616 BTRFS_CHUNK_ITEM_KEY);
3618 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3623 leaf = path->nodes[0];
3624 slot = path->slots[0];
3625 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3627 if (found_key.objectid != key.objectid) {
3628 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3632 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3633 chunk_type = btrfs_chunk_type(leaf, chunk);
3636 spin_lock(&fs_info->balance_lock);
3637 bctl->stat.considered++;
3638 spin_unlock(&fs_info->balance_lock);
3641 ret = should_balance_chunk(fs_info, leaf, chunk,
3644 btrfs_release_path(path);
3646 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3651 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3652 spin_lock(&fs_info->balance_lock);
3653 bctl->stat.expected++;
3654 spin_unlock(&fs_info->balance_lock);
3656 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3658 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3660 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3667 * Apply limit_min filter, no need to check if the LIMITS
3668 * filter is used, limit_min is 0 by default
3670 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3671 count_data < bctl->data.limit_min)
3672 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3673 count_meta < bctl->meta.limit_min)
3674 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3675 count_sys < bctl->sys.limit_min)) {
3676 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3680 if (!chunk_reserved) {
3682 * We may be relocating the only data chunk we have,
3683 * which could potentially end up with losing data's
3684 * raid profile, so lets allocate an empty one in
3687 ret = btrfs_may_alloc_data_chunk(fs_info,
3690 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3692 } else if (ret == 1) {
3697 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3698 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3699 if (ret && ret != -ENOSPC)
3701 if (ret == -ENOSPC) {
3704 spin_lock(&fs_info->balance_lock);
3705 bctl->stat.completed++;
3706 spin_unlock(&fs_info->balance_lock);
3709 if (found_key.offset == 0)
3711 key.offset = found_key.offset - 1;
3715 btrfs_release_path(path);
3720 btrfs_free_path(path);
3721 if (enospc_errors) {
3722 btrfs_info(fs_info, "%d enospc errors during balance",
3732 * alloc_profile_is_valid - see if a given profile is valid and reduced
3733 * @flags: profile to validate
3734 * @extended: if true @flags is treated as an extended profile
3736 static int alloc_profile_is_valid(u64 flags, int extended)
3738 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3739 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3741 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3743 /* 1) check that all other bits are zeroed */
3747 /* 2) see if profile is reduced */
3749 return !extended; /* "0" is valid for usual profiles */
3751 /* true if exactly one bit set */
3752 return (flags & (flags - 1)) == 0;
3755 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3757 /* cancel requested || normal exit path */
3758 return atomic_read(&fs_info->balance_cancel_req) ||
3759 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3760 atomic_read(&fs_info->balance_cancel_req) == 0);
3763 /* Non-zero return value signifies invalidity */
3764 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3767 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3768 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3769 (bctl_arg->target & ~allowed)));
3773 * Should be called with balance mutexe held
3775 int btrfs_balance(struct btrfs_fs_info *fs_info,
3776 struct btrfs_balance_control *bctl,
3777 struct btrfs_ioctl_balance_args *bargs)
3779 u64 meta_target, data_target;
3786 if (btrfs_fs_closing(fs_info) ||
3787 atomic_read(&fs_info->balance_pause_req) ||
3788 atomic_read(&fs_info->balance_cancel_req)) {
3793 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3794 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3798 * In case of mixed groups both data and meta should be picked,
3799 * and identical options should be given for both of them.
3801 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3802 if (mixed && (bctl->flags & allowed)) {
3803 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3804 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3805 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3807 "balance: mixed groups data and metadata options must be the same");
3813 num_devices = fs_info->fs_devices->num_devices;
3814 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
3815 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3816 BUG_ON(num_devices < 1);
3819 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
3820 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3821 if (num_devices > 1)
3822 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3823 if (num_devices > 2)
3824 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3825 if (num_devices > 3)
3826 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3827 BTRFS_BLOCK_GROUP_RAID6);
3828 if (validate_convert_profile(&bctl->data, allowed)) {
3829 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
3832 "balance: invalid convert data profile %s",
3833 get_raid_name(index));
3837 if (validate_convert_profile(&bctl->meta, allowed)) {
3838 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
3841 "balance: invalid convert metadata profile %s",
3842 get_raid_name(index));
3846 if (validate_convert_profile(&bctl->sys, allowed)) {
3847 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
3850 "balance: invalid convert system profile %s",
3851 get_raid_name(index));
3856 /* allow to reduce meta or sys integrity only if force set */
3857 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3858 BTRFS_BLOCK_GROUP_RAID10 |
3859 BTRFS_BLOCK_GROUP_RAID5 |
3860 BTRFS_BLOCK_GROUP_RAID6;
3862 seq = read_seqbegin(&fs_info->profiles_lock);
3864 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3865 (fs_info->avail_system_alloc_bits & allowed) &&
3866 !(bctl->sys.target & allowed)) ||
3867 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3868 (fs_info->avail_metadata_alloc_bits & allowed) &&
3869 !(bctl->meta.target & allowed))) {
3870 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3872 "balance: force reducing metadata integrity");
3875 "balance: reduces metadata integrity, use --force if you want this");
3880 } while (read_seqretry(&fs_info->profiles_lock, seq));
3882 /* if we're not converting, the target field is uninitialized */
3883 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3884 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3885 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3886 bctl->data.target : fs_info->avail_data_alloc_bits;
3887 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3888 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3889 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
3890 int data_index = btrfs_bg_flags_to_raid_index(data_target);
3893 "balance: metadata profile %s has lower redundancy than data profile %s",
3894 get_raid_name(meta_index), get_raid_name(data_index));
3897 ret = insert_balance_item(fs_info, bctl);
3898 if (ret && ret != -EEXIST)
3901 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3902 BUG_ON(ret == -EEXIST);
3903 BUG_ON(fs_info->balance_ctl);
3904 spin_lock(&fs_info->balance_lock);
3905 fs_info->balance_ctl = bctl;
3906 spin_unlock(&fs_info->balance_lock);
3908 BUG_ON(ret != -EEXIST);
3909 spin_lock(&fs_info->balance_lock);
3910 update_balance_args(bctl);
3911 spin_unlock(&fs_info->balance_lock);
3914 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
3915 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3916 mutex_unlock(&fs_info->balance_mutex);
3918 ret = __btrfs_balance(fs_info);
3920 mutex_lock(&fs_info->balance_mutex);
3921 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3924 memset(bargs, 0, sizeof(*bargs));
3925 btrfs_update_ioctl_balance_args(fs_info, bargs);
3928 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3929 balance_need_close(fs_info)) {
3930 reset_balance_state(fs_info);
3931 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3934 wake_up(&fs_info->balance_wait_q);
3938 if (bctl->flags & BTRFS_BALANCE_RESUME)
3939 reset_balance_state(fs_info);
3942 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3947 static int balance_kthread(void *data)
3949 struct btrfs_fs_info *fs_info = data;
3952 mutex_lock(&fs_info->balance_mutex);
3953 if (fs_info->balance_ctl) {
3954 btrfs_info(fs_info, "balance: resuming");
3955 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
3957 mutex_unlock(&fs_info->balance_mutex);
3962 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3964 struct task_struct *tsk;
3966 mutex_lock(&fs_info->balance_mutex);
3967 if (!fs_info->balance_ctl) {
3968 mutex_unlock(&fs_info->balance_mutex);
3971 mutex_unlock(&fs_info->balance_mutex);
3973 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
3974 btrfs_info(fs_info, "balance: resume skipped");
3979 * A ro->rw remount sequence should continue with the paused balance
3980 * regardless of who pauses it, system or the user as of now, so set
3983 spin_lock(&fs_info->balance_lock);
3984 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
3985 spin_unlock(&fs_info->balance_lock);
3987 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3988 return PTR_ERR_OR_ZERO(tsk);
3991 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3993 struct btrfs_balance_control *bctl;
3994 struct btrfs_balance_item *item;
3995 struct btrfs_disk_balance_args disk_bargs;
3996 struct btrfs_path *path;
3997 struct extent_buffer *leaf;
3998 struct btrfs_key key;
4001 path = btrfs_alloc_path();
4005 key.objectid = BTRFS_BALANCE_OBJECTID;
4006 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4009 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4012 if (ret > 0) { /* ret = -ENOENT; */
4017 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4023 leaf = path->nodes[0];
4024 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4026 bctl->flags = btrfs_balance_flags(leaf, item);
4027 bctl->flags |= BTRFS_BALANCE_RESUME;
4029 btrfs_balance_data(leaf, item, &disk_bargs);
4030 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4031 btrfs_balance_meta(leaf, item, &disk_bargs);
4032 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4033 btrfs_balance_sys(leaf, item, &disk_bargs);
4034 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4037 * This should never happen, as the paused balance state is recovered
4038 * during mount without any chance of other exclusive ops to collide.
4040 * This gives the exclusive op status to balance and keeps in paused
4041 * state until user intervention (cancel or umount). If the ownership
4042 * cannot be assigned, show a message but do not fail. The balance
4043 * is in a paused state and must have fs_info::balance_ctl properly
4046 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4048 "balance: cannot set exclusive op status, resume manually");
4050 mutex_lock(&fs_info->balance_mutex);
4051 BUG_ON(fs_info->balance_ctl);
4052 spin_lock(&fs_info->balance_lock);
4053 fs_info->balance_ctl = bctl;
4054 spin_unlock(&fs_info->balance_lock);
4055 mutex_unlock(&fs_info->balance_mutex);
4057 btrfs_free_path(path);
4061 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4065 mutex_lock(&fs_info->balance_mutex);
4066 if (!fs_info->balance_ctl) {
4067 mutex_unlock(&fs_info->balance_mutex);
4071 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4072 atomic_inc(&fs_info->balance_pause_req);
4073 mutex_unlock(&fs_info->balance_mutex);
4075 wait_event(fs_info->balance_wait_q,
4076 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4078 mutex_lock(&fs_info->balance_mutex);
4079 /* we are good with balance_ctl ripped off from under us */
4080 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4081 atomic_dec(&fs_info->balance_pause_req);
4086 mutex_unlock(&fs_info->balance_mutex);
4090 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4092 mutex_lock(&fs_info->balance_mutex);
4093 if (!fs_info->balance_ctl) {
4094 mutex_unlock(&fs_info->balance_mutex);
4099 * A paused balance with the item stored on disk can be resumed at
4100 * mount time if the mount is read-write. Otherwise it's still paused
4101 * and we must not allow cancelling as it deletes the item.
4103 if (sb_rdonly(fs_info->sb)) {
4104 mutex_unlock(&fs_info->balance_mutex);
4108 atomic_inc(&fs_info->balance_cancel_req);
4110 * if we are running just wait and return, balance item is
4111 * deleted in btrfs_balance in this case
4113 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4114 mutex_unlock(&fs_info->balance_mutex);
4115 wait_event(fs_info->balance_wait_q,
4116 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4117 mutex_lock(&fs_info->balance_mutex);
4119 mutex_unlock(&fs_info->balance_mutex);
4121 * Lock released to allow other waiters to continue, we'll
4122 * reexamine the status again.
4124 mutex_lock(&fs_info->balance_mutex);
4126 if (fs_info->balance_ctl) {
4127 reset_balance_state(fs_info);
4128 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4129 btrfs_info(fs_info, "balance: canceled");
4133 BUG_ON(fs_info->balance_ctl ||
4134 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4135 atomic_dec(&fs_info->balance_cancel_req);
4136 mutex_unlock(&fs_info->balance_mutex);
4140 static int btrfs_uuid_scan_kthread(void *data)
4142 struct btrfs_fs_info *fs_info = data;
4143 struct btrfs_root *root = fs_info->tree_root;
4144 struct btrfs_key key;
4145 struct btrfs_path *path = NULL;
4147 struct extent_buffer *eb;
4149 struct btrfs_root_item root_item;
4151 struct btrfs_trans_handle *trans = NULL;
4153 path = btrfs_alloc_path();
4160 key.type = BTRFS_ROOT_ITEM_KEY;
4164 ret = btrfs_search_forward(root, &key, path,
4165 BTRFS_OLDEST_GENERATION);
4172 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4173 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4174 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4175 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4178 eb = path->nodes[0];
4179 slot = path->slots[0];
4180 item_size = btrfs_item_size_nr(eb, slot);
4181 if (item_size < sizeof(root_item))
4184 read_extent_buffer(eb, &root_item,
4185 btrfs_item_ptr_offset(eb, slot),
4186 (int)sizeof(root_item));
4187 if (btrfs_root_refs(&root_item) == 0)
4190 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4191 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4195 btrfs_release_path(path);
4197 * 1 - subvol uuid item
4198 * 1 - received_subvol uuid item
4200 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4201 if (IS_ERR(trans)) {
4202 ret = PTR_ERR(trans);
4210 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4211 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4212 BTRFS_UUID_KEY_SUBVOL,
4215 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4221 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4222 ret = btrfs_uuid_tree_add(trans,
4223 root_item.received_uuid,
4224 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4227 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4235 ret = btrfs_end_transaction(trans);
4241 btrfs_release_path(path);
4242 if (key.offset < (u64)-1) {
4244 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4246 key.type = BTRFS_ROOT_ITEM_KEY;
4247 } else if (key.objectid < (u64)-1) {
4249 key.type = BTRFS_ROOT_ITEM_KEY;
4258 btrfs_free_path(path);
4259 if (trans && !IS_ERR(trans))
4260 btrfs_end_transaction(trans);
4262 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4264 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4265 up(&fs_info->uuid_tree_rescan_sem);
4270 * Callback for btrfs_uuid_tree_iterate().
4272 * 0 check succeeded, the entry is not outdated.
4273 * < 0 if an error occurred.
4274 * > 0 if the check failed, which means the caller shall remove the entry.
4276 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4277 u8 *uuid, u8 type, u64 subid)
4279 struct btrfs_key key;
4281 struct btrfs_root *subvol_root;
4283 if (type != BTRFS_UUID_KEY_SUBVOL &&
4284 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4287 key.objectid = subid;
4288 key.type = BTRFS_ROOT_ITEM_KEY;
4289 key.offset = (u64)-1;
4290 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4291 if (IS_ERR(subvol_root)) {
4292 ret = PTR_ERR(subvol_root);
4299 case BTRFS_UUID_KEY_SUBVOL:
4300 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4303 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4304 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4314 static int btrfs_uuid_rescan_kthread(void *data)
4316 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4320 * 1st step is to iterate through the existing UUID tree and
4321 * to delete all entries that contain outdated data.
4322 * 2nd step is to add all missing entries to the UUID tree.
4324 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4326 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4327 up(&fs_info->uuid_tree_rescan_sem);
4330 return btrfs_uuid_scan_kthread(data);
4333 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4335 struct btrfs_trans_handle *trans;
4336 struct btrfs_root *tree_root = fs_info->tree_root;
4337 struct btrfs_root *uuid_root;
4338 struct task_struct *task;
4345 trans = btrfs_start_transaction(tree_root, 2);
4347 return PTR_ERR(trans);
4349 uuid_root = btrfs_create_tree(trans, fs_info,
4350 BTRFS_UUID_TREE_OBJECTID);
4351 if (IS_ERR(uuid_root)) {
4352 ret = PTR_ERR(uuid_root);
4353 btrfs_abort_transaction(trans, ret);
4354 btrfs_end_transaction(trans);
4358 fs_info->uuid_root = uuid_root;
4360 ret = btrfs_commit_transaction(trans);
4364 down(&fs_info->uuid_tree_rescan_sem);
4365 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4367 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4368 btrfs_warn(fs_info, "failed to start uuid_scan task");
4369 up(&fs_info->uuid_tree_rescan_sem);
4370 return PTR_ERR(task);
4376 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4378 struct task_struct *task;
4380 down(&fs_info->uuid_tree_rescan_sem);
4381 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4383 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4384 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4385 up(&fs_info->uuid_tree_rescan_sem);
4386 return PTR_ERR(task);
4393 * shrinking a device means finding all of the device extents past
4394 * the new size, and then following the back refs to the chunks.
4395 * The chunk relocation code actually frees the device extent
4397 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4399 struct btrfs_fs_info *fs_info = device->fs_info;
4400 struct btrfs_root *root = fs_info->dev_root;
4401 struct btrfs_trans_handle *trans;
4402 struct btrfs_dev_extent *dev_extent = NULL;
4403 struct btrfs_path *path;
4409 bool retried = false;
4410 bool checked_pending_chunks = false;
4411 struct extent_buffer *l;
4412 struct btrfs_key key;
4413 struct btrfs_super_block *super_copy = fs_info->super_copy;
4414 u64 old_total = btrfs_super_total_bytes(super_copy);
4415 u64 old_size = btrfs_device_get_total_bytes(device);
4418 new_size = round_down(new_size, fs_info->sectorsize);
4419 diff = round_down(old_size - new_size, fs_info->sectorsize);
4421 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4424 path = btrfs_alloc_path();
4428 path->reada = READA_BACK;
4430 mutex_lock(&fs_info->chunk_mutex);
4432 btrfs_device_set_total_bytes(device, new_size);
4433 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4434 device->fs_devices->total_rw_bytes -= diff;
4435 atomic64_sub(diff, &fs_info->free_chunk_space);
4437 mutex_unlock(&fs_info->chunk_mutex);
4440 key.objectid = device->devid;
4441 key.offset = (u64)-1;
4442 key.type = BTRFS_DEV_EXTENT_KEY;
4445 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4446 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4448 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4452 ret = btrfs_previous_item(root, path, 0, key.type);
4454 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4459 btrfs_release_path(path);
4464 slot = path->slots[0];
4465 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4467 if (key.objectid != device->devid) {
4468 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4469 btrfs_release_path(path);
4473 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4474 length = btrfs_dev_extent_length(l, dev_extent);
4476 if (key.offset + length <= new_size) {
4477 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4478 btrfs_release_path(path);
4482 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4483 btrfs_release_path(path);
4486 * We may be relocating the only data chunk we have,
4487 * which could potentially end up with losing data's
4488 * raid profile, so lets allocate an empty one in
4491 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4493 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4497 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4498 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4499 if (ret && ret != -ENOSPC)
4503 } while (key.offset-- > 0);
4505 if (failed && !retried) {
4509 } else if (failed && retried) {
4514 /* Shrinking succeeded, else we would be at "done". */
4515 trans = btrfs_start_transaction(root, 0);
4516 if (IS_ERR(trans)) {
4517 ret = PTR_ERR(trans);
4521 mutex_lock(&fs_info->chunk_mutex);
4524 * We checked in the above loop all device extents that were already in
4525 * the device tree. However before we have updated the device's
4526 * total_bytes to the new size, we might have had chunk allocations that
4527 * have not complete yet (new block groups attached to transaction
4528 * handles), and therefore their device extents were not yet in the
4529 * device tree and we missed them in the loop above. So if we have any
4530 * pending chunk using a device extent that overlaps the device range
4531 * that we can not use anymore, commit the current transaction and
4532 * repeat the search on the device tree - this way we guarantee we will
4533 * not have chunks using device extents that end beyond 'new_size'.
4535 if (!checked_pending_chunks) {
4536 u64 start = new_size;
4537 u64 len = old_size - new_size;
4539 if (contains_pending_extent(trans->transaction, device,
4541 mutex_unlock(&fs_info->chunk_mutex);
4542 checked_pending_chunks = true;
4545 ret = btrfs_commit_transaction(trans);
4552 btrfs_device_set_disk_total_bytes(device, new_size);
4553 if (list_empty(&device->resized_list))
4554 list_add_tail(&device->resized_list,
4555 &fs_info->fs_devices->resized_devices);
4557 WARN_ON(diff > old_total);
4558 btrfs_set_super_total_bytes(super_copy,
4559 round_down(old_total - diff, fs_info->sectorsize));
4560 mutex_unlock(&fs_info->chunk_mutex);
4562 /* Now btrfs_update_device() will change the on-disk size. */
4563 ret = btrfs_update_device(trans, device);
4564 btrfs_end_transaction(trans);
4566 btrfs_free_path(path);
4568 mutex_lock(&fs_info->chunk_mutex);
4569 btrfs_device_set_total_bytes(device, old_size);
4570 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4571 device->fs_devices->total_rw_bytes += diff;
4572 atomic64_add(diff, &fs_info->free_chunk_space);
4573 mutex_unlock(&fs_info->chunk_mutex);
4578 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4579 struct btrfs_key *key,
4580 struct btrfs_chunk *chunk, int item_size)
4582 struct btrfs_super_block *super_copy = fs_info->super_copy;
4583 struct btrfs_disk_key disk_key;
4587 mutex_lock(&fs_info->chunk_mutex);
4588 array_size = btrfs_super_sys_array_size(super_copy);
4589 if (array_size + item_size + sizeof(disk_key)
4590 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4591 mutex_unlock(&fs_info->chunk_mutex);
4595 ptr = super_copy->sys_chunk_array + array_size;
4596 btrfs_cpu_key_to_disk(&disk_key, key);
4597 memcpy(ptr, &disk_key, sizeof(disk_key));
4598 ptr += sizeof(disk_key);
4599 memcpy(ptr, chunk, item_size);
4600 item_size += sizeof(disk_key);
4601 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4602 mutex_unlock(&fs_info->chunk_mutex);
4608 * sort the devices in descending order by max_avail, total_avail
4610 static int btrfs_cmp_device_info(const void *a, const void *b)
4612 const struct btrfs_device_info *di_a = a;
4613 const struct btrfs_device_info *di_b = b;
4615 if (di_a->max_avail > di_b->max_avail)
4617 if (di_a->max_avail < di_b->max_avail)
4619 if (di_a->total_avail > di_b->total_avail)
4621 if (di_a->total_avail < di_b->total_avail)
4626 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4628 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4631 btrfs_set_fs_incompat(info, RAID56);
4634 #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \
4635 - sizeof(struct btrfs_chunk)) \
4636 / sizeof(struct btrfs_stripe) + 1)
4638 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4639 - 2 * sizeof(struct btrfs_disk_key) \
4640 - 2 * sizeof(struct btrfs_chunk)) \
4641 / sizeof(struct btrfs_stripe) + 1)
4643 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4644 u64 start, u64 type)
4646 struct btrfs_fs_info *info = trans->fs_info;
4647 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4648 struct btrfs_device *device;
4649 struct map_lookup *map = NULL;
4650 struct extent_map_tree *em_tree;
4651 struct extent_map *em;
4652 struct btrfs_device_info *devices_info = NULL;
4654 int num_stripes; /* total number of stripes to allocate */
4655 int data_stripes; /* number of stripes that count for
4657 int sub_stripes; /* sub_stripes info for map */
4658 int dev_stripes; /* stripes per dev */
4659 int devs_max; /* max devs to use */
4660 int devs_min; /* min devs needed */
4661 int devs_increment; /* ndevs has to be a multiple of this */
4662 int ncopies; /* how many copies to data has */
4664 u64 max_stripe_size;
4673 BUG_ON(!alloc_profile_is_valid(type, 0));
4675 if (list_empty(&fs_devices->alloc_list)) {
4676 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4677 btrfs_debug(info, "%s: no writable device", __func__);
4681 index = btrfs_bg_flags_to_raid_index(type);
4683 sub_stripes = btrfs_raid_array[index].sub_stripes;
4684 dev_stripes = btrfs_raid_array[index].dev_stripes;
4685 devs_max = btrfs_raid_array[index].devs_max;
4686 devs_min = btrfs_raid_array[index].devs_min;
4687 devs_increment = btrfs_raid_array[index].devs_increment;
4688 ncopies = btrfs_raid_array[index].ncopies;
4690 if (type & BTRFS_BLOCK_GROUP_DATA) {
4691 max_stripe_size = SZ_1G;
4692 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4694 devs_max = BTRFS_MAX_DEVS(info);
4695 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4696 /* for larger filesystems, use larger metadata chunks */
4697 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4698 max_stripe_size = SZ_1G;
4700 max_stripe_size = SZ_256M;
4701 max_chunk_size = max_stripe_size;
4703 devs_max = BTRFS_MAX_DEVS(info);
4704 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4705 max_stripe_size = SZ_32M;
4706 max_chunk_size = 2 * max_stripe_size;
4708 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4710 btrfs_err(info, "invalid chunk type 0x%llx requested",
4715 /* we don't want a chunk larger than 10% of writeable space */
4716 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4719 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4725 * in the first pass through the devices list, we gather information
4726 * about the available holes on each device.
4729 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4733 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4735 "BTRFS: read-only device in alloc_list\n");
4739 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4740 &device->dev_state) ||
4741 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4744 if (device->total_bytes > device->bytes_used)
4745 total_avail = device->total_bytes - device->bytes_used;
4749 /* If there is no space on this device, skip it. */
4750 if (total_avail == 0)
4753 ret = find_free_dev_extent(trans, device,
4754 max_stripe_size * dev_stripes,
4755 &dev_offset, &max_avail);
4756 if (ret && ret != -ENOSPC)
4760 max_avail = max_stripe_size * dev_stripes;
4762 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4763 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4765 "%s: devid %llu has no free space, have=%llu want=%u",
4766 __func__, device->devid, max_avail,
4767 BTRFS_STRIPE_LEN * dev_stripes);
4771 if (ndevs == fs_devices->rw_devices) {
4772 WARN(1, "%s: found more than %llu devices\n",
4773 __func__, fs_devices->rw_devices);
4776 devices_info[ndevs].dev_offset = dev_offset;
4777 devices_info[ndevs].max_avail = max_avail;
4778 devices_info[ndevs].total_avail = total_avail;
4779 devices_info[ndevs].dev = device;
4784 * now sort the devices by hole size / available space
4786 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4787 btrfs_cmp_device_info, NULL);
4789 /* round down to number of usable stripes */
4790 ndevs = round_down(ndevs, devs_increment);
4792 if (ndevs < devs_min) {
4794 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4796 "%s: not enough devices with free space: have=%d minimum required=%d",
4797 __func__, ndevs, devs_min);
4802 ndevs = min(ndevs, devs_max);
4805 * The primary goal is to maximize the number of stripes, so use as
4806 * many devices as possible, even if the stripes are not maximum sized.
4808 * The DUP profile stores more than one stripe per device, the
4809 * max_avail is the total size so we have to adjust.
4811 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4812 num_stripes = ndevs * dev_stripes;
4815 * this will have to be fixed for RAID1 and RAID10 over
4818 data_stripes = num_stripes / ncopies;
4820 if (type & BTRFS_BLOCK_GROUP_RAID5)
4821 data_stripes = num_stripes - 1;
4823 if (type & BTRFS_BLOCK_GROUP_RAID6)
4824 data_stripes = num_stripes - 2;
4827 * Use the number of data stripes to figure out how big this chunk
4828 * is really going to be in terms of logical address space,
4829 * and compare that answer with the max chunk size
4831 if (stripe_size * data_stripes > max_chunk_size) {
4832 stripe_size = div_u64(max_chunk_size, data_stripes);
4834 /* bump the answer up to a 16MB boundary */
4835 stripe_size = round_up(stripe_size, SZ_16M);
4838 * But don't go higher than the limits we found while searching
4841 stripe_size = min(devices_info[ndevs - 1].max_avail,
4845 /* align to BTRFS_STRIPE_LEN */
4846 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4848 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4853 map->num_stripes = num_stripes;
4855 for (i = 0; i < ndevs; ++i) {
4856 for (j = 0; j < dev_stripes; ++j) {
4857 int s = i * dev_stripes + j;
4858 map->stripes[s].dev = devices_info[i].dev;
4859 map->stripes[s].physical = devices_info[i].dev_offset +
4863 map->stripe_len = BTRFS_STRIPE_LEN;
4864 map->io_align = BTRFS_STRIPE_LEN;
4865 map->io_width = BTRFS_STRIPE_LEN;
4867 map->sub_stripes = sub_stripes;
4869 num_bytes = stripe_size * data_stripes;
4871 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4873 em = alloc_extent_map();
4879 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4880 em->map_lookup = map;
4882 em->len = num_bytes;
4883 em->block_start = 0;
4884 em->block_len = em->len;
4885 em->orig_block_len = stripe_size;
4887 em_tree = &info->mapping_tree.map_tree;
4888 write_lock(&em_tree->lock);
4889 ret = add_extent_mapping(em_tree, em, 0);
4891 write_unlock(&em_tree->lock);
4892 free_extent_map(em);
4896 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4897 refcount_inc(&em->refs);
4898 write_unlock(&em_tree->lock);
4900 ret = btrfs_make_block_group(trans, 0, type, start, num_bytes);
4902 goto error_del_extent;
4904 for (i = 0; i < map->num_stripes; i++) {
4905 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4906 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4909 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4911 free_extent_map(em);
4912 check_raid56_incompat_flag(info, type);
4914 kfree(devices_info);
4918 write_lock(&em_tree->lock);
4919 remove_extent_mapping(em_tree, em);
4920 write_unlock(&em_tree->lock);
4922 /* One for our allocation */
4923 free_extent_map(em);
4924 /* One for the tree reference */
4925 free_extent_map(em);
4926 /* One for the pending_chunks list reference */
4927 free_extent_map(em);
4929 kfree(devices_info);
4933 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4934 struct btrfs_fs_info *fs_info,
4935 u64 chunk_offset, u64 chunk_size)
4937 struct btrfs_root *extent_root = fs_info->extent_root;
4938 struct btrfs_root *chunk_root = fs_info->chunk_root;
4939 struct btrfs_key key;
4940 struct btrfs_device *device;
4941 struct btrfs_chunk *chunk;
4942 struct btrfs_stripe *stripe;
4943 struct extent_map *em;
4944 struct map_lookup *map;
4951 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4955 map = em->map_lookup;
4956 item_size = btrfs_chunk_item_size(map->num_stripes);
4957 stripe_size = em->orig_block_len;
4959 chunk = kzalloc(item_size, GFP_NOFS);
4966 * Take the device list mutex to prevent races with the final phase of
4967 * a device replace operation that replaces the device object associated
4968 * with the map's stripes, because the device object's id can change
4969 * at any time during that final phase of the device replace operation
4970 * (dev-replace.c:btrfs_dev_replace_finishing()).
4972 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4973 for (i = 0; i < map->num_stripes; i++) {
4974 device = map->stripes[i].dev;
4975 dev_offset = map->stripes[i].physical;
4977 ret = btrfs_update_device(trans, device);
4980 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
4981 dev_offset, stripe_size);
4986 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4990 stripe = &chunk->stripe;
4991 for (i = 0; i < map->num_stripes; i++) {
4992 device = map->stripes[i].dev;
4993 dev_offset = map->stripes[i].physical;
4995 btrfs_set_stack_stripe_devid(stripe, device->devid);
4996 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4997 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5000 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5002 btrfs_set_stack_chunk_length(chunk, chunk_size);
5003 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5004 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5005 btrfs_set_stack_chunk_type(chunk, map->type);
5006 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5007 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5008 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5009 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5010 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5012 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5013 key.type = BTRFS_CHUNK_ITEM_KEY;
5014 key.offset = chunk_offset;
5016 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5017 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5019 * TODO: Cleanup of inserted chunk root in case of
5022 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5027 free_extent_map(em);
5032 * Chunk allocation falls into two parts. The first part does works
5033 * that make the new allocated chunk useable, but not do any operation
5034 * that modifies the chunk tree. The second part does the works that
5035 * require modifying the chunk tree. This division is important for the
5036 * bootstrap process of adding storage to a seed btrfs.
5038 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5042 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5043 chunk_offset = find_next_chunk(trans->fs_info);
5044 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5047 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5048 struct btrfs_fs_info *fs_info)
5051 u64 sys_chunk_offset;
5055 chunk_offset = find_next_chunk(fs_info);
5056 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5057 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5061 sys_chunk_offset = find_next_chunk(fs_info);
5062 alloc_profile = btrfs_system_alloc_profile(fs_info);
5063 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5067 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5071 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5072 BTRFS_BLOCK_GROUP_RAID10 |
5073 BTRFS_BLOCK_GROUP_RAID5 |
5074 BTRFS_BLOCK_GROUP_DUP)) {
5076 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5085 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5087 struct extent_map *em;
5088 struct map_lookup *map;
5093 em = get_chunk_map(fs_info, chunk_offset, 1);
5097 map = em->map_lookup;
5098 for (i = 0; i < map->num_stripes; i++) {
5099 if (test_bit(BTRFS_DEV_STATE_MISSING,
5100 &map->stripes[i].dev->dev_state)) {
5104 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5105 &map->stripes[i].dev->dev_state)) {
5112 * If the number of missing devices is larger than max errors,
5113 * we can not write the data into that chunk successfully, so
5116 if (miss_ndevs > btrfs_chunk_max_errors(map))
5119 free_extent_map(em);
5123 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5125 extent_map_tree_init(&tree->map_tree);
5128 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5130 struct extent_map *em;
5133 write_lock(&tree->map_tree.lock);
5134 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5136 remove_extent_mapping(&tree->map_tree, em);
5137 write_unlock(&tree->map_tree.lock);
5141 free_extent_map(em);
5142 /* once for the tree */
5143 free_extent_map(em);
5147 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5149 struct extent_map *em;
5150 struct map_lookup *map;
5153 em = get_chunk_map(fs_info, logical, len);
5156 * We could return errors for these cases, but that could get
5157 * ugly and we'd probably do the same thing which is just not do
5158 * anything else and exit, so return 1 so the callers don't try
5159 * to use other copies.
5163 map = em->map_lookup;
5164 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5165 ret = map->num_stripes;
5166 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5167 ret = map->sub_stripes;
5168 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5170 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5172 * There could be two corrupted data stripes, we need
5173 * to loop retry in order to rebuild the correct data.
5175 * Fail a stripe at a time on every retry except the
5176 * stripe under reconstruction.
5178 ret = map->num_stripes;
5181 free_extent_map(em);
5183 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
5184 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5185 fs_info->dev_replace.tgtdev)
5187 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
5192 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5195 struct extent_map *em;
5196 struct map_lookup *map;
5197 unsigned long len = fs_info->sectorsize;
5199 em = get_chunk_map(fs_info, logical, len);
5201 if (!WARN_ON(IS_ERR(em))) {
5202 map = em->map_lookup;
5203 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5204 len = map->stripe_len * nr_data_stripes(map);
5205 free_extent_map(em);
5210 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5212 struct extent_map *em;
5213 struct map_lookup *map;
5216 em = get_chunk_map(fs_info, logical, len);
5218 if(!WARN_ON(IS_ERR(em))) {
5219 map = em->map_lookup;
5220 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5222 free_extent_map(em);
5227 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5228 struct map_lookup *map, int first,
5229 int dev_replace_is_ongoing)
5233 int preferred_mirror;
5235 struct btrfs_device *srcdev;
5238 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5240 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5241 num_stripes = map->sub_stripes;
5243 num_stripes = map->num_stripes;
5245 preferred_mirror = first + current->pid % num_stripes;
5247 if (dev_replace_is_ongoing &&
5248 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5249 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5250 srcdev = fs_info->dev_replace.srcdev;
5255 * try to avoid the drive that is the source drive for a
5256 * dev-replace procedure, only choose it if no other non-missing
5257 * mirror is available
5259 for (tolerance = 0; tolerance < 2; tolerance++) {
5260 if (map->stripes[preferred_mirror].dev->bdev &&
5261 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5262 return preferred_mirror;
5263 for (i = first; i < first + num_stripes; i++) {
5264 if (map->stripes[i].dev->bdev &&
5265 (tolerance || map->stripes[i].dev != srcdev))
5270 /* we couldn't find one that doesn't fail. Just return something
5271 * and the io error handling code will clean up eventually
5273 return preferred_mirror;
5276 static inline int parity_smaller(u64 a, u64 b)
5281 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5282 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5284 struct btrfs_bio_stripe s;
5291 for (i = 0; i < num_stripes - 1; i++) {
5292 if (parity_smaller(bbio->raid_map[i],
5293 bbio->raid_map[i+1])) {
5294 s = bbio->stripes[i];
5295 l = bbio->raid_map[i];
5296 bbio->stripes[i] = bbio->stripes[i+1];
5297 bbio->raid_map[i] = bbio->raid_map[i+1];
5298 bbio->stripes[i+1] = s;
5299 bbio->raid_map[i+1] = l;
5307 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5309 struct btrfs_bio *bbio = kzalloc(
5310 /* the size of the btrfs_bio */
5311 sizeof(struct btrfs_bio) +
5312 /* plus the variable array for the stripes */
5313 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5314 /* plus the variable array for the tgt dev */
5315 sizeof(int) * (real_stripes) +
5317 * plus the raid_map, which includes both the tgt dev
5320 sizeof(u64) * (total_stripes),
5321 GFP_NOFS|__GFP_NOFAIL);
5323 atomic_set(&bbio->error, 0);
5324 refcount_set(&bbio->refs, 1);
5329 void btrfs_get_bbio(struct btrfs_bio *bbio)
5331 WARN_ON(!refcount_read(&bbio->refs));
5332 refcount_inc(&bbio->refs);
5335 void btrfs_put_bbio(struct btrfs_bio *bbio)
5339 if (refcount_dec_and_test(&bbio->refs))
5343 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5345 * Please note that, discard won't be sent to target device of device
5348 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5349 u64 logical, u64 length,
5350 struct btrfs_bio **bbio_ret)
5352 struct extent_map *em;
5353 struct map_lookup *map;
5354 struct btrfs_bio *bbio;
5358 u64 stripe_end_offset;
5365 u32 sub_stripes = 0;
5366 u64 stripes_per_dev = 0;
5367 u32 remaining_stripes = 0;
5368 u32 last_stripe = 0;
5372 /* discard always return a bbio */
5375 em = get_chunk_map(fs_info, logical, length);
5379 map = em->map_lookup;
5380 /* we don't discard raid56 yet */
5381 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5386 offset = logical - em->start;
5387 length = min_t(u64, em->len - offset, length);
5389 stripe_len = map->stripe_len;
5391 * stripe_nr counts the total number of stripes we have to stride
5392 * to get to this block
5394 stripe_nr = div64_u64(offset, stripe_len);
5396 /* stripe_offset is the offset of this block in its stripe */
5397 stripe_offset = offset - stripe_nr * stripe_len;
5399 stripe_nr_end = round_up(offset + length, map->stripe_len);
5400 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5401 stripe_cnt = stripe_nr_end - stripe_nr;
5402 stripe_end_offset = stripe_nr_end * map->stripe_len -
5405 * after this, stripe_nr is the number of stripes on this
5406 * device we have to walk to find the data, and stripe_index is
5407 * the number of our device in the stripe array
5411 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5412 BTRFS_BLOCK_GROUP_RAID10)) {
5413 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5416 sub_stripes = map->sub_stripes;
5418 factor = map->num_stripes / sub_stripes;
5419 num_stripes = min_t(u64, map->num_stripes,
5420 sub_stripes * stripe_cnt);
5421 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5422 stripe_index *= sub_stripes;
5423 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5424 &remaining_stripes);
5425 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5426 last_stripe *= sub_stripes;
5427 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5428 BTRFS_BLOCK_GROUP_DUP)) {
5429 num_stripes = map->num_stripes;
5431 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5435 bbio = alloc_btrfs_bio(num_stripes, 0);
5441 for (i = 0; i < num_stripes; i++) {
5442 bbio->stripes[i].physical =
5443 map->stripes[stripe_index].physical +
5444 stripe_offset + stripe_nr * map->stripe_len;
5445 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5447 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5448 BTRFS_BLOCK_GROUP_RAID10)) {
5449 bbio->stripes[i].length = stripes_per_dev *
5452 if (i / sub_stripes < remaining_stripes)
5453 bbio->stripes[i].length +=
5457 * Special for the first stripe and
5460 * |-------|...|-------|
5464 if (i < sub_stripes)
5465 bbio->stripes[i].length -=
5468 if (stripe_index >= last_stripe &&
5469 stripe_index <= (last_stripe +
5471 bbio->stripes[i].length -=
5474 if (i == sub_stripes - 1)
5477 bbio->stripes[i].length = length;
5481 if (stripe_index == map->num_stripes) {
5488 bbio->map_type = map->type;
5489 bbio->num_stripes = num_stripes;
5491 free_extent_map(em);
5496 * In dev-replace case, for repair case (that's the only case where the mirror
5497 * is selected explicitly when calling btrfs_map_block), blocks left of the
5498 * left cursor can also be read from the target drive.
5500 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5502 * For READ, it also needs to be supported using the same mirror number.
5504 * If the requested block is not left of the left cursor, EIO is returned. This
5505 * can happen because btrfs_num_copies() returns one more in the dev-replace
5508 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5509 u64 logical, u64 length,
5510 u64 srcdev_devid, int *mirror_num,
5513 struct btrfs_bio *bbio = NULL;
5515 int index_srcdev = 0;
5517 u64 physical_of_found = 0;
5521 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5522 logical, &length, &bbio, 0, 0);
5524 ASSERT(bbio == NULL);
5528 num_stripes = bbio->num_stripes;
5529 if (*mirror_num > num_stripes) {
5531 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5532 * that means that the requested area is not left of the left
5535 btrfs_put_bbio(bbio);
5540 * process the rest of the function using the mirror_num of the source
5541 * drive. Therefore look it up first. At the end, patch the device
5542 * pointer to the one of the target drive.
5544 for (i = 0; i < num_stripes; i++) {
5545 if (bbio->stripes[i].dev->devid != srcdev_devid)
5549 * In case of DUP, in order to keep it simple, only add the
5550 * mirror with the lowest physical address
5553 physical_of_found <= bbio->stripes[i].physical)
5558 physical_of_found = bbio->stripes[i].physical;
5561 btrfs_put_bbio(bbio);
5567 *mirror_num = index_srcdev + 1;
5568 *physical = physical_of_found;
5572 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5573 struct btrfs_bio **bbio_ret,
5574 struct btrfs_dev_replace *dev_replace,
5575 int *num_stripes_ret, int *max_errors_ret)
5577 struct btrfs_bio *bbio = *bbio_ret;
5578 u64 srcdev_devid = dev_replace->srcdev->devid;
5579 int tgtdev_indexes = 0;
5580 int num_stripes = *num_stripes_ret;
5581 int max_errors = *max_errors_ret;
5584 if (op == BTRFS_MAP_WRITE) {
5585 int index_where_to_add;
5588 * duplicate the write operations while the dev replace
5589 * procedure is running. Since the copying of the old disk to
5590 * the new disk takes place at run time while the filesystem is
5591 * mounted writable, the regular write operations to the old
5592 * disk have to be duplicated to go to the new disk as well.
5594 * Note that device->missing is handled by the caller, and that
5595 * the write to the old disk is already set up in the stripes
5598 index_where_to_add = num_stripes;
5599 for (i = 0; i < num_stripes; i++) {
5600 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5601 /* write to new disk, too */
5602 struct btrfs_bio_stripe *new =
5603 bbio->stripes + index_where_to_add;
5604 struct btrfs_bio_stripe *old =
5607 new->physical = old->physical;
5608 new->length = old->length;
5609 new->dev = dev_replace->tgtdev;
5610 bbio->tgtdev_map[i] = index_where_to_add;
5611 index_where_to_add++;
5616 num_stripes = index_where_to_add;
5617 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5618 int index_srcdev = 0;
5620 u64 physical_of_found = 0;
5623 * During the dev-replace procedure, the target drive can also
5624 * be used to read data in case it is needed to repair a corrupt
5625 * block elsewhere. This is possible if the requested area is
5626 * left of the left cursor. In this area, the target drive is a
5627 * full copy of the source drive.
5629 for (i = 0; i < num_stripes; i++) {
5630 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5632 * In case of DUP, in order to keep it simple,
5633 * only add the mirror with the lowest physical
5637 physical_of_found <=
5638 bbio->stripes[i].physical)
5642 physical_of_found = bbio->stripes[i].physical;
5646 struct btrfs_bio_stripe *tgtdev_stripe =
5647 bbio->stripes + num_stripes;
5649 tgtdev_stripe->physical = physical_of_found;
5650 tgtdev_stripe->length =
5651 bbio->stripes[index_srcdev].length;
5652 tgtdev_stripe->dev = dev_replace->tgtdev;
5653 bbio->tgtdev_map[index_srcdev] = num_stripes;
5660 *num_stripes_ret = num_stripes;
5661 *max_errors_ret = max_errors;
5662 bbio->num_tgtdevs = tgtdev_indexes;
5666 static bool need_full_stripe(enum btrfs_map_op op)
5668 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5671 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5672 enum btrfs_map_op op,
5673 u64 logical, u64 *length,
5674 struct btrfs_bio **bbio_ret,
5675 int mirror_num, int need_raid_map)
5677 struct extent_map *em;
5678 struct map_lookup *map;
5688 int tgtdev_indexes = 0;
5689 struct btrfs_bio *bbio = NULL;
5690 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5691 int dev_replace_is_ongoing = 0;
5692 int num_alloc_stripes;
5693 int patch_the_first_stripe_for_dev_replace = 0;
5694 u64 physical_to_patch_in_first_stripe = 0;
5695 u64 raid56_full_stripe_start = (u64)-1;
5697 if (op == BTRFS_MAP_DISCARD)
5698 return __btrfs_map_block_for_discard(fs_info, logical,
5701 em = get_chunk_map(fs_info, logical, *length);
5705 map = em->map_lookup;
5706 offset = logical - em->start;
5708 stripe_len = map->stripe_len;
5711 * stripe_nr counts the total number of stripes we have to stride
5712 * to get to this block
5714 stripe_nr = div64_u64(stripe_nr, stripe_len);
5716 stripe_offset = stripe_nr * stripe_len;
5717 if (offset < stripe_offset) {
5719 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5720 stripe_offset, offset, em->start, logical,
5722 free_extent_map(em);
5726 /* stripe_offset is the offset of this block in its stripe*/
5727 stripe_offset = offset - stripe_offset;
5729 /* if we're here for raid56, we need to know the stripe aligned start */
5730 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5731 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5732 raid56_full_stripe_start = offset;
5734 /* allow a write of a full stripe, but make sure we don't
5735 * allow straddling of stripes
5737 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5739 raid56_full_stripe_start *= full_stripe_len;
5742 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5744 /* For writes to RAID[56], allow a full stripeset across all disks.
5745 For other RAID types and for RAID[56] reads, just allow a single
5746 stripe (on a single disk). */
5747 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5748 (op == BTRFS_MAP_WRITE)) {
5749 max_len = stripe_len * nr_data_stripes(map) -
5750 (offset - raid56_full_stripe_start);
5752 /* we limit the length of each bio to what fits in a stripe */
5753 max_len = stripe_len - stripe_offset;
5755 *length = min_t(u64, em->len - offset, max_len);
5757 *length = em->len - offset;
5760 /* This is for when we're called from btrfs_merge_bio_hook() and all
5761 it cares about is the length */
5765 btrfs_dev_replace_read_lock(dev_replace);
5766 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5767 if (!dev_replace_is_ongoing)
5768 btrfs_dev_replace_read_unlock(dev_replace);
5770 btrfs_dev_replace_set_lock_blocking(dev_replace);
5772 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5773 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5774 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5775 dev_replace->srcdev->devid,
5777 &physical_to_patch_in_first_stripe);
5781 patch_the_first_stripe_for_dev_replace = 1;
5782 } else if (mirror_num > map->num_stripes) {
5788 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5789 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5791 if (!need_full_stripe(op))
5793 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5794 if (need_full_stripe(op))
5795 num_stripes = map->num_stripes;
5796 else if (mirror_num)
5797 stripe_index = mirror_num - 1;
5799 stripe_index = find_live_mirror(fs_info, map, 0,
5800 dev_replace_is_ongoing);
5801 mirror_num = stripe_index + 1;
5804 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5805 if (need_full_stripe(op)) {
5806 num_stripes = map->num_stripes;
5807 } else if (mirror_num) {
5808 stripe_index = mirror_num - 1;
5813 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5814 u32 factor = map->num_stripes / map->sub_stripes;
5816 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5817 stripe_index *= map->sub_stripes;
5819 if (need_full_stripe(op))
5820 num_stripes = map->sub_stripes;
5821 else if (mirror_num)
5822 stripe_index += mirror_num - 1;
5824 int old_stripe_index = stripe_index;
5825 stripe_index = find_live_mirror(fs_info, map,
5827 dev_replace_is_ongoing);
5828 mirror_num = stripe_index - old_stripe_index + 1;
5831 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5832 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5833 /* push stripe_nr back to the start of the full stripe */
5834 stripe_nr = div64_u64(raid56_full_stripe_start,
5835 stripe_len * nr_data_stripes(map));
5837 /* RAID[56] write or recovery. Return all stripes */
5838 num_stripes = map->num_stripes;
5839 max_errors = nr_parity_stripes(map);
5841 *length = map->stripe_len;
5846 * Mirror #0 or #1 means the original data block.
5847 * Mirror #2 is RAID5 parity block.
5848 * Mirror #3 is RAID6 Q block.
5850 stripe_nr = div_u64_rem(stripe_nr,
5851 nr_data_stripes(map), &stripe_index);
5853 stripe_index = nr_data_stripes(map) +
5856 /* We distribute the parity blocks across stripes */
5857 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5859 if (!need_full_stripe(op) && mirror_num <= 1)
5864 * after this, stripe_nr is the number of stripes on this
5865 * device we have to walk to find the data, and stripe_index is
5866 * the number of our device in the stripe array
5868 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5870 mirror_num = stripe_index + 1;
5872 if (stripe_index >= map->num_stripes) {
5874 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5875 stripe_index, map->num_stripes);
5880 num_alloc_stripes = num_stripes;
5881 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5882 if (op == BTRFS_MAP_WRITE)
5883 num_alloc_stripes <<= 1;
5884 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5885 num_alloc_stripes++;
5886 tgtdev_indexes = num_stripes;
5889 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5894 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5895 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5897 /* build raid_map */
5898 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5899 (need_full_stripe(op) || mirror_num > 1)) {
5903 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5904 sizeof(struct btrfs_bio_stripe) *
5906 sizeof(int) * tgtdev_indexes);
5908 /* Work out the disk rotation on this stripe-set */
5909 div_u64_rem(stripe_nr, num_stripes, &rot);
5911 /* Fill in the logical address of each stripe */
5912 tmp = stripe_nr * nr_data_stripes(map);
5913 for (i = 0; i < nr_data_stripes(map); i++)
5914 bbio->raid_map[(i+rot) % num_stripes] =
5915 em->start + (tmp + i) * map->stripe_len;
5917 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5918 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5919 bbio->raid_map[(i+rot+1) % num_stripes] =
5924 for (i = 0; i < num_stripes; i++) {
5925 bbio->stripes[i].physical =
5926 map->stripes[stripe_index].physical +
5928 stripe_nr * map->stripe_len;
5929 bbio->stripes[i].dev =
5930 map->stripes[stripe_index].dev;
5934 if (need_full_stripe(op))
5935 max_errors = btrfs_chunk_max_errors(map);
5938 sort_parity_stripes(bbio, num_stripes);
5940 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5941 need_full_stripe(op)) {
5942 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5947 bbio->map_type = map->type;
5948 bbio->num_stripes = num_stripes;
5949 bbio->max_errors = max_errors;
5950 bbio->mirror_num = mirror_num;
5953 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5954 * mirror_num == num_stripes + 1 && dev_replace target drive is
5955 * available as a mirror
5957 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5958 WARN_ON(num_stripes > 1);
5959 bbio->stripes[0].dev = dev_replace->tgtdev;
5960 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5961 bbio->mirror_num = map->num_stripes + 1;
5964 if (dev_replace_is_ongoing) {
5965 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5966 btrfs_dev_replace_read_unlock(dev_replace);
5968 free_extent_map(em);
5972 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5973 u64 logical, u64 *length,
5974 struct btrfs_bio **bbio_ret, int mirror_num)
5976 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
5980 /* For Scrub/replace */
5981 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5982 u64 logical, u64 *length,
5983 struct btrfs_bio **bbio_ret)
5985 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
5988 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
5989 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
5991 struct extent_map *em;
5992 struct map_lookup *map;
6000 em = get_chunk_map(fs_info, chunk_start, 1);
6004 map = em->map_lookup;
6006 rmap_len = map->stripe_len;
6008 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6009 length = div_u64(length, map->num_stripes / map->sub_stripes);
6010 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6011 length = div_u64(length, map->num_stripes);
6012 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6013 length = div_u64(length, nr_data_stripes(map));
6014 rmap_len = map->stripe_len * nr_data_stripes(map);
6017 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6018 BUG_ON(!buf); /* -ENOMEM */
6020 for (i = 0; i < map->num_stripes; i++) {
6021 if (map->stripes[i].physical > physical ||
6022 map->stripes[i].physical + length <= physical)
6025 stripe_nr = physical - map->stripes[i].physical;
6026 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6028 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6029 stripe_nr = stripe_nr * map->num_stripes + i;
6030 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6031 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6032 stripe_nr = stripe_nr * map->num_stripes + i;
6033 } /* else if RAID[56], multiply by nr_data_stripes().
6034 * Alternatively, just use rmap_len below instead of
6035 * map->stripe_len */
6037 bytenr = chunk_start + stripe_nr * rmap_len;
6038 WARN_ON(nr >= map->num_stripes);
6039 for (j = 0; j < nr; j++) {
6040 if (buf[j] == bytenr)
6044 WARN_ON(nr >= map->num_stripes);
6051 *stripe_len = rmap_len;
6053 free_extent_map(em);
6057 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6059 bio->bi_private = bbio->private;
6060 bio->bi_end_io = bbio->end_io;
6063 btrfs_put_bbio(bbio);
6066 static void btrfs_end_bio(struct bio *bio)
6068 struct btrfs_bio *bbio = bio->bi_private;
6069 int is_orig_bio = 0;
6071 if (bio->bi_status) {
6072 atomic_inc(&bbio->error);
6073 if (bio->bi_status == BLK_STS_IOERR ||
6074 bio->bi_status == BLK_STS_TARGET) {
6075 unsigned int stripe_index =
6076 btrfs_io_bio(bio)->stripe_index;
6077 struct btrfs_device *dev;
6079 BUG_ON(stripe_index >= bbio->num_stripes);
6080 dev = bbio->stripes[stripe_index].dev;
6082 if (bio_op(bio) == REQ_OP_WRITE)
6083 btrfs_dev_stat_inc_and_print(dev,
6084 BTRFS_DEV_STAT_WRITE_ERRS);
6086 btrfs_dev_stat_inc_and_print(dev,
6087 BTRFS_DEV_STAT_READ_ERRS);
6088 if (bio->bi_opf & REQ_PREFLUSH)
6089 btrfs_dev_stat_inc_and_print(dev,
6090 BTRFS_DEV_STAT_FLUSH_ERRS);
6095 if (bio == bbio->orig_bio)
6098 btrfs_bio_counter_dec(bbio->fs_info);
6100 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6103 bio = bbio->orig_bio;
6106 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6107 /* only send an error to the higher layers if it is
6108 * beyond the tolerance of the btrfs bio
6110 if (atomic_read(&bbio->error) > bbio->max_errors) {
6111 bio->bi_status = BLK_STS_IOERR;
6114 * this bio is actually up to date, we didn't
6115 * go over the max number of errors
6117 bio->bi_status = BLK_STS_OK;
6120 btrfs_end_bbio(bbio, bio);
6121 } else if (!is_orig_bio) {
6127 * see run_scheduled_bios for a description of why bios are collected for
6130 * This will add one bio to the pending list for a device and make sure
6131 * the work struct is scheduled.
6133 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6136 struct btrfs_fs_info *fs_info = device->fs_info;
6137 int should_queue = 1;
6138 struct btrfs_pending_bios *pending_bios;
6140 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state) ||
6146 /* don't bother with additional async steps for reads, right now */
6147 if (bio_op(bio) == REQ_OP_READ) {
6148 btrfsic_submit_bio(bio);
6152 WARN_ON(bio->bi_next);
6153 bio->bi_next = NULL;
6155 spin_lock(&device->io_lock);
6156 if (op_is_sync(bio->bi_opf))
6157 pending_bios = &device->pending_sync_bios;
6159 pending_bios = &device->pending_bios;
6161 if (pending_bios->tail)
6162 pending_bios->tail->bi_next = bio;
6164 pending_bios->tail = bio;
6165 if (!pending_bios->head)
6166 pending_bios->head = bio;
6167 if (device->running_pending)
6170 spin_unlock(&device->io_lock);
6173 btrfs_queue_work(fs_info->submit_workers, &device->work);
6176 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6177 u64 physical, int dev_nr, int async)
6179 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6180 struct btrfs_fs_info *fs_info = bbio->fs_info;
6182 bio->bi_private = bbio;
6183 btrfs_io_bio(bio)->stripe_index = dev_nr;
6184 bio->bi_end_io = btrfs_end_bio;
6185 bio->bi_iter.bi_sector = physical >> 9;
6188 struct rcu_string *name;
6191 name = rcu_dereference(dev->name);
6192 btrfs_debug(fs_info,
6193 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6194 bio_op(bio), bio->bi_opf,
6195 (u64)bio->bi_iter.bi_sector,
6196 (u_long)dev->bdev->bd_dev, name->str, dev->devid,
6197 bio->bi_iter.bi_size);
6201 bio_set_dev(bio, dev->bdev);
6203 btrfs_bio_counter_inc_noblocked(fs_info);
6206 btrfs_schedule_bio(dev, bio);
6208 btrfsic_submit_bio(bio);
6211 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6213 atomic_inc(&bbio->error);
6214 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6215 /* Should be the original bio. */
6216 WARN_ON(bio != bbio->orig_bio);
6218 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6219 bio->bi_iter.bi_sector = logical >> 9;
6220 if (atomic_read(&bbio->error) > bbio->max_errors)
6221 bio->bi_status = BLK_STS_IOERR;
6223 bio->bi_status = BLK_STS_OK;
6224 btrfs_end_bbio(bbio, bio);
6228 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6229 int mirror_num, int async_submit)
6231 struct btrfs_device *dev;
6232 struct bio *first_bio = bio;
6233 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6239 struct btrfs_bio *bbio = NULL;
6241 length = bio->bi_iter.bi_size;
6242 map_length = length;
6244 btrfs_bio_counter_inc_blocked(fs_info);
6245 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6246 &map_length, &bbio, mirror_num, 1);
6248 btrfs_bio_counter_dec(fs_info);
6249 return errno_to_blk_status(ret);
6252 total_devs = bbio->num_stripes;
6253 bbio->orig_bio = first_bio;
6254 bbio->private = first_bio->bi_private;
6255 bbio->end_io = first_bio->bi_end_io;
6256 bbio->fs_info = fs_info;
6257 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6259 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6260 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6261 /* In this case, map_length has been set to the length of
6262 a single stripe; not the whole write */
6263 if (bio_op(bio) == REQ_OP_WRITE) {
6264 ret = raid56_parity_write(fs_info, bio, bbio,
6267 ret = raid56_parity_recover(fs_info, bio, bbio,
6268 map_length, mirror_num, 1);
6271 btrfs_bio_counter_dec(fs_info);
6272 return errno_to_blk_status(ret);
6275 if (map_length < length) {
6277 "mapping failed logical %llu bio len %llu len %llu",
6278 logical, length, map_length);
6282 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6283 dev = bbio->stripes[dev_nr].dev;
6284 if (!dev || !dev->bdev ||
6285 (bio_op(first_bio) == REQ_OP_WRITE &&
6286 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6287 bbio_error(bbio, first_bio, logical);
6291 if (dev_nr < total_devs - 1)
6292 bio = btrfs_bio_clone(first_bio);
6296 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6297 dev_nr, async_submit);
6299 btrfs_bio_counter_dec(fs_info);
6303 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6306 struct btrfs_device *device;
6307 struct btrfs_fs_devices *cur_devices;
6309 cur_devices = fs_info->fs_devices;
6310 while (cur_devices) {
6312 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6313 device = find_device(cur_devices, devid, uuid);
6317 cur_devices = cur_devices->seed;
6322 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6323 u64 devid, u8 *dev_uuid)
6325 struct btrfs_device *device;
6327 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6331 list_add(&device->dev_list, &fs_devices->devices);
6332 device->fs_devices = fs_devices;
6333 fs_devices->num_devices++;
6335 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6336 fs_devices->missing_devices++;
6342 * btrfs_alloc_device - allocate struct btrfs_device
6343 * @fs_info: used only for generating a new devid, can be NULL if
6344 * devid is provided (i.e. @devid != NULL).
6345 * @devid: a pointer to devid for this device. If NULL a new devid
6347 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6350 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6351 * on error. Returned struct is not linked onto any lists and must be
6352 * destroyed with btrfs_free_device.
6354 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6358 struct btrfs_device *dev;
6361 if (WARN_ON(!devid && !fs_info))
6362 return ERR_PTR(-EINVAL);
6364 dev = __alloc_device();
6373 ret = find_next_devid(fs_info, &tmp);
6375 btrfs_free_device(dev);
6376 return ERR_PTR(ret);
6382 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6384 generate_random_uuid(dev->uuid);
6386 btrfs_init_work(&dev->work, btrfs_submit_helper,
6387 pending_bios_fn, NULL, NULL);
6392 /* Return -EIO if any error, otherwise return 0. */
6393 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6394 struct extent_buffer *leaf,
6395 struct btrfs_chunk *chunk, u64 logical)
6403 length = btrfs_chunk_length(leaf, chunk);
6404 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6405 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6406 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6407 type = btrfs_chunk_type(leaf, chunk);
6410 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6414 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6415 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6418 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6419 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6420 btrfs_chunk_sector_size(leaf, chunk));
6423 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6424 btrfs_err(fs_info, "invalid chunk length %llu", length);
6427 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6428 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6432 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6434 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6435 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6436 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6437 btrfs_chunk_type(leaf, chunk));
6440 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6441 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6442 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6443 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6444 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6445 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6446 num_stripes != 1)) {
6448 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6449 num_stripes, sub_stripes,
6450 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6457 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6458 u64 devid, u8 *uuid, bool error)
6461 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6464 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6468 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6469 struct extent_buffer *leaf,
6470 struct btrfs_chunk *chunk)
6472 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6473 struct map_lookup *map;
6474 struct extent_map *em;
6478 u8 uuid[BTRFS_UUID_SIZE];
6483 logical = key->offset;
6484 length = btrfs_chunk_length(leaf, chunk);
6485 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6487 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6491 read_lock(&map_tree->map_tree.lock);
6492 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6493 read_unlock(&map_tree->map_tree.lock);
6495 /* already mapped? */
6496 if (em && em->start <= logical && em->start + em->len > logical) {
6497 free_extent_map(em);
6500 free_extent_map(em);
6503 em = alloc_extent_map();
6506 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6508 free_extent_map(em);
6512 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6513 em->map_lookup = map;
6514 em->start = logical;
6517 em->block_start = 0;
6518 em->block_len = em->len;
6520 map->num_stripes = num_stripes;
6521 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6522 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6523 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6524 map->type = btrfs_chunk_type(leaf, chunk);
6525 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6526 for (i = 0; i < num_stripes; i++) {
6527 map->stripes[i].physical =
6528 btrfs_stripe_offset_nr(leaf, chunk, i);
6529 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6530 read_extent_buffer(leaf, uuid, (unsigned long)
6531 btrfs_stripe_dev_uuid_nr(chunk, i),
6533 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6535 if (!map->stripes[i].dev &&
6536 !btrfs_test_opt(fs_info, DEGRADED)) {
6537 free_extent_map(em);
6538 btrfs_report_missing_device(fs_info, devid, uuid, true);
6541 if (!map->stripes[i].dev) {
6542 map->stripes[i].dev =
6543 add_missing_dev(fs_info->fs_devices, devid,
6545 if (IS_ERR(map->stripes[i].dev)) {
6546 free_extent_map(em);
6548 "failed to init missing dev %llu: %ld",
6549 devid, PTR_ERR(map->stripes[i].dev));
6550 return PTR_ERR(map->stripes[i].dev);
6552 btrfs_report_missing_device(fs_info, devid, uuid, false);
6554 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6555 &(map->stripes[i].dev->dev_state));
6559 write_lock(&map_tree->map_tree.lock);
6560 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6561 write_unlock(&map_tree->map_tree.lock);
6562 BUG_ON(ret); /* Tree corruption */
6563 free_extent_map(em);
6568 static void fill_device_from_item(struct extent_buffer *leaf,
6569 struct btrfs_dev_item *dev_item,
6570 struct btrfs_device *device)
6574 device->devid = btrfs_device_id(leaf, dev_item);
6575 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6576 device->total_bytes = device->disk_total_bytes;
6577 device->commit_total_bytes = device->disk_total_bytes;
6578 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6579 device->commit_bytes_used = device->bytes_used;
6580 device->type = btrfs_device_type(leaf, dev_item);
6581 device->io_align = btrfs_device_io_align(leaf, dev_item);
6582 device->io_width = btrfs_device_io_width(leaf, dev_item);
6583 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6584 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6585 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6587 ptr = btrfs_device_uuid(dev_item);
6588 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6591 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6594 struct btrfs_fs_devices *fs_devices;
6597 lockdep_assert_held(&uuid_mutex);
6600 fs_devices = fs_info->fs_devices->seed;
6601 while (fs_devices) {
6602 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6605 fs_devices = fs_devices->seed;
6608 fs_devices = find_fsid(fsid);
6610 if (!btrfs_test_opt(fs_info, DEGRADED))
6611 return ERR_PTR(-ENOENT);
6613 fs_devices = alloc_fs_devices(fsid);
6614 if (IS_ERR(fs_devices))
6617 fs_devices->seeding = 1;
6618 fs_devices->opened = 1;
6622 fs_devices = clone_fs_devices(fs_devices);
6623 if (IS_ERR(fs_devices))
6626 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6628 free_fs_devices(fs_devices);
6629 fs_devices = ERR_PTR(ret);
6633 if (!fs_devices->seeding) {
6634 close_fs_devices(fs_devices);
6635 free_fs_devices(fs_devices);
6636 fs_devices = ERR_PTR(-EINVAL);
6640 fs_devices->seed = fs_info->fs_devices->seed;
6641 fs_info->fs_devices->seed = fs_devices;
6646 static int read_one_dev(struct btrfs_fs_info *fs_info,
6647 struct extent_buffer *leaf,
6648 struct btrfs_dev_item *dev_item)
6650 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6651 struct btrfs_device *device;
6654 u8 fs_uuid[BTRFS_FSID_SIZE];
6655 u8 dev_uuid[BTRFS_UUID_SIZE];
6657 devid = btrfs_device_id(leaf, dev_item);
6658 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6660 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6663 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6664 fs_devices = open_seed_devices(fs_info, fs_uuid);
6665 if (IS_ERR(fs_devices))
6666 return PTR_ERR(fs_devices);
6669 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6671 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6672 btrfs_report_missing_device(fs_info, devid,
6677 device = add_missing_dev(fs_devices, devid, dev_uuid);
6678 if (IS_ERR(device)) {
6680 "failed to add missing dev %llu: %ld",
6681 devid, PTR_ERR(device));
6682 return PTR_ERR(device);
6684 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6686 if (!device->bdev) {
6687 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6688 btrfs_report_missing_device(fs_info,
6689 devid, dev_uuid, true);
6692 btrfs_report_missing_device(fs_info, devid,
6696 if (!device->bdev &&
6697 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6699 * this happens when a device that was properly setup
6700 * in the device info lists suddenly goes bad.
6701 * device->bdev is NULL, and so we have to set
6702 * device->missing to one here
6704 device->fs_devices->missing_devices++;
6705 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6708 /* Move the device to its own fs_devices */
6709 if (device->fs_devices != fs_devices) {
6710 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6711 &device->dev_state));
6713 list_move(&device->dev_list, &fs_devices->devices);
6714 device->fs_devices->num_devices--;
6715 fs_devices->num_devices++;
6717 device->fs_devices->missing_devices--;
6718 fs_devices->missing_devices++;
6720 device->fs_devices = fs_devices;
6724 if (device->fs_devices != fs_info->fs_devices) {
6725 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6726 if (device->generation !=
6727 btrfs_device_generation(leaf, dev_item))
6731 fill_device_from_item(leaf, dev_item, device);
6732 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6733 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6734 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6735 device->fs_devices->total_rw_bytes += device->total_bytes;
6736 atomic64_add(device->total_bytes - device->bytes_used,
6737 &fs_info->free_chunk_space);
6743 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6745 struct btrfs_root *root = fs_info->tree_root;
6746 struct btrfs_super_block *super_copy = fs_info->super_copy;
6747 struct extent_buffer *sb;
6748 struct btrfs_disk_key *disk_key;
6749 struct btrfs_chunk *chunk;
6751 unsigned long sb_array_offset;
6758 struct btrfs_key key;
6760 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6762 * This will create extent buffer of nodesize, superblock size is
6763 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6764 * overallocate but we can keep it as-is, only the first page is used.
6766 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6769 set_extent_buffer_uptodate(sb);
6770 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6772 * The sb extent buffer is artificial and just used to read the system array.
6773 * set_extent_buffer_uptodate() call does not properly mark all it's
6774 * pages up-to-date when the page is larger: extent does not cover the
6775 * whole page and consequently check_page_uptodate does not find all
6776 * the page's extents up-to-date (the hole beyond sb),
6777 * write_extent_buffer then triggers a WARN_ON.
6779 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6780 * but sb spans only this function. Add an explicit SetPageUptodate call
6781 * to silence the warning eg. on PowerPC 64.
6783 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6784 SetPageUptodate(sb->pages[0]);
6786 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6787 array_size = btrfs_super_sys_array_size(super_copy);
6789 array_ptr = super_copy->sys_chunk_array;
6790 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6793 while (cur_offset < array_size) {
6794 disk_key = (struct btrfs_disk_key *)array_ptr;
6795 len = sizeof(*disk_key);
6796 if (cur_offset + len > array_size)
6797 goto out_short_read;
6799 btrfs_disk_key_to_cpu(&key, disk_key);
6802 sb_array_offset += len;
6805 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6806 chunk = (struct btrfs_chunk *)sb_array_offset;
6808 * At least one btrfs_chunk with one stripe must be
6809 * present, exact stripe count check comes afterwards
6811 len = btrfs_chunk_item_size(1);
6812 if (cur_offset + len > array_size)
6813 goto out_short_read;
6815 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6818 "invalid number of stripes %u in sys_array at offset %u",
6819 num_stripes, cur_offset);
6824 type = btrfs_chunk_type(sb, chunk);
6825 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6827 "invalid chunk type %llu in sys_array at offset %u",
6833 len = btrfs_chunk_item_size(num_stripes);
6834 if (cur_offset + len > array_size)
6835 goto out_short_read;
6837 ret = read_one_chunk(fs_info, &key, sb, chunk);
6842 "unexpected item type %u in sys_array at offset %u",
6843 (u32)key.type, cur_offset);
6848 sb_array_offset += len;
6851 clear_extent_buffer_uptodate(sb);
6852 free_extent_buffer_stale(sb);
6856 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6858 clear_extent_buffer_uptodate(sb);
6859 free_extent_buffer_stale(sb);
6864 * Check if all chunks in the fs are OK for read-write degraded mount
6866 * If the @failing_dev is specified, it's accounted as missing.
6868 * Return true if all chunks meet the minimal RW mount requirements.
6869 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6871 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6872 struct btrfs_device *failing_dev)
6874 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6875 struct extent_map *em;
6879 read_lock(&map_tree->map_tree.lock);
6880 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6881 read_unlock(&map_tree->map_tree.lock);
6882 /* No chunk at all? Return false anyway */
6888 struct map_lookup *map;
6893 map = em->map_lookup;
6895 btrfs_get_num_tolerated_disk_barrier_failures(
6897 for (i = 0; i < map->num_stripes; i++) {
6898 struct btrfs_device *dev = map->stripes[i].dev;
6900 if (!dev || !dev->bdev ||
6901 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6902 dev->last_flush_error)
6904 else if (failing_dev && failing_dev == dev)
6907 if (missing > max_tolerated) {
6910 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6911 em->start, missing, max_tolerated);
6912 free_extent_map(em);
6916 next_start = extent_map_end(em);
6917 free_extent_map(em);
6919 read_lock(&map_tree->map_tree.lock);
6920 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6921 (u64)(-1) - next_start);
6922 read_unlock(&map_tree->map_tree.lock);
6928 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6930 struct btrfs_root *root = fs_info->chunk_root;
6931 struct btrfs_path *path;
6932 struct extent_buffer *leaf;
6933 struct btrfs_key key;
6934 struct btrfs_key found_key;
6939 path = btrfs_alloc_path();
6944 * uuid_mutex is needed only if we are mounting a sprout FS
6945 * otherwise we don't need it.
6947 mutex_lock(&uuid_mutex);
6948 mutex_lock(&fs_info->chunk_mutex);
6951 * Read all device items, and then all the chunk items. All
6952 * device items are found before any chunk item (their object id
6953 * is smaller than the lowest possible object id for a chunk
6954 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6956 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6959 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6963 leaf = path->nodes[0];
6964 slot = path->slots[0];
6965 if (slot >= btrfs_header_nritems(leaf)) {
6966 ret = btrfs_next_leaf(root, path);
6973 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6974 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6975 struct btrfs_dev_item *dev_item;
6976 dev_item = btrfs_item_ptr(leaf, slot,
6977 struct btrfs_dev_item);
6978 ret = read_one_dev(fs_info, leaf, dev_item);
6982 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6983 struct btrfs_chunk *chunk;
6984 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6985 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
6993 * After loading chunk tree, we've got all device information,
6994 * do another round of validation checks.
6996 if (total_dev != fs_info->fs_devices->total_devices) {
6998 "super_num_devices %llu mismatch with num_devices %llu found here",
6999 btrfs_super_num_devices(fs_info->super_copy),
7004 if (btrfs_super_total_bytes(fs_info->super_copy) <
7005 fs_info->fs_devices->total_rw_bytes) {
7007 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7008 btrfs_super_total_bytes(fs_info->super_copy),
7009 fs_info->fs_devices->total_rw_bytes);
7015 mutex_unlock(&fs_info->chunk_mutex);
7016 mutex_unlock(&uuid_mutex);
7018 btrfs_free_path(path);
7022 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7024 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7025 struct btrfs_device *device;
7027 while (fs_devices) {
7028 mutex_lock(&fs_devices->device_list_mutex);
7029 list_for_each_entry(device, &fs_devices->devices, dev_list)
7030 device->fs_info = fs_info;
7031 mutex_unlock(&fs_devices->device_list_mutex);
7033 fs_devices = fs_devices->seed;
7037 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7041 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7042 btrfs_dev_stat_reset(dev, i);
7045 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7047 struct btrfs_key key;
7048 struct btrfs_key found_key;
7049 struct btrfs_root *dev_root = fs_info->dev_root;
7050 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7051 struct extent_buffer *eb;
7054 struct btrfs_device *device;
7055 struct btrfs_path *path = NULL;
7058 path = btrfs_alloc_path();
7064 mutex_lock(&fs_devices->device_list_mutex);
7065 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7067 struct btrfs_dev_stats_item *ptr;
7069 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7070 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7071 key.offset = device->devid;
7072 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7074 __btrfs_reset_dev_stats(device);
7075 device->dev_stats_valid = 1;
7076 btrfs_release_path(path);
7079 slot = path->slots[0];
7080 eb = path->nodes[0];
7081 btrfs_item_key_to_cpu(eb, &found_key, slot);
7082 item_size = btrfs_item_size_nr(eb, slot);
7084 ptr = btrfs_item_ptr(eb, slot,
7085 struct btrfs_dev_stats_item);
7087 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7088 if (item_size >= (1 + i) * sizeof(__le64))
7089 btrfs_dev_stat_set(device, i,
7090 btrfs_dev_stats_value(eb, ptr, i));
7092 btrfs_dev_stat_reset(device, i);
7095 device->dev_stats_valid = 1;
7096 btrfs_dev_stat_print_on_load(device);
7097 btrfs_release_path(path);
7099 mutex_unlock(&fs_devices->device_list_mutex);
7102 btrfs_free_path(path);
7103 return ret < 0 ? ret : 0;
7106 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7107 struct btrfs_fs_info *fs_info,
7108 struct btrfs_device *device)
7110 struct btrfs_root *dev_root = fs_info->dev_root;
7111 struct btrfs_path *path;
7112 struct btrfs_key key;
7113 struct extent_buffer *eb;
7114 struct btrfs_dev_stats_item *ptr;
7118 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7119 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7120 key.offset = device->devid;
7122 path = btrfs_alloc_path();
7125 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7127 btrfs_warn_in_rcu(fs_info,
7128 "error %d while searching for dev_stats item for device %s",
7129 ret, rcu_str_deref(device->name));
7134 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7135 /* need to delete old one and insert a new one */
7136 ret = btrfs_del_item(trans, dev_root, path);
7138 btrfs_warn_in_rcu(fs_info,
7139 "delete too small dev_stats item for device %s failed %d",
7140 rcu_str_deref(device->name), ret);
7147 /* need to insert a new item */
7148 btrfs_release_path(path);
7149 ret = btrfs_insert_empty_item(trans, dev_root, path,
7150 &key, sizeof(*ptr));
7152 btrfs_warn_in_rcu(fs_info,
7153 "insert dev_stats item for device %s failed %d",
7154 rcu_str_deref(device->name), ret);
7159 eb = path->nodes[0];
7160 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7161 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7162 btrfs_set_dev_stats_value(eb, ptr, i,
7163 btrfs_dev_stat_read(device, i));
7164 btrfs_mark_buffer_dirty(eb);
7167 btrfs_free_path(path);
7172 * called from commit_transaction. Writes all changed device stats to disk.
7174 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7175 struct btrfs_fs_info *fs_info)
7177 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7178 struct btrfs_device *device;
7182 mutex_lock(&fs_devices->device_list_mutex);
7183 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7184 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7185 if (!device->dev_stats_valid || stats_cnt == 0)
7190 * There is a LOAD-LOAD control dependency between the value of
7191 * dev_stats_ccnt and updating the on-disk values which requires
7192 * reading the in-memory counters. Such control dependencies
7193 * require explicit read memory barriers.
7195 * This memory barriers pairs with smp_mb__before_atomic in
7196 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7197 * barrier implied by atomic_xchg in
7198 * btrfs_dev_stats_read_and_reset
7202 ret = update_dev_stat_item(trans, fs_info, device);
7204 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7206 mutex_unlock(&fs_devices->device_list_mutex);
7211 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7213 btrfs_dev_stat_inc(dev, index);
7214 btrfs_dev_stat_print_on_error(dev);
7217 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7219 if (!dev->dev_stats_valid)
7221 btrfs_err_rl_in_rcu(dev->fs_info,
7222 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7223 rcu_str_deref(dev->name),
7224 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7225 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7226 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7227 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7228 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7231 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7235 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7236 if (btrfs_dev_stat_read(dev, i) != 0)
7238 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7239 return; /* all values == 0, suppress message */
7241 btrfs_info_in_rcu(dev->fs_info,
7242 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7243 rcu_str_deref(dev->name),
7244 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7245 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7246 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7247 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7248 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7251 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7252 struct btrfs_ioctl_get_dev_stats *stats)
7254 struct btrfs_device *dev;
7255 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7258 mutex_lock(&fs_devices->device_list_mutex);
7259 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7260 mutex_unlock(&fs_devices->device_list_mutex);
7263 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7265 } else if (!dev->dev_stats_valid) {
7266 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7268 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7269 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7270 if (stats->nr_items > i)
7272 btrfs_dev_stat_read_and_reset(dev, i);
7274 btrfs_dev_stat_reset(dev, i);
7277 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7278 if (stats->nr_items > i)
7279 stats->values[i] = btrfs_dev_stat_read(dev, i);
7281 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7282 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7286 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7288 struct buffer_head *bh;
7289 struct btrfs_super_block *disk_super;
7295 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7298 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7301 disk_super = (struct btrfs_super_block *)bh->b_data;
7303 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7304 set_buffer_dirty(bh);
7305 sync_dirty_buffer(bh);
7309 /* Notify udev that device has changed */
7310 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7312 /* Update ctime/mtime for device path for libblkid */
7313 update_dev_time(device_path);
7317 * Update the size of all devices, which is used for writing out the
7320 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7322 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7323 struct btrfs_device *curr, *next;
7325 if (list_empty(&fs_devices->resized_devices))
7328 mutex_lock(&fs_devices->device_list_mutex);
7329 mutex_lock(&fs_info->chunk_mutex);
7330 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7332 list_del_init(&curr->resized_list);
7333 curr->commit_total_bytes = curr->disk_total_bytes;
7335 mutex_unlock(&fs_info->chunk_mutex);
7336 mutex_unlock(&fs_devices->device_list_mutex);
7339 /* Must be invoked during the transaction commit */
7340 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7342 struct btrfs_fs_info *fs_info = trans->fs_info;
7343 struct extent_map *em;
7344 struct map_lookup *map;
7345 struct btrfs_device *dev;
7348 if (list_empty(&trans->pending_chunks))
7351 /* In order to kick the device replace finish process */
7352 mutex_lock(&fs_info->chunk_mutex);
7353 list_for_each_entry(em, &trans->pending_chunks, list) {
7354 map = em->map_lookup;
7356 for (i = 0; i < map->num_stripes; i++) {
7357 dev = map->stripes[i].dev;
7358 dev->commit_bytes_used = dev->bytes_used;
7361 mutex_unlock(&fs_info->chunk_mutex);
7364 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7366 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7367 while (fs_devices) {
7368 fs_devices->fs_info = fs_info;
7369 fs_devices = fs_devices->seed;
7373 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7375 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7376 while (fs_devices) {
7377 fs_devices->fs_info = NULL;
7378 fs_devices = fs_devices->seed;