1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
8 #include <linux/slab.h>
9 #include <linux/buffer_head.h>
10 #include <linux/blkdev.h>
11 #include <linux/iocontext.h>
12 #include <linux/capability.h>
13 #include <linux/ratelimit.h>
14 #include <linux/kthread.h>
15 #include <linux/raid/pq.h>
16 #include <linux/semaphore.h>
17 #include <linux/uuid.h>
18 #include <linux/list_sort.h>
19 #include <asm/div64.h>
21 #include "extent_map.h"
23 #include "transaction.h"
24 #include "print-tree.h"
27 #include "async-thread.h"
28 #include "check-integrity.h"
29 #include "rcu-string.h"
31 #include "dev-replace.h"
34 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
35 [BTRFS_RAID_RAID10] = {
38 .devs_max = 0, /* 0 == as many as possible */
40 .tolerated_failures = 1,
44 [BTRFS_RAID_RAID1] = {
49 .tolerated_failures = 1,
58 .tolerated_failures = 0,
62 [BTRFS_RAID_RAID0] = {
67 .tolerated_failures = 0,
71 [BTRFS_RAID_SINGLE] = {
76 .tolerated_failures = 0,
80 [BTRFS_RAID_RAID5] = {
85 .tolerated_failures = 1,
89 [BTRFS_RAID_RAID6] = {
94 .tolerated_failures = 2,
100 const u64 btrfs_raid_group[BTRFS_NR_RAID_TYPES] = {
101 [BTRFS_RAID_RAID10] = BTRFS_BLOCK_GROUP_RAID10,
102 [BTRFS_RAID_RAID1] = BTRFS_BLOCK_GROUP_RAID1,
103 [BTRFS_RAID_DUP] = BTRFS_BLOCK_GROUP_DUP,
104 [BTRFS_RAID_RAID0] = BTRFS_BLOCK_GROUP_RAID0,
105 [BTRFS_RAID_SINGLE] = 0,
106 [BTRFS_RAID_RAID5] = BTRFS_BLOCK_GROUP_RAID5,
107 [BTRFS_RAID_RAID6] = BTRFS_BLOCK_GROUP_RAID6,
111 * Table to convert BTRFS_RAID_* to the error code if minimum number of devices
112 * condition is not met. Zero means there's no corresponding
113 * BTRFS_ERROR_DEV_*_NOT_MET value.
115 const int btrfs_raid_mindev_error[BTRFS_NR_RAID_TYPES] = {
116 [BTRFS_RAID_RAID10] = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
117 [BTRFS_RAID_RAID1] = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
118 [BTRFS_RAID_DUP] = 0,
119 [BTRFS_RAID_RAID0] = 0,
120 [BTRFS_RAID_SINGLE] = 0,
121 [BTRFS_RAID_RAID5] = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
122 [BTRFS_RAID_RAID6] = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
125 static int init_first_rw_device(struct btrfs_trans_handle *trans,
126 struct btrfs_fs_info *fs_info);
127 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
128 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
129 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
130 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
131 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
132 enum btrfs_map_op op,
133 u64 logical, u64 *length,
134 struct btrfs_bio **bbio_ret,
135 int mirror_num, int need_raid_map);
141 * There are several mutexes that protect manipulation of devices and low-level
142 * structures like chunks but not block groups, extents or files
144 * uuid_mutex (global lock)
145 * ------------------------
146 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
147 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
148 * device) or requested by the device= mount option
150 * the mutex can be very coarse and can cover long-running operations
152 * protects: updates to fs_devices counters like missing devices, rw devices,
153 * seeding, structure cloning, openning/closing devices at mount/umount time
155 * global::fs_devs - add, remove, updates to the global list
157 * does not protect: manipulation of the fs_devices::devices list!
159 * btrfs_device::name - renames (write side), read is RCU
161 * fs_devices::device_list_mutex (per-fs, with RCU)
162 * ------------------------------------------------
163 * protects updates to fs_devices::devices, ie. adding and deleting
165 * simple list traversal with read-only actions can be done with RCU protection
167 * may be used to exclude some operations from running concurrently without any
168 * modifications to the list (see write_all_supers)
172 * coarse lock owned by a mounted filesystem; used to exclude some operations
173 * that cannot run in parallel and affect the higher-level properties of the
174 * filesystem like: device add/deleting/resize/replace, or balance
178 * protects balance structures (status, state) and context accessed from
179 * several places (internally, ioctl)
183 * protects chunks, adding or removing during allocation, trim or when a new
184 * device is added/removed
188 * a big lock that is held by the cleaner thread and prevents running subvolume
189 * cleaning together with relocation or delayed iputs
202 * Exclusive operations, BTRFS_FS_EXCL_OP
203 * ======================================
205 * Maintains the exclusivity of the following operations that apply to the
206 * whole filesystem and cannot run in parallel.
211 * - Device replace (*)
214 * The device operations (as above) can be in one of the following states:
220 * Only device operations marked with (*) can go into the Paused state for the
223 * - ioctl (only Balance can be Paused through ioctl)
224 * - filesystem remounted as read-only
225 * - filesystem unmounted and mounted as read-only
226 * - system power-cycle and filesystem mounted as read-only
227 * - filesystem or device errors leading to forced read-only
229 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
230 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
231 * A device operation in Paused or Running state can be canceled or resumed
232 * either by ioctl (Balance only) or when remounted as read-write.
233 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
237 DEFINE_MUTEX(uuid_mutex);
238 static LIST_HEAD(fs_uuids);
239 struct list_head *btrfs_get_fs_uuids(void)
245 * alloc_fs_devices - allocate struct btrfs_fs_devices
246 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
248 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
249 * The returned struct is not linked onto any lists and can be destroyed with
250 * kfree() right away.
252 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
254 struct btrfs_fs_devices *fs_devs;
256 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
258 return ERR_PTR(-ENOMEM);
260 mutex_init(&fs_devs->device_list_mutex);
262 INIT_LIST_HEAD(&fs_devs->devices);
263 INIT_LIST_HEAD(&fs_devs->resized_devices);
264 INIT_LIST_HEAD(&fs_devs->alloc_list);
265 INIT_LIST_HEAD(&fs_devs->fs_list);
267 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
272 static void free_device(struct btrfs_device *device)
274 rcu_string_free(device->name);
275 bio_put(device->flush_bio);
279 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
281 struct btrfs_device *device;
282 WARN_ON(fs_devices->opened);
283 while (!list_empty(&fs_devices->devices)) {
284 device = list_entry(fs_devices->devices.next,
285 struct btrfs_device, dev_list);
286 list_del(&device->dev_list);
292 static void btrfs_kobject_uevent(struct block_device *bdev,
293 enum kobject_action action)
297 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
299 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
301 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
302 &disk_to_dev(bdev->bd_disk)->kobj);
305 void __exit btrfs_cleanup_fs_uuids(void)
307 struct btrfs_fs_devices *fs_devices;
309 while (!list_empty(&fs_uuids)) {
310 fs_devices = list_entry(fs_uuids.next,
311 struct btrfs_fs_devices, fs_list);
312 list_del(&fs_devices->fs_list);
313 free_fs_devices(fs_devices);
318 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
319 * Returned struct is not linked onto any lists and must be destroyed using
322 static struct btrfs_device *__alloc_device(void)
324 struct btrfs_device *dev;
326 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
328 return ERR_PTR(-ENOMEM);
331 * Preallocate a bio that's always going to be used for flushing device
332 * barriers and matches the device lifespan
334 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
335 if (!dev->flush_bio) {
337 return ERR_PTR(-ENOMEM);
340 INIT_LIST_HEAD(&dev->dev_list);
341 INIT_LIST_HEAD(&dev->dev_alloc_list);
342 INIT_LIST_HEAD(&dev->resized_list);
344 spin_lock_init(&dev->io_lock);
346 atomic_set(&dev->reada_in_flight, 0);
347 atomic_set(&dev->dev_stats_ccnt, 0);
348 btrfs_device_data_ordered_init(dev);
349 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
350 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
356 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
359 * If devid and uuid are both specified, the match must be exact, otherwise
360 * only devid is used.
362 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
363 u64 devid, const u8 *uuid)
365 struct btrfs_device *dev;
367 list_for_each_entry(dev, &fs_devices->devices, dev_list) {
368 if (dev->devid == devid &&
369 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
376 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
378 struct btrfs_fs_devices *fs_devices;
380 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
381 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
388 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
389 int flush, struct block_device **bdev,
390 struct buffer_head **bh)
394 *bdev = blkdev_get_by_path(device_path, flags, holder);
397 ret = PTR_ERR(*bdev);
402 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
403 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
405 blkdev_put(*bdev, flags);
408 invalidate_bdev(*bdev);
409 *bh = btrfs_read_dev_super(*bdev);
412 blkdev_put(*bdev, flags);
424 static void requeue_list(struct btrfs_pending_bios *pending_bios,
425 struct bio *head, struct bio *tail)
428 struct bio *old_head;
430 old_head = pending_bios->head;
431 pending_bios->head = head;
432 if (pending_bios->tail)
433 tail->bi_next = old_head;
435 pending_bios->tail = tail;
439 * we try to collect pending bios for a device so we don't get a large
440 * number of procs sending bios down to the same device. This greatly
441 * improves the schedulers ability to collect and merge the bios.
443 * But, it also turns into a long list of bios to process and that is sure
444 * to eventually make the worker thread block. The solution here is to
445 * make some progress and then put this work struct back at the end of
446 * the list if the block device is congested. This way, multiple devices
447 * can make progress from a single worker thread.
449 static noinline void run_scheduled_bios(struct btrfs_device *device)
451 struct btrfs_fs_info *fs_info = device->fs_info;
453 struct backing_dev_info *bdi;
454 struct btrfs_pending_bios *pending_bios;
458 unsigned long num_run;
459 unsigned long batch_run = 0;
460 unsigned long last_waited = 0;
462 int sync_pending = 0;
463 struct blk_plug plug;
466 * this function runs all the bios we've collected for
467 * a particular device. We don't want to wander off to
468 * another device without first sending all of these down.
469 * So, setup a plug here and finish it off before we return
471 blk_start_plug(&plug);
473 bdi = device->bdev->bd_bdi;
476 spin_lock(&device->io_lock);
481 /* take all the bios off the list at once and process them
482 * later on (without the lock held). But, remember the
483 * tail and other pointers so the bios can be properly reinserted
484 * into the list if we hit congestion
486 if (!force_reg && device->pending_sync_bios.head) {
487 pending_bios = &device->pending_sync_bios;
490 pending_bios = &device->pending_bios;
494 pending = pending_bios->head;
495 tail = pending_bios->tail;
496 WARN_ON(pending && !tail);
499 * if pending was null this time around, no bios need processing
500 * at all and we can stop. Otherwise it'll loop back up again
501 * and do an additional check so no bios are missed.
503 * device->running_pending is used to synchronize with the
506 if (device->pending_sync_bios.head == NULL &&
507 device->pending_bios.head == NULL) {
509 device->running_pending = 0;
512 device->running_pending = 1;
515 pending_bios->head = NULL;
516 pending_bios->tail = NULL;
518 spin_unlock(&device->io_lock);
523 /* we want to work on both lists, but do more bios on the
524 * sync list than the regular list
527 pending_bios != &device->pending_sync_bios &&
528 device->pending_sync_bios.head) ||
529 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
530 device->pending_bios.head)) {
531 spin_lock(&device->io_lock);
532 requeue_list(pending_bios, pending, tail);
537 pending = pending->bi_next;
540 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
543 * if we're doing the sync list, record that our
544 * plug has some sync requests on it
546 * If we're doing the regular list and there are
547 * sync requests sitting around, unplug before
550 if (pending_bios == &device->pending_sync_bios) {
552 } else if (sync_pending) {
553 blk_finish_plug(&plug);
554 blk_start_plug(&plug);
558 btrfsic_submit_bio(cur);
565 * we made progress, there is more work to do and the bdi
566 * is now congested. Back off and let other work structs
569 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
570 fs_info->fs_devices->open_devices > 1) {
571 struct io_context *ioc;
573 ioc = current->io_context;
576 * the main goal here is that we don't want to
577 * block if we're going to be able to submit
578 * more requests without blocking.
580 * This code does two great things, it pokes into
581 * the elevator code from a filesystem _and_
582 * it makes assumptions about how batching works.
584 if (ioc && ioc->nr_batch_requests > 0 &&
585 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
587 ioc->last_waited == last_waited)) {
589 * we want to go through our batch of
590 * requests and stop. So, we copy out
591 * the ioc->last_waited time and test
592 * against it before looping
594 last_waited = ioc->last_waited;
598 spin_lock(&device->io_lock);
599 requeue_list(pending_bios, pending, tail);
600 device->running_pending = 1;
602 spin_unlock(&device->io_lock);
603 btrfs_queue_work(fs_info->submit_workers,
613 spin_lock(&device->io_lock);
614 if (device->pending_bios.head || device->pending_sync_bios.head)
616 spin_unlock(&device->io_lock);
619 blk_finish_plug(&plug);
622 static void pending_bios_fn(struct btrfs_work *work)
624 struct btrfs_device *device;
626 device = container_of(work, struct btrfs_device, work);
627 run_scheduled_bios(device);
631 * Search and remove all stale (devices which are not mounted) devices.
632 * When both inputs are NULL, it will search and release all stale devices.
633 * path: Optional. When provided will it release all unmounted devices
634 * matching this path only.
635 * skip_dev: Optional. Will skip this device when searching for the stale
638 static void btrfs_free_stale_devices(const char *path,
639 struct btrfs_device *skip_dev)
641 struct btrfs_fs_devices *fs_devs, *tmp_fs_devs;
642 struct btrfs_device *dev, *tmp_dev;
644 list_for_each_entry_safe(fs_devs, tmp_fs_devs, &fs_uuids, fs_list) {
649 list_for_each_entry_safe(dev, tmp_dev,
650 &fs_devs->devices, dev_list) {
653 if (skip_dev && skip_dev == dev)
655 if (path && !dev->name)
660 not_found = strcmp(rcu_str_deref(dev->name),
666 /* delete the stale device */
667 if (fs_devs->num_devices == 1) {
668 btrfs_sysfs_remove_fsid(fs_devs);
669 list_del(&fs_devs->fs_list);
670 free_fs_devices(fs_devs);
673 fs_devs->num_devices--;
674 list_del(&dev->dev_list);
681 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
682 struct btrfs_device *device, fmode_t flags,
685 struct request_queue *q;
686 struct block_device *bdev;
687 struct buffer_head *bh;
688 struct btrfs_super_block *disk_super;
697 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
702 disk_super = (struct btrfs_super_block *)bh->b_data;
703 devid = btrfs_stack_device_id(&disk_super->dev_item);
704 if (devid != device->devid)
707 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
710 device->generation = btrfs_super_generation(disk_super);
712 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
713 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
714 fs_devices->seeding = 1;
716 if (bdev_read_only(bdev))
717 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
719 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
722 q = bdev_get_queue(bdev);
723 if (!blk_queue_nonrot(q))
724 fs_devices->rotating = 1;
727 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
728 device->mode = flags;
730 fs_devices->open_devices++;
731 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
732 device->devid != BTRFS_DEV_REPLACE_DEVID) {
733 fs_devices->rw_devices++;
734 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
742 blkdev_put(bdev, flags);
748 * Add new device to list of registered devices
751 * device pointer which was just added or updated when successful
752 * error pointer when failed
754 static noinline struct btrfs_device *device_list_add(const char *path,
755 struct btrfs_super_block *disk_super)
757 struct btrfs_device *device;
758 struct btrfs_fs_devices *fs_devices;
759 struct rcu_string *name;
760 u64 found_transid = btrfs_super_generation(disk_super);
761 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
763 fs_devices = find_fsid(disk_super->fsid);
765 fs_devices = alloc_fs_devices(disk_super->fsid);
766 if (IS_ERR(fs_devices))
767 return ERR_CAST(fs_devices);
769 list_add(&fs_devices->fs_list, &fs_uuids);
773 device = find_device(fs_devices, devid,
774 disk_super->dev_item.uuid);
778 if (fs_devices->opened)
779 return ERR_PTR(-EBUSY);
781 device = btrfs_alloc_device(NULL, &devid,
782 disk_super->dev_item.uuid);
783 if (IS_ERR(device)) {
784 /* we can safely leave the fs_devices entry around */
788 name = rcu_string_strdup(path, GFP_NOFS);
791 return ERR_PTR(-ENOMEM);
793 rcu_assign_pointer(device->name, name);
795 mutex_lock(&fs_devices->device_list_mutex);
796 list_add_rcu(&device->dev_list, &fs_devices->devices);
797 fs_devices->num_devices++;
798 mutex_unlock(&fs_devices->device_list_mutex);
800 device->fs_devices = fs_devices;
801 btrfs_free_stale_devices(path, device);
803 if (disk_super->label[0])
804 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
805 disk_super->label, devid, found_transid, path);
807 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
808 disk_super->fsid, devid, found_transid, path);
810 } else if (!device->name || strcmp(device->name->str, path)) {
812 * When FS is already mounted.
813 * 1. If you are here and if the device->name is NULL that
814 * means this device was missing at time of FS mount.
815 * 2. If you are here and if the device->name is different
816 * from 'path' that means either
817 * a. The same device disappeared and reappeared with
819 * b. The missing-disk-which-was-replaced, has
822 * We must allow 1 and 2a above. But 2b would be a spurious
825 * Further in case of 1 and 2a above, the disk at 'path'
826 * would have missed some transaction when it was away and
827 * in case of 2a the stale bdev has to be updated as well.
828 * 2b must not be allowed at all time.
832 * For now, we do allow update to btrfs_fs_device through the
833 * btrfs dev scan cli after FS has been mounted. We're still
834 * tracking a problem where systems fail mount by subvolume id
835 * when we reject replacement on a mounted FS.
837 if (!fs_devices->opened && found_transid < device->generation) {
839 * That is if the FS is _not_ mounted and if you
840 * are here, that means there is more than one
841 * disk with same uuid and devid.We keep the one
842 * with larger generation number or the last-in if
843 * generation are equal.
845 return ERR_PTR(-EEXIST);
848 name = rcu_string_strdup(path, GFP_NOFS);
850 return ERR_PTR(-ENOMEM);
851 rcu_string_free(device->name);
852 rcu_assign_pointer(device->name, name);
853 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
854 fs_devices->missing_devices--;
855 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
860 * Unmount does not free the btrfs_device struct but would zero
861 * generation along with most of the other members. So just update
862 * it back. We need it to pick the disk with largest generation
865 if (!fs_devices->opened)
866 device->generation = found_transid;
868 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
873 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
875 struct btrfs_fs_devices *fs_devices;
876 struct btrfs_device *device;
877 struct btrfs_device *orig_dev;
879 fs_devices = alloc_fs_devices(orig->fsid);
880 if (IS_ERR(fs_devices))
883 mutex_lock(&orig->device_list_mutex);
884 fs_devices->total_devices = orig->total_devices;
886 /* We have held the volume lock, it is safe to get the devices. */
887 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
888 struct rcu_string *name;
890 device = btrfs_alloc_device(NULL, &orig_dev->devid,
896 * This is ok to do without rcu read locked because we hold the
897 * uuid mutex so nothing we touch in here is going to disappear.
899 if (orig_dev->name) {
900 name = rcu_string_strdup(orig_dev->name->str,
906 rcu_assign_pointer(device->name, name);
909 list_add(&device->dev_list, &fs_devices->devices);
910 device->fs_devices = fs_devices;
911 fs_devices->num_devices++;
913 mutex_unlock(&orig->device_list_mutex);
916 mutex_unlock(&orig->device_list_mutex);
917 free_fs_devices(fs_devices);
918 return ERR_PTR(-ENOMEM);
922 * After we have read the system tree and know devids belonging to
923 * this filesystem, remove the device which does not belong there.
925 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
927 struct btrfs_device *device, *next;
928 struct btrfs_device *latest_dev = NULL;
930 mutex_lock(&uuid_mutex);
932 /* This is the initialized path, it is safe to release the devices. */
933 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
934 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
935 &device->dev_state)) {
936 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
937 &device->dev_state) &&
939 device->generation > latest_dev->generation)) {
945 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
947 * In the first step, keep the device which has
948 * the correct fsid and the devid that is used
949 * for the dev_replace procedure.
950 * In the second step, the dev_replace state is
951 * read from the device tree and it is known
952 * whether the procedure is really active or
953 * not, which means whether this device is
954 * used or whether it should be removed.
956 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
957 &device->dev_state)) {
962 blkdev_put(device->bdev, device->mode);
964 fs_devices->open_devices--;
966 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
967 list_del_init(&device->dev_alloc_list);
968 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
969 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
971 fs_devices->rw_devices--;
973 list_del_init(&device->dev_list);
974 fs_devices->num_devices--;
978 if (fs_devices->seed) {
979 fs_devices = fs_devices->seed;
983 fs_devices->latest_bdev = latest_dev->bdev;
985 mutex_unlock(&uuid_mutex);
988 static void free_device_rcu(struct rcu_head *head)
990 struct btrfs_device *device;
992 device = container_of(head, struct btrfs_device, rcu);
996 static void btrfs_close_bdev(struct btrfs_device *device)
1001 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1002 sync_blockdev(device->bdev);
1003 invalidate_bdev(device->bdev);
1006 blkdev_put(device->bdev, device->mode);
1009 static void btrfs_prepare_close_one_device(struct btrfs_device *device)
1011 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1012 struct btrfs_device *new_device;
1013 struct rcu_string *name;
1016 fs_devices->open_devices--;
1018 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1019 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1020 list_del_init(&device->dev_alloc_list);
1021 fs_devices->rw_devices--;
1024 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1025 fs_devices->missing_devices--;
1027 new_device = btrfs_alloc_device(NULL, &device->devid,
1029 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1031 /* Safe because we are under uuid_mutex */
1033 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1034 BUG_ON(!name); /* -ENOMEM */
1035 rcu_assign_pointer(new_device->name, name);
1038 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1039 new_device->fs_devices = device->fs_devices;
1042 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1044 struct btrfs_device *device, *tmp;
1045 struct list_head pending_put;
1047 INIT_LIST_HEAD(&pending_put);
1049 if (--fs_devices->opened > 0)
1052 mutex_lock(&fs_devices->device_list_mutex);
1053 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1054 btrfs_prepare_close_one_device(device);
1055 list_add(&device->dev_list, &pending_put);
1057 mutex_unlock(&fs_devices->device_list_mutex);
1060 * btrfs_show_devname() is using the device_list_mutex,
1061 * sometimes call to blkdev_put() leads vfs calling
1062 * into this func. So do put outside of device_list_mutex,
1065 while (!list_empty(&pending_put)) {
1066 device = list_first_entry(&pending_put,
1067 struct btrfs_device, dev_list);
1068 list_del(&device->dev_list);
1069 btrfs_close_bdev(device);
1070 call_rcu(&device->rcu, free_device_rcu);
1073 WARN_ON(fs_devices->open_devices);
1074 WARN_ON(fs_devices->rw_devices);
1075 fs_devices->opened = 0;
1076 fs_devices->seeding = 0;
1081 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1083 struct btrfs_fs_devices *seed_devices = NULL;
1086 mutex_lock(&uuid_mutex);
1087 ret = close_fs_devices(fs_devices);
1088 if (!fs_devices->opened) {
1089 seed_devices = fs_devices->seed;
1090 fs_devices->seed = NULL;
1092 mutex_unlock(&uuid_mutex);
1094 while (seed_devices) {
1095 fs_devices = seed_devices;
1096 seed_devices = fs_devices->seed;
1097 close_fs_devices(fs_devices);
1098 free_fs_devices(fs_devices);
1103 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1104 fmode_t flags, void *holder)
1106 struct btrfs_device *device;
1107 struct btrfs_device *latest_dev = NULL;
1110 flags |= FMODE_EXCL;
1112 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1113 /* Just open everything we can; ignore failures here */
1114 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1118 device->generation > latest_dev->generation)
1119 latest_dev = device;
1121 if (fs_devices->open_devices == 0) {
1125 fs_devices->opened = 1;
1126 fs_devices->latest_bdev = latest_dev->bdev;
1127 fs_devices->total_rw_bytes = 0;
1132 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1134 struct btrfs_device *dev1, *dev2;
1136 dev1 = list_entry(a, struct btrfs_device, dev_list);
1137 dev2 = list_entry(b, struct btrfs_device, dev_list);
1139 if (dev1->devid < dev2->devid)
1141 else if (dev1->devid > dev2->devid)
1146 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1147 fmode_t flags, void *holder)
1151 mutex_lock(&uuid_mutex);
1152 if (fs_devices->opened) {
1153 fs_devices->opened++;
1156 list_sort(NULL, &fs_devices->devices, devid_cmp);
1157 ret = open_fs_devices(fs_devices, flags, holder);
1159 mutex_unlock(&uuid_mutex);
1163 static void btrfs_release_disk_super(struct page *page)
1169 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1171 struct btrfs_super_block **disk_super)
1176 /* make sure our super fits in the device */
1177 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1180 /* make sure our super fits in the page */
1181 if (sizeof(**disk_super) > PAGE_SIZE)
1184 /* make sure our super doesn't straddle pages on disk */
1185 index = bytenr >> PAGE_SHIFT;
1186 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1189 /* pull in the page with our super */
1190 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1193 if (IS_ERR_OR_NULL(*page))
1198 /* align our pointer to the offset of the super block */
1199 *disk_super = p + (bytenr & ~PAGE_MASK);
1201 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1202 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1203 btrfs_release_disk_super(*page);
1207 if ((*disk_super)->label[0] &&
1208 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1209 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1215 * Look for a btrfs signature on a device. This may be called out of the mount path
1216 * and we are not allowed to call set_blocksize during the scan. The superblock
1217 * is read via pagecache
1219 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1220 struct btrfs_fs_devices **fs_devices_ret)
1222 struct btrfs_super_block *disk_super;
1223 struct btrfs_device *device;
1224 struct block_device *bdev;
1230 * we would like to check all the supers, but that would make
1231 * a btrfs mount succeed after a mkfs from a different FS.
1232 * So, we need to add a special mount option to scan for
1233 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1235 bytenr = btrfs_sb_offset(0);
1236 flags |= FMODE_EXCL;
1237 mutex_lock(&uuid_mutex);
1239 bdev = blkdev_get_by_path(path, flags, holder);
1241 ret = PTR_ERR(bdev);
1245 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1247 goto error_bdev_put;
1250 device = device_list_add(path, disk_super);
1252 ret = PTR_ERR(device);
1254 *fs_devices_ret = device->fs_devices;
1256 btrfs_release_disk_super(page);
1259 blkdev_put(bdev, flags);
1261 mutex_unlock(&uuid_mutex);
1265 /* helper to account the used device space in the range */
1266 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1267 u64 end, u64 *length)
1269 struct btrfs_key key;
1270 struct btrfs_root *root = device->fs_info->dev_root;
1271 struct btrfs_dev_extent *dev_extent;
1272 struct btrfs_path *path;
1276 struct extent_buffer *l;
1280 if (start >= device->total_bytes ||
1281 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1284 path = btrfs_alloc_path();
1287 path->reada = READA_FORWARD;
1289 key.objectid = device->devid;
1291 key.type = BTRFS_DEV_EXTENT_KEY;
1293 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1297 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1304 slot = path->slots[0];
1305 if (slot >= btrfs_header_nritems(l)) {
1306 ret = btrfs_next_leaf(root, path);
1314 btrfs_item_key_to_cpu(l, &key, slot);
1316 if (key.objectid < device->devid)
1319 if (key.objectid > device->devid)
1322 if (key.type != BTRFS_DEV_EXTENT_KEY)
1325 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1326 extent_end = key.offset + btrfs_dev_extent_length(l,
1328 if (key.offset <= start && extent_end > end) {
1329 *length = end - start + 1;
1331 } else if (key.offset <= start && extent_end > start)
1332 *length += extent_end - start;
1333 else if (key.offset > start && extent_end <= end)
1334 *length += extent_end - key.offset;
1335 else if (key.offset > start && key.offset <= end) {
1336 *length += end - key.offset + 1;
1338 } else if (key.offset > end)
1346 btrfs_free_path(path);
1350 static int contains_pending_extent(struct btrfs_transaction *transaction,
1351 struct btrfs_device *device,
1352 u64 *start, u64 len)
1354 struct btrfs_fs_info *fs_info = device->fs_info;
1355 struct extent_map *em;
1356 struct list_head *search_list = &fs_info->pinned_chunks;
1358 u64 physical_start = *start;
1361 search_list = &transaction->pending_chunks;
1363 list_for_each_entry(em, search_list, list) {
1364 struct map_lookup *map;
1367 map = em->map_lookup;
1368 for (i = 0; i < map->num_stripes; i++) {
1371 if (map->stripes[i].dev != device)
1373 if (map->stripes[i].physical >= physical_start + len ||
1374 map->stripes[i].physical + em->orig_block_len <=
1378 * Make sure that while processing the pinned list we do
1379 * not override our *start with a lower value, because
1380 * we can have pinned chunks that fall within this
1381 * device hole and that have lower physical addresses
1382 * than the pending chunks we processed before. If we
1383 * do not take this special care we can end up getting
1384 * 2 pending chunks that start at the same physical
1385 * device offsets because the end offset of a pinned
1386 * chunk can be equal to the start offset of some
1389 end = map->stripes[i].physical + em->orig_block_len;
1396 if (search_list != &fs_info->pinned_chunks) {
1397 search_list = &fs_info->pinned_chunks;
1406 * find_free_dev_extent_start - find free space in the specified device
1407 * @device: the device which we search the free space in
1408 * @num_bytes: the size of the free space that we need
1409 * @search_start: the position from which to begin the search
1410 * @start: store the start of the free space.
1411 * @len: the size of the free space. that we find, or the size
1412 * of the max free space if we don't find suitable free space
1414 * this uses a pretty simple search, the expectation is that it is
1415 * called very infrequently and that a given device has a small number
1418 * @start is used to store the start of the free space if we find. But if we
1419 * don't find suitable free space, it will be used to store the start position
1420 * of the max free space.
1422 * @len is used to store the size of the free space that we find.
1423 * But if we don't find suitable free space, it is used to store the size of
1424 * the max free space.
1426 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1427 struct btrfs_device *device, u64 num_bytes,
1428 u64 search_start, u64 *start, u64 *len)
1430 struct btrfs_fs_info *fs_info = device->fs_info;
1431 struct btrfs_root *root = fs_info->dev_root;
1432 struct btrfs_key key;
1433 struct btrfs_dev_extent *dev_extent;
1434 struct btrfs_path *path;
1439 u64 search_end = device->total_bytes;
1442 struct extent_buffer *l;
1445 * We don't want to overwrite the superblock on the drive nor any area
1446 * used by the boot loader (grub for example), so we make sure to start
1447 * at an offset of at least 1MB.
1449 search_start = max_t(u64, search_start, SZ_1M);
1451 path = btrfs_alloc_path();
1455 max_hole_start = search_start;
1459 if (search_start >= search_end ||
1460 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1465 path->reada = READA_FORWARD;
1466 path->search_commit_root = 1;
1467 path->skip_locking = 1;
1469 key.objectid = device->devid;
1470 key.offset = search_start;
1471 key.type = BTRFS_DEV_EXTENT_KEY;
1473 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1477 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1484 slot = path->slots[0];
1485 if (slot >= btrfs_header_nritems(l)) {
1486 ret = btrfs_next_leaf(root, path);
1494 btrfs_item_key_to_cpu(l, &key, slot);
1496 if (key.objectid < device->devid)
1499 if (key.objectid > device->devid)
1502 if (key.type != BTRFS_DEV_EXTENT_KEY)
1505 if (key.offset > search_start) {
1506 hole_size = key.offset - search_start;
1509 * Have to check before we set max_hole_start, otherwise
1510 * we could end up sending back this offset anyway.
1512 if (contains_pending_extent(transaction, device,
1515 if (key.offset >= search_start) {
1516 hole_size = key.offset - search_start;
1523 if (hole_size > max_hole_size) {
1524 max_hole_start = search_start;
1525 max_hole_size = hole_size;
1529 * If this free space is greater than which we need,
1530 * it must be the max free space that we have found
1531 * until now, so max_hole_start must point to the start
1532 * of this free space and the length of this free space
1533 * is stored in max_hole_size. Thus, we return
1534 * max_hole_start and max_hole_size and go back to the
1537 if (hole_size >= num_bytes) {
1543 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1544 extent_end = key.offset + btrfs_dev_extent_length(l,
1546 if (extent_end > search_start)
1547 search_start = extent_end;
1554 * At this point, search_start should be the end of
1555 * allocated dev extents, and when shrinking the device,
1556 * search_end may be smaller than search_start.
1558 if (search_end > search_start) {
1559 hole_size = search_end - search_start;
1561 if (contains_pending_extent(transaction, device, &search_start,
1563 btrfs_release_path(path);
1567 if (hole_size > max_hole_size) {
1568 max_hole_start = search_start;
1569 max_hole_size = hole_size;
1574 if (max_hole_size < num_bytes)
1580 btrfs_free_path(path);
1581 *start = max_hole_start;
1583 *len = max_hole_size;
1587 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1588 struct btrfs_device *device, u64 num_bytes,
1589 u64 *start, u64 *len)
1591 /* FIXME use last free of some kind */
1592 return find_free_dev_extent_start(trans->transaction, device,
1593 num_bytes, 0, start, len);
1596 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1597 struct btrfs_device *device,
1598 u64 start, u64 *dev_extent_len)
1600 struct btrfs_fs_info *fs_info = device->fs_info;
1601 struct btrfs_root *root = fs_info->dev_root;
1603 struct btrfs_path *path;
1604 struct btrfs_key key;
1605 struct btrfs_key found_key;
1606 struct extent_buffer *leaf = NULL;
1607 struct btrfs_dev_extent *extent = NULL;
1609 path = btrfs_alloc_path();
1613 key.objectid = device->devid;
1615 key.type = BTRFS_DEV_EXTENT_KEY;
1617 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1619 ret = btrfs_previous_item(root, path, key.objectid,
1620 BTRFS_DEV_EXTENT_KEY);
1623 leaf = path->nodes[0];
1624 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1625 extent = btrfs_item_ptr(leaf, path->slots[0],
1626 struct btrfs_dev_extent);
1627 BUG_ON(found_key.offset > start || found_key.offset +
1628 btrfs_dev_extent_length(leaf, extent) < start);
1630 btrfs_release_path(path);
1632 } else if (ret == 0) {
1633 leaf = path->nodes[0];
1634 extent = btrfs_item_ptr(leaf, path->slots[0],
1635 struct btrfs_dev_extent);
1637 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1641 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1643 ret = btrfs_del_item(trans, root, path);
1645 btrfs_handle_fs_error(fs_info, ret,
1646 "Failed to remove dev extent item");
1648 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1651 btrfs_free_path(path);
1655 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1656 struct btrfs_device *device,
1657 u64 chunk_offset, u64 start, u64 num_bytes)
1660 struct btrfs_path *path;
1661 struct btrfs_fs_info *fs_info = device->fs_info;
1662 struct btrfs_root *root = fs_info->dev_root;
1663 struct btrfs_dev_extent *extent;
1664 struct extent_buffer *leaf;
1665 struct btrfs_key key;
1667 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1668 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1669 path = btrfs_alloc_path();
1673 key.objectid = device->devid;
1675 key.type = BTRFS_DEV_EXTENT_KEY;
1676 ret = btrfs_insert_empty_item(trans, root, path, &key,
1681 leaf = path->nodes[0];
1682 extent = btrfs_item_ptr(leaf, path->slots[0],
1683 struct btrfs_dev_extent);
1684 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1685 BTRFS_CHUNK_TREE_OBJECTID);
1686 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1687 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1688 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1690 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1691 btrfs_mark_buffer_dirty(leaf);
1693 btrfs_free_path(path);
1697 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1699 struct extent_map_tree *em_tree;
1700 struct extent_map *em;
1704 em_tree = &fs_info->mapping_tree.map_tree;
1705 read_lock(&em_tree->lock);
1706 n = rb_last(&em_tree->map);
1708 em = rb_entry(n, struct extent_map, rb_node);
1709 ret = em->start + em->len;
1711 read_unlock(&em_tree->lock);
1716 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1720 struct btrfs_key key;
1721 struct btrfs_key found_key;
1722 struct btrfs_path *path;
1724 path = btrfs_alloc_path();
1728 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1729 key.type = BTRFS_DEV_ITEM_KEY;
1730 key.offset = (u64)-1;
1732 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1736 BUG_ON(ret == 0); /* Corruption */
1738 ret = btrfs_previous_item(fs_info->chunk_root, path,
1739 BTRFS_DEV_ITEMS_OBJECTID,
1740 BTRFS_DEV_ITEM_KEY);
1744 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1746 *devid_ret = found_key.offset + 1;
1750 btrfs_free_path(path);
1755 * the device information is stored in the chunk root
1756 * the btrfs_device struct should be fully filled in
1758 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1759 struct btrfs_fs_info *fs_info,
1760 struct btrfs_device *device)
1762 struct btrfs_root *root = fs_info->chunk_root;
1764 struct btrfs_path *path;
1765 struct btrfs_dev_item *dev_item;
1766 struct extent_buffer *leaf;
1767 struct btrfs_key key;
1770 path = btrfs_alloc_path();
1774 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1775 key.type = BTRFS_DEV_ITEM_KEY;
1776 key.offset = device->devid;
1778 ret = btrfs_insert_empty_item(trans, root, path, &key,
1783 leaf = path->nodes[0];
1784 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1786 btrfs_set_device_id(leaf, dev_item, device->devid);
1787 btrfs_set_device_generation(leaf, dev_item, 0);
1788 btrfs_set_device_type(leaf, dev_item, device->type);
1789 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1790 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1791 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1792 btrfs_set_device_total_bytes(leaf, dev_item,
1793 btrfs_device_get_disk_total_bytes(device));
1794 btrfs_set_device_bytes_used(leaf, dev_item,
1795 btrfs_device_get_bytes_used(device));
1796 btrfs_set_device_group(leaf, dev_item, 0);
1797 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1798 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1799 btrfs_set_device_start_offset(leaf, dev_item, 0);
1801 ptr = btrfs_device_uuid(dev_item);
1802 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1803 ptr = btrfs_device_fsid(dev_item);
1804 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1805 btrfs_mark_buffer_dirty(leaf);
1809 btrfs_free_path(path);
1814 * Function to update ctime/mtime for a given device path.
1815 * Mainly used for ctime/mtime based probe like libblkid.
1817 static void update_dev_time(const char *path_name)
1821 filp = filp_open(path_name, O_RDWR, 0);
1824 file_update_time(filp);
1825 filp_close(filp, NULL);
1828 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1829 struct btrfs_device *device)
1831 struct btrfs_root *root = fs_info->chunk_root;
1833 struct btrfs_path *path;
1834 struct btrfs_key key;
1835 struct btrfs_trans_handle *trans;
1837 path = btrfs_alloc_path();
1841 trans = btrfs_start_transaction(root, 0);
1842 if (IS_ERR(trans)) {
1843 btrfs_free_path(path);
1844 return PTR_ERR(trans);
1846 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1847 key.type = BTRFS_DEV_ITEM_KEY;
1848 key.offset = device->devid;
1850 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1854 btrfs_abort_transaction(trans, ret);
1855 btrfs_end_transaction(trans);
1859 ret = btrfs_del_item(trans, root, path);
1861 btrfs_abort_transaction(trans, ret);
1862 btrfs_end_transaction(trans);
1866 btrfs_free_path(path);
1868 ret = btrfs_commit_transaction(trans);
1873 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1874 * filesystem. It's up to the caller to adjust that number regarding eg. device
1877 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1885 seq = read_seqbegin(&fs_info->profiles_lock);
1887 all_avail = fs_info->avail_data_alloc_bits |
1888 fs_info->avail_system_alloc_bits |
1889 fs_info->avail_metadata_alloc_bits;
1890 } while (read_seqretry(&fs_info->profiles_lock, seq));
1892 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1893 if (!(all_avail & btrfs_raid_group[i]))
1896 if (num_devices < btrfs_raid_array[i].devs_min) {
1897 int ret = btrfs_raid_mindev_error[i];
1907 static struct btrfs_device * btrfs_find_next_active_device(
1908 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1910 struct btrfs_device *next_device;
1912 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1913 if (next_device != device &&
1914 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1915 && next_device->bdev)
1923 * Helper function to check if the given device is part of s_bdev / latest_bdev
1924 * and replace it with the provided or the next active device, in the context
1925 * where this function called, there should be always be another device (or
1926 * this_dev) which is active.
1928 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1929 struct btrfs_device *device, struct btrfs_device *this_dev)
1931 struct btrfs_device *next_device;
1934 next_device = this_dev;
1936 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1938 ASSERT(next_device);
1940 if (fs_info->sb->s_bdev &&
1941 (fs_info->sb->s_bdev == device->bdev))
1942 fs_info->sb->s_bdev = next_device->bdev;
1944 if (fs_info->fs_devices->latest_bdev == device->bdev)
1945 fs_info->fs_devices->latest_bdev = next_device->bdev;
1948 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1951 struct btrfs_device *device;
1952 struct btrfs_fs_devices *cur_devices;
1953 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1957 mutex_lock(&fs_info->volume_mutex);
1958 mutex_lock(&uuid_mutex);
1960 num_devices = fs_devices->num_devices;
1961 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1962 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1963 WARN_ON(num_devices < 1);
1966 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1968 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1972 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1977 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1978 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1982 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1983 fs_info->fs_devices->rw_devices == 1) {
1984 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1988 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1989 mutex_lock(&fs_info->chunk_mutex);
1990 list_del_init(&device->dev_alloc_list);
1991 device->fs_devices->rw_devices--;
1992 mutex_unlock(&fs_info->chunk_mutex);
1995 mutex_unlock(&uuid_mutex);
1996 ret = btrfs_shrink_device(device, 0);
1997 mutex_lock(&uuid_mutex);
2002 * TODO: the superblock still includes this device in its num_devices
2003 * counter although write_all_supers() is not locked out. This
2004 * could give a filesystem state which requires a degraded mount.
2006 ret = btrfs_rm_dev_item(fs_info, device);
2010 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2011 btrfs_scrub_cancel_dev(fs_info, device);
2014 * the device list mutex makes sure that we don't change
2015 * the device list while someone else is writing out all
2016 * the device supers. Whoever is writing all supers, should
2017 * lock the device list mutex before getting the number of
2018 * devices in the super block (super_copy). Conversely,
2019 * whoever updates the number of devices in the super block
2020 * (super_copy) should hold the device list mutex.
2023 cur_devices = device->fs_devices;
2024 mutex_lock(&fs_devices->device_list_mutex);
2025 list_del_rcu(&device->dev_list);
2027 device->fs_devices->num_devices--;
2028 device->fs_devices->total_devices--;
2030 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2031 device->fs_devices->missing_devices--;
2033 btrfs_assign_next_active_device(fs_info, device, NULL);
2036 device->fs_devices->open_devices--;
2037 /* remove sysfs entry */
2038 btrfs_sysfs_rm_device_link(fs_devices, device);
2041 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2042 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2043 mutex_unlock(&fs_devices->device_list_mutex);
2046 * at this point, the device is zero sized and detached from
2047 * the devices list. All that's left is to zero out the old
2048 * supers and free the device.
2050 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2051 btrfs_scratch_superblocks(device->bdev, device->name->str);
2053 btrfs_close_bdev(device);
2054 call_rcu(&device->rcu, free_device_rcu);
2056 if (cur_devices->open_devices == 0) {
2057 while (fs_devices) {
2058 if (fs_devices->seed == cur_devices) {
2059 fs_devices->seed = cur_devices->seed;
2062 fs_devices = fs_devices->seed;
2064 cur_devices->seed = NULL;
2065 close_fs_devices(cur_devices);
2066 free_fs_devices(cur_devices);
2070 mutex_unlock(&uuid_mutex);
2071 mutex_unlock(&fs_info->volume_mutex);
2075 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2076 mutex_lock(&fs_info->chunk_mutex);
2077 list_add(&device->dev_alloc_list,
2078 &fs_devices->alloc_list);
2079 device->fs_devices->rw_devices++;
2080 mutex_unlock(&fs_info->chunk_mutex);
2085 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2086 struct btrfs_device *srcdev)
2088 struct btrfs_fs_devices *fs_devices;
2090 lockdep_assert_held(&fs_info->fs_devices->device_list_mutex);
2093 * in case of fs with no seed, srcdev->fs_devices will point
2094 * to fs_devices of fs_info. However when the dev being replaced is
2095 * a seed dev it will point to the seed's local fs_devices. In short
2096 * srcdev will have its correct fs_devices in both the cases.
2098 fs_devices = srcdev->fs_devices;
2100 list_del_rcu(&srcdev->dev_list);
2101 list_del(&srcdev->dev_alloc_list);
2102 fs_devices->num_devices--;
2103 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2104 fs_devices->missing_devices--;
2106 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2107 fs_devices->rw_devices--;
2110 fs_devices->open_devices--;
2113 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2114 struct btrfs_device *srcdev)
2116 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2118 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2119 /* zero out the old super if it is writable */
2120 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2123 btrfs_close_bdev(srcdev);
2124 call_rcu(&srcdev->rcu, free_device_rcu);
2126 /* if this is no devs we rather delete the fs_devices */
2127 if (!fs_devices->num_devices) {
2128 struct btrfs_fs_devices *tmp_fs_devices;
2131 * On a mounted FS, num_devices can't be zero unless it's a
2132 * seed. In case of a seed device being replaced, the replace
2133 * target added to the sprout FS, so there will be no more
2134 * device left under the seed FS.
2136 ASSERT(fs_devices->seeding);
2138 tmp_fs_devices = fs_info->fs_devices;
2139 while (tmp_fs_devices) {
2140 if (tmp_fs_devices->seed == fs_devices) {
2141 tmp_fs_devices->seed = fs_devices->seed;
2144 tmp_fs_devices = tmp_fs_devices->seed;
2146 fs_devices->seed = NULL;
2147 close_fs_devices(fs_devices);
2148 free_fs_devices(fs_devices);
2152 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2153 struct btrfs_device *tgtdev)
2155 mutex_lock(&uuid_mutex);
2157 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2159 btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2162 fs_info->fs_devices->open_devices--;
2164 fs_info->fs_devices->num_devices--;
2166 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2168 list_del_rcu(&tgtdev->dev_list);
2170 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2171 mutex_unlock(&uuid_mutex);
2174 * The update_dev_time() with in btrfs_scratch_superblocks()
2175 * may lead to a call to btrfs_show_devname() which will try
2176 * to hold device_list_mutex. And here this device
2177 * is already out of device list, so we don't have to hold
2178 * the device_list_mutex lock.
2180 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2182 btrfs_close_bdev(tgtdev);
2183 call_rcu(&tgtdev->rcu, free_device_rcu);
2186 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2187 const char *device_path,
2188 struct btrfs_device **device)
2191 struct btrfs_super_block *disk_super;
2194 struct block_device *bdev;
2195 struct buffer_head *bh;
2198 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2199 fs_info->bdev_holder, 0, &bdev, &bh);
2202 disk_super = (struct btrfs_super_block *)bh->b_data;
2203 devid = btrfs_stack_device_id(&disk_super->dev_item);
2204 dev_uuid = disk_super->dev_item.uuid;
2205 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2209 blkdev_put(bdev, FMODE_READ);
2213 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2214 const char *device_path,
2215 struct btrfs_device **device)
2218 if (strcmp(device_path, "missing") == 0) {
2219 struct list_head *devices;
2220 struct btrfs_device *tmp;
2222 devices = &fs_info->fs_devices->devices;
2224 * It is safe to read the devices since the volume_mutex
2225 * is held by the caller.
2227 list_for_each_entry(tmp, devices, dev_list) {
2228 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2229 &tmp->dev_state) && !tmp->bdev) {
2236 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2240 return btrfs_find_device_by_path(fs_info, device_path, device);
2245 * Lookup a device given by device id, or the path if the id is 0.
2247 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2248 const char *devpath,
2249 struct btrfs_device **device)
2255 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2259 if (!devpath || !devpath[0])
2262 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2269 * does all the dirty work required for changing file system's UUID.
2271 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2273 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2274 struct btrfs_fs_devices *old_devices;
2275 struct btrfs_fs_devices *seed_devices;
2276 struct btrfs_super_block *disk_super = fs_info->super_copy;
2277 struct btrfs_device *device;
2280 lockdep_assert_held(&uuid_mutex);
2281 if (!fs_devices->seeding)
2284 seed_devices = alloc_fs_devices(NULL);
2285 if (IS_ERR(seed_devices))
2286 return PTR_ERR(seed_devices);
2288 old_devices = clone_fs_devices(fs_devices);
2289 if (IS_ERR(old_devices)) {
2290 kfree(seed_devices);
2291 return PTR_ERR(old_devices);
2294 list_add(&old_devices->fs_list, &fs_uuids);
2296 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2297 seed_devices->opened = 1;
2298 INIT_LIST_HEAD(&seed_devices->devices);
2299 INIT_LIST_HEAD(&seed_devices->alloc_list);
2300 mutex_init(&seed_devices->device_list_mutex);
2302 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2303 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2305 list_for_each_entry(device, &seed_devices->devices, dev_list)
2306 device->fs_devices = seed_devices;
2308 mutex_lock(&fs_info->chunk_mutex);
2309 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2310 mutex_unlock(&fs_info->chunk_mutex);
2312 fs_devices->seeding = 0;
2313 fs_devices->num_devices = 0;
2314 fs_devices->open_devices = 0;
2315 fs_devices->missing_devices = 0;
2316 fs_devices->rotating = 0;
2317 fs_devices->seed = seed_devices;
2319 generate_random_uuid(fs_devices->fsid);
2320 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2321 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2322 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2324 super_flags = btrfs_super_flags(disk_super) &
2325 ~BTRFS_SUPER_FLAG_SEEDING;
2326 btrfs_set_super_flags(disk_super, super_flags);
2332 * Store the expected generation for seed devices in device items.
2334 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2335 struct btrfs_fs_info *fs_info)
2337 struct btrfs_root *root = fs_info->chunk_root;
2338 struct btrfs_path *path;
2339 struct extent_buffer *leaf;
2340 struct btrfs_dev_item *dev_item;
2341 struct btrfs_device *device;
2342 struct btrfs_key key;
2343 u8 fs_uuid[BTRFS_FSID_SIZE];
2344 u8 dev_uuid[BTRFS_UUID_SIZE];
2348 path = btrfs_alloc_path();
2352 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2354 key.type = BTRFS_DEV_ITEM_KEY;
2357 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2361 leaf = path->nodes[0];
2363 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2364 ret = btrfs_next_leaf(root, path);
2369 leaf = path->nodes[0];
2370 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2371 btrfs_release_path(path);
2375 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2376 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2377 key.type != BTRFS_DEV_ITEM_KEY)
2380 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2381 struct btrfs_dev_item);
2382 devid = btrfs_device_id(leaf, dev_item);
2383 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2385 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2387 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2388 BUG_ON(!device); /* Logic error */
2390 if (device->fs_devices->seeding) {
2391 btrfs_set_device_generation(leaf, dev_item,
2392 device->generation);
2393 btrfs_mark_buffer_dirty(leaf);
2401 btrfs_free_path(path);
2405 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2407 struct btrfs_root *root = fs_info->dev_root;
2408 struct request_queue *q;
2409 struct btrfs_trans_handle *trans;
2410 struct btrfs_device *device;
2411 struct block_device *bdev;
2412 struct list_head *devices;
2413 struct super_block *sb = fs_info->sb;
2414 struct rcu_string *name;
2416 int seeding_dev = 0;
2418 bool unlocked = false;
2420 if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2423 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2424 fs_info->bdev_holder);
2426 return PTR_ERR(bdev);
2428 if (fs_info->fs_devices->seeding) {
2430 down_write(&sb->s_umount);
2431 mutex_lock(&uuid_mutex);
2434 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2436 devices = &fs_info->fs_devices->devices;
2438 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2439 list_for_each_entry(device, devices, dev_list) {
2440 if (device->bdev == bdev) {
2443 &fs_info->fs_devices->device_list_mutex);
2447 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2449 device = btrfs_alloc_device(fs_info, NULL, NULL);
2450 if (IS_ERR(device)) {
2451 /* we can safely leave the fs_devices entry around */
2452 ret = PTR_ERR(device);
2456 name = rcu_string_strdup(device_path, GFP_KERNEL);
2459 goto error_free_device;
2461 rcu_assign_pointer(device->name, name);
2463 trans = btrfs_start_transaction(root, 0);
2464 if (IS_ERR(trans)) {
2465 ret = PTR_ERR(trans);
2466 goto error_free_device;
2469 q = bdev_get_queue(bdev);
2470 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2471 device->generation = trans->transid;
2472 device->io_width = fs_info->sectorsize;
2473 device->io_align = fs_info->sectorsize;
2474 device->sector_size = fs_info->sectorsize;
2475 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2476 fs_info->sectorsize);
2477 device->disk_total_bytes = device->total_bytes;
2478 device->commit_total_bytes = device->total_bytes;
2479 device->fs_info = fs_info;
2480 device->bdev = bdev;
2481 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2482 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2483 device->mode = FMODE_EXCL;
2484 device->dev_stats_valid = 1;
2485 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2488 sb->s_flags &= ~SB_RDONLY;
2489 ret = btrfs_prepare_sprout(fs_info);
2491 btrfs_abort_transaction(trans, ret);
2496 device->fs_devices = fs_info->fs_devices;
2498 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2499 mutex_lock(&fs_info->chunk_mutex);
2500 list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2501 list_add(&device->dev_alloc_list,
2502 &fs_info->fs_devices->alloc_list);
2503 fs_info->fs_devices->num_devices++;
2504 fs_info->fs_devices->open_devices++;
2505 fs_info->fs_devices->rw_devices++;
2506 fs_info->fs_devices->total_devices++;
2507 fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2509 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2511 if (!blk_queue_nonrot(q))
2512 fs_info->fs_devices->rotating = 1;
2514 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2515 btrfs_set_super_total_bytes(fs_info->super_copy,
2516 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2518 tmp = btrfs_super_num_devices(fs_info->super_copy);
2519 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2521 /* add sysfs device entry */
2522 btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2525 * we've got more storage, clear any full flags on the space
2528 btrfs_clear_space_info_full(fs_info);
2530 mutex_unlock(&fs_info->chunk_mutex);
2531 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2534 mutex_lock(&fs_info->chunk_mutex);
2535 ret = init_first_rw_device(trans, fs_info);
2536 mutex_unlock(&fs_info->chunk_mutex);
2538 btrfs_abort_transaction(trans, ret);
2543 ret = btrfs_add_dev_item(trans, fs_info, device);
2545 btrfs_abort_transaction(trans, ret);
2550 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2552 ret = btrfs_finish_sprout(trans, fs_info);
2554 btrfs_abort_transaction(trans, ret);
2558 /* Sprouting would change fsid of the mounted root,
2559 * so rename the fsid on the sysfs
2561 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2563 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2565 "sysfs: failed to create fsid for sprout");
2568 ret = btrfs_commit_transaction(trans);
2571 mutex_unlock(&uuid_mutex);
2572 up_write(&sb->s_umount);
2575 if (ret) /* transaction commit */
2578 ret = btrfs_relocate_sys_chunks(fs_info);
2580 btrfs_handle_fs_error(fs_info, ret,
2581 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2582 trans = btrfs_attach_transaction(root);
2583 if (IS_ERR(trans)) {
2584 if (PTR_ERR(trans) == -ENOENT)
2586 ret = PTR_ERR(trans);
2590 ret = btrfs_commit_transaction(trans);
2593 /* Update ctime/mtime for libblkid */
2594 update_dev_time(device_path);
2598 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2601 sb->s_flags |= SB_RDONLY;
2603 btrfs_end_transaction(trans);
2605 free_device(device);
2607 blkdev_put(bdev, FMODE_EXCL);
2608 if (seeding_dev && !unlocked) {
2609 mutex_unlock(&uuid_mutex);
2610 up_write(&sb->s_umount);
2616 * Initialize a new device for device replace target from a given source dev
2619 * Return 0 and new device in @device_out, otherwise return < 0
2621 int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2622 const char *device_path,
2623 struct btrfs_device *srcdev,
2624 struct btrfs_device **device_out)
2626 struct btrfs_device *device;
2627 struct block_device *bdev;
2628 struct list_head *devices;
2629 struct rcu_string *name;
2630 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2634 if (fs_info->fs_devices->seeding) {
2635 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2639 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2640 fs_info->bdev_holder);
2642 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2643 return PTR_ERR(bdev);
2646 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2648 devices = &fs_info->fs_devices->devices;
2649 list_for_each_entry(device, devices, dev_list) {
2650 if (device->bdev == bdev) {
2652 "target device is in the filesystem!");
2659 if (i_size_read(bdev->bd_inode) <
2660 btrfs_device_get_total_bytes(srcdev)) {
2662 "target device is smaller than source device!");
2668 device = btrfs_alloc_device(NULL, &devid, NULL);
2669 if (IS_ERR(device)) {
2670 ret = PTR_ERR(device);
2674 name = rcu_string_strdup(device_path, GFP_KERNEL);
2676 free_device(device);
2680 rcu_assign_pointer(device->name, name);
2682 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2683 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2684 device->generation = 0;
2685 device->io_width = fs_info->sectorsize;
2686 device->io_align = fs_info->sectorsize;
2687 device->sector_size = fs_info->sectorsize;
2688 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2689 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2690 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2691 device->commit_total_bytes = srcdev->commit_total_bytes;
2692 device->commit_bytes_used = device->bytes_used;
2693 device->fs_info = fs_info;
2694 device->bdev = bdev;
2695 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2696 set_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2697 device->mode = FMODE_EXCL;
2698 device->dev_stats_valid = 1;
2699 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2700 device->fs_devices = fs_info->fs_devices;
2701 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2702 fs_info->fs_devices->num_devices++;
2703 fs_info->fs_devices->open_devices++;
2704 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2706 *device_out = device;
2710 blkdev_put(bdev, FMODE_EXCL);
2714 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2715 struct btrfs_device *device)
2718 struct btrfs_path *path;
2719 struct btrfs_root *root = device->fs_info->chunk_root;
2720 struct btrfs_dev_item *dev_item;
2721 struct extent_buffer *leaf;
2722 struct btrfs_key key;
2724 path = btrfs_alloc_path();
2728 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2729 key.type = BTRFS_DEV_ITEM_KEY;
2730 key.offset = device->devid;
2732 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2741 leaf = path->nodes[0];
2742 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2744 btrfs_set_device_id(leaf, dev_item, device->devid);
2745 btrfs_set_device_type(leaf, dev_item, device->type);
2746 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2747 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2748 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2749 btrfs_set_device_total_bytes(leaf, dev_item,
2750 btrfs_device_get_disk_total_bytes(device));
2751 btrfs_set_device_bytes_used(leaf, dev_item,
2752 btrfs_device_get_bytes_used(device));
2753 btrfs_mark_buffer_dirty(leaf);
2756 btrfs_free_path(path);
2760 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2761 struct btrfs_device *device, u64 new_size)
2763 struct btrfs_fs_info *fs_info = device->fs_info;
2764 struct btrfs_super_block *super_copy = fs_info->super_copy;
2765 struct btrfs_fs_devices *fs_devices;
2769 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2772 new_size = round_down(new_size, fs_info->sectorsize);
2774 mutex_lock(&fs_info->chunk_mutex);
2775 old_total = btrfs_super_total_bytes(super_copy);
2776 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2778 if (new_size <= device->total_bytes ||
2779 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2780 mutex_unlock(&fs_info->chunk_mutex);
2784 fs_devices = fs_info->fs_devices;
2786 btrfs_set_super_total_bytes(super_copy,
2787 round_down(old_total + diff, fs_info->sectorsize));
2788 device->fs_devices->total_rw_bytes += diff;
2790 btrfs_device_set_total_bytes(device, new_size);
2791 btrfs_device_set_disk_total_bytes(device, new_size);
2792 btrfs_clear_space_info_full(device->fs_info);
2793 if (list_empty(&device->resized_list))
2794 list_add_tail(&device->resized_list,
2795 &fs_devices->resized_devices);
2796 mutex_unlock(&fs_info->chunk_mutex);
2798 return btrfs_update_device(trans, device);
2801 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2802 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2804 struct btrfs_root *root = fs_info->chunk_root;
2806 struct btrfs_path *path;
2807 struct btrfs_key key;
2809 path = btrfs_alloc_path();
2813 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2814 key.offset = chunk_offset;
2815 key.type = BTRFS_CHUNK_ITEM_KEY;
2817 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2820 else if (ret > 0) { /* Logic error or corruption */
2821 btrfs_handle_fs_error(fs_info, -ENOENT,
2822 "Failed lookup while freeing chunk.");
2827 ret = btrfs_del_item(trans, root, path);
2829 btrfs_handle_fs_error(fs_info, ret,
2830 "Failed to delete chunk item.");
2832 btrfs_free_path(path);
2836 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2838 struct btrfs_super_block *super_copy = fs_info->super_copy;
2839 struct btrfs_disk_key *disk_key;
2840 struct btrfs_chunk *chunk;
2847 struct btrfs_key key;
2849 mutex_lock(&fs_info->chunk_mutex);
2850 array_size = btrfs_super_sys_array_size(super_copy);
2852 ptr = super_copy->sys_chunk_array;
2855 while (cur < array_size) {
2856 disk_key = (struct btrfs_disk_key *)ptr;
2857 btrfs_disk_key_to_cpu(&key, disk_key);
2859 len = sizeof(*disk_key);
2861 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2862 chunk = (struct btrfs_chunk *)(ptr + len);
2863 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2864 len += btrfs_chunk_item_size(num_stripes);
2869 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2870 key.offset == chunk_offset) {
2871 memmove(ptr, ptr + len, array_size - (cur + len));
2873 btrfs_set_super_sys_array_size(super_copy, array_size);
2879 mutex_unlock(&fs_info->chunk_mutex);
2883 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2884 u64 logical, u64 length)
2886 struct extent_map_tree *em_tree;
2887 struct extent_map *em;
2889 em_tree = &fs_info->mapping_tree.map_tree;
2890 read_lock(&em_tree->lock);
2891 em = lookup_extent_mapping(em_tree, logical, length);
2892 read_unlock(&em_tree->lock);
2895 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2897 return ERR_PTR(-EINVAL);
2900 if (em->start > logical || em->start + em->len < logical) {
2902 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2903 logical, length, em->start, em->start + em->len);
2904 free_extent_map(em);
2905 return ERR_PTR(-EINVAL);
2908 /* callers are responsible for dropping em's ref. */
2912 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2913 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2915 struct extent_map *em;
2916 struct map_lookup *map;
2917 u64 dev_extent_len = 0;
2919 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2921 em = get_chunk_map(fs_info, chunk_offset, 1);
2924 * This is a logic error, but we don't want to just rely on the
2925 * user having built with ASSERT enabled, so if ASSERT doesn't
2926 * do anything we still error out.
2931 map = em->map_lookup;
2932 mutex_lock(&fs_info->chunk_mutex);
2933 check_system_chunk(trans, fs_info, map->type);
2934 mutex_unlock(&fs_info->chunk_mutex);
2937 * Take the device list mutex to prevent races with the final phase of
2938 * a device replace operation that replaces the device object associated
2939 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2941 mutex_lock(&fs_devices->device_list_mutex);
2942 for (i = 0; i < map->num_stripes; i++) {
2943 struct btrfs_device *device = map->stripes[i].dev;
2944 ret = btrfs_free_dev_extent(trans, device,
2945 map->stripes[i].physical,
2948 mutex_unlock(&fs_devices->device_list_mutex);
2949 btrfs_abort_transaction(trans, ret);
2953 if (device->bytes_used > 0) {
2954 mutex_lock(&fs_info->chunk_mutex);
2955 btrfs_device_set_bytes_used(device,
2956 device->bytes_used - dev_extent_len);
2957 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2958 btrfs_clear_space_info_full(fs_info);
2959 mutex_unlock(&fs_info->chunk_mutex);
2962 if (map->stripes[i].dev) {
2963 ret = btrfs_update_device(trans, map->stripes[i].dev);
2965 mutex_unlock(&fs_devices->device_list_mutex);
2966 btrfs_abort_transaction(trans, ret);
2971 mutex_unlock(&fs_devices->device_list_mutex);
2973 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2975 btrfs_abort_transaction(trans, ret);
2979 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2981 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2982 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2984 btrfs_abort_transaction(trans, ret);
2989 ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2991 btrfs_abort_transaction(trans, ret);
2997 free_extent_map(em);
3001 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3003 struct btrfs_root *root = fs_info->chunk_root;
3004 struct btrfs_trans_handle *trans;
3008 * Prevent races with automatic removal of unused block groups.
3009 * After we relocate and before we remove the chunk with offset
3010 * chunk_offset, automatic removal of the block group can kick in,
3011 * resulting in a failure when calling btrfs_remove_chunk() below.
3013 * Make sure to acquire this mutex before doing a tree search (dev
3014 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3015 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3016 * we release the path used to search the chunk/dev tree and before
3017 * the current task acquires this mutex and calls us.
3019 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3021 ret = btrfs_can_relocate(fs_info, chunk_offset);
3025 /* step one, relocate all the extents inside this chunk */
3026 btrfs_scrub_pause(fs_info);
3027 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3028 btrfs_scrub_continue(fs_info);
3033 * We add the kobjects here (and after forcing data chunk creation)
3034 * since relocation is the only place we'll create chunks of a new
3035 * type at runtime. The only place where we'll remove the last
3036 * chunk of a type is the call immediately below this one. Even
3037 * so, we're protected against races with the cleaner thread since
3038 * we're covered by the delete_unused_bgs_mutex.
3040 btrfs_add_raid_kobjects(fs_info);
3042 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3044 if (IS_ERR(trans)) {
3045 ret = PTR_ERR(trans);
3046 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3051 * step two, delete the device extents and the
3052 * chunk tree entries
3054 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
3055 btrfs_end_transaction(trans);
3059 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3061 struct btrfs_root *chunk_root = fs_info->chunk_root;
3062 struct btrfs_path *path;
3063 struct extent_buffer *leaf;
3064 struct btrfs_chunk *chunk;
3065 struct btrfs_key key;
3066 struct btrfs_key found_key;
3068 bool retried = false;
3072 path = btrfs_alloc_path();
3077 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3078 key.offset = (u64)-1;
3079 key.type = BTRFS_CHUNK_ITEM_KEY;
3082 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3083 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3085 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3088 BUG_ON(ret == 0); /* Corruption */
3090 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3093 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3099 leaf = path->nodes[0];
3100 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3102 chunk = btrfs_item_ptr(leaf, path->slots[0],
3103 struct btrfs_chunk);
3104 chunk_type = btrfs_chunk_type(leaf, chunk);
3105 btrfs_release_path(path);
3107 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3108 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3114 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3116 if (found_key.offset == 0)
3118 key.offset = found_key.offset - 1;
3121 if (failed && !retried) {
3125 } else if (WARN_ON(failed && retried)) {
3129 btrfs_free_path(path);
3134 * return 1 : allocate a data chunk successfully,
3135 * return <0: errors during allocating a data chunk,
3136 * return 0 : no need to allocate a data chunk.
3138 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3141 struct btrfs_block_group_cache *cache;
3145 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3147 chunk_type = cache->flags;
3148 btrfs_put_block_group(cache);
3150 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3151 spin_lock(&fs_info->data_sinfo->lock);
3152 bytes_used = fs_info->data_sinfo->bytes_used;
3153 spin_unlock(&fs_info->data_sinfo->lock);
3156 struct btrfs_trans_handle *trans;
3159 trans = btrfs_join_transaction(fs_info->tree_root);
3161 return PTR_ERR(trans);
3163 ret = btrfs_force_chunk_alloc(trans, fs_info,
3164 BTRFS_BLOCK_GROUP_DATA);
3165 btrfs_end_transaction(trans);
3169 btrfs_add_raid_kobjects(fs_info);
3177 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3178 struct btrfs_balance_control *bctl)
3180 struct btrfs_root *root = fs_info->tree_root;
3181 struct btrfs_trans_handle *trans;
3182 struct btrfs_balance_item *item;
3183 struct btrfs_disk_balance_args disk_bargs;
3184 struct btrfs_path *path;
3185 struct extent_buffer *leaf;
3186 struct btrfs_key key;
3189 path = btrfs_alloc_path();
3193 trans = btrfs_start_transaction(root, 0);
3194 if (IS_ERR(trans)) {
3195 btrfs_free_path(path);
3196 return PTR_ERR(trans);
3199 key.objectid = BTRFS_BALANCE_OBJECTID;
3200 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3203 ret = btrfs_insert_empty_item(trans, root, path, &key,
3208 leaf = path->nodes[0];
3209 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3211 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3213 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3214 btrfs_set_balance_data(leaf, item, &disk_bargs);
3215 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3216 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3217 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3218 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3220 btrfs_set_balance_flags(leaf, item, bctl->flags);
3222 btrfs_mark_buffer_dirty(leaf);
3224 btrfs_free_path(path);
3225 err = btrfs_commit_transaction(trans);
3231 static int del_balance_item(struct btrfs_fs_info *fs_info)
3233 struct btrfs_root *root = fs_info->tree_root;
3234 struct btrfs_trans_handle *trans;
3235 struct btrfs_path *path;
3236 struct btrfs_key key;
3239 path = btrfs_alloc_path();
3243 trans = btrfs_start_transaction(root, 0);
3244 if (IS_ERR(trans)) {
3245 btrfs_free_path(path);
3246 return PTR_ERR(trans);
3249 key.objectid = BTRFS_BALANCE_OBJECTID;
3250 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3253 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3261 ret = btrfs_del_item(trans, root, path);
3263 btrfs_free_path(path);
3264 err = btrfs_commit_transaction(trans);
3271 * This is a heuristic used to reduce the number of chunks balanced on
3272 * resume after balance was interrupted.
3274 static void update_balance_args(struct btrfs_balance_control *bctl)
3277 * Turn on soft mode for chunk types that were being converted.
3279 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3280 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3281 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3282 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3283 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3284 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3287 * Turn on usage filter if is not already used. The idea is
3288 * that chunks that we have already balanced should be
3289 * reasonably full. Don't do it for chunks that are being
3290 * converted - that will keep us from relocating unconverted
3291 * (albeit full) chunks.
3293 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3294 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3295 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3296 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3297 bctl->data.usage = 90;
3299 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3300 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3301 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3302 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3303 bctl->sys.usage = 90;
3305 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3306 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3307 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3308 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3309 bctl->meta.usage = 90;
3314 * Should be called with both balance and volume mutexes held to
3315 * serialize other volume operations (add_dev/rm_dev/resize) with
3316 * restriper. Same goes for unset_balance_control.
3318 static void set_balance_control(struct btrfs_balance_control *bctl)
3320 struct btrfs_fs_info *fs_info = bctl->fs_info;
3322 BUG_ON(fs_info->balance_ctl);
3324 spin_lock(&fs_info->balance_lock);
3325 fs_info->balance_ctl = bctl;
3326 spin_unlock(&fs_info->balance_lock);
3329 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3331 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3333 BUG_ON(!fs_info->balance_ctl);
3335 spin_lock(&fs_info->balance_lock);
3336 fs_info->balance_ctl = NULL;
3337 spin_unlock(&fs_info->balance_lock);
3343 * Balance filters. Return 1 if chunk should be filtered out
3344 * (should not be balanced).
3346 static int chunk_profiles_filter(u64 chunk_type,
3347 struct btrfs_balance_args *bargs)
3349 chunk_type = chunk_to_extended(chunk_type) &
3350 BTRFS_EXTENDED_PROFILE_MASK;
3352 if (bargs->profiles & chunk_type)
3358 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3359 struct btrfs_balance_args *bargs)
3361 struct btrfs_block_group_cache *cache;
3363 u64 user_thresh_min;
3364 u64 user_thresh_max;
3367 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3368 chunk_used = btrfs_block_group_used(&cache->item);
3370 if (bargs->usage_min == 0)
3371 user_thresh_min = 0;
3373 user_thresh_min = div_factor_fine(cache->key.offset,
3376 if (bargs->usage_max == 0)
3377 user_thresh_max = 1;
3378 else if (bargs->usage_max > 100)
3379 user_thresh_max = cache->key.offset;
3381 user_thresh_max = div_factor_fine(cache->key.offset,
3384 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3387 btrfs_put_block_group(cache);
3391 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3392 u64 chunk_offset, struct btrfs_balance_args *bargs)
3394 struct btrfs_block_group_cache *cache;
3395 u64 chunk_used, user_thresh;
3398 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3399 chunk_used = btrfs_block_group_used(&cache->item);
3401 if (bargs->usage_min == 0)
3403 else if (bargs->usage > 100)
3404 user_thresh = cache->key.offset;
3406 user_thresh = div_factor_fine(cache->key.offset,
3409 if (chunk_used < user_thresh)
3412 btrfs_put_block_group(cache);
3416 static int chunk_devid_filter(struct extent_buffer *leaf,
3417 struct btrfs_chunk *chunk,
3418 struct btrfs_balance_args *bargs)
3420 struct btrfs_stripe *stripe;
3421 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3424 for (i = 0; i < num_stripes; i++) {
3425 stripe = btrfs_stripe_nr(chunk, i);
3426 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3433 /* [pstart, pend) */
3434 static int chunk_drange_filter(struct extent_buffer *leaf,
3435 struct btrfs_chunk *chunk,
3436 struct btrfs_balance_args *bargs)
3438 struct btrfs_stripe *stripe;
3439 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3445 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3448 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3449 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3450 factor = num_stripes / 2;
3451 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3452 factor = num_stripes - 1;
3453 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3454 factor = num_stripes - 2;
3456 factor = num_stripes;
3459 for (i = 0; i < num_stripes; i++) {
3460 stripe = btrfs_stripe_nr(chunk, i);
3461 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3464 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3465 stripe_length = btrfs_chunk_length(leaf, chunk);
3466 stripe_length = div_u64(stripe_length, factor);
3468 if (stripe_offset < bargs->pend &&
3469 stripe_offset + stripe_length > bargs->pstart)
3476 /* [vstart, vend) */
3477 static int chunk_vrange_filter(struct extent_buffer *leaf,
3478 struct btrfs_chunk *chunk,
3480 struct btrfs_balance_args *bargs)
3482 if (chunk_offset < bargs->vend &&
3483 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3484 /* at least part of the chunk is inside this vrange */
3490 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3491 struct btrfs_chunk *chunk,
3492 struct btrfs_balance_args *bargs)
3494 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3496 if (bargs->stripes_min <= num_stripes
3497 && num_stripes <= bargs->stripes_max)
3503 static int chunk_soft_convert_filter(u64 chunk_type,
3504 struct btrfs_balance_args *bargs)
3506 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3509 chunk_type = chunk_to_extended(chunk_type) &
3510 BTRFS_EXTENDED_PROFILE_MASK;
3512 if (bargs->target == chunk_type)
3518 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3519 struct extent_buffer *leaf,
3520 struct btrfs_chunk *chunk, u64 chunk_offset)
3522 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3523 struct btrfs_balance_args *bargs = NULL;
3524 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3527 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3528 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3532 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3533 bargs = &bctl->data;
3534 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3536 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3537 bargs = &bctl->meta;
3539 /* profiles filter */
3540 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3541 chunk_profiles_filter(chunk_type, bargs)) {
3546 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3547 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3549 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3550 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3555 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3556 chunk_devid_filter(leaf, chunk, bargs)) {
3560 /* drange filter, makes sense only with devid filter */
3561 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3562 chunk_drange_filter(leaf, chunk, bargs)) {
3567 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3568 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3572 /* stripes filter */
3573 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3574 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3578 /* soft profile changing mode */
3579 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3580 chunk_soft_convert_filter(chunk_type, bargs)) {
3585 * limited by count, must be the last filter
3587 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3588 if (bargs->limit == 0)
3592 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3594 * Same logic as the 'limit' filter; the minimum cannot be
3595 * determined here because we do not have the global information
3596 * about the count of all chunks that satisfy the filters.
3598 if (bargs->limit_max == 0)
3607 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3609 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3610 struct btrfs_root *chunk_root = fs_info->chunk_root;
3611 struct btrfs_root *dev_root = fs_info->dev_root;
3612 struct list_head *devices;
3613 struct btrfs_device *device;
3617 struct btrfs_chunk *chunk;
3618 struct btrfs_path *path = NULL;
3619 struct btrfs_key key;
3620 struct btrfs_key found_key;
3621 struct btrfs_trans_handle *trans;
3622 struct extent_buffer *leaf;
3625 int enospc_errors = 0;
3626 bool counting = true;
3627 /* The single value limit and min/max limits use the same bytes in the */
3628 u64 limit_data = bctl->data.limit;
3629 u64 limit_meta = bctl->meta.limit;
3630 u64 limit_sys = bctl->sys.limit;
3634 int chunk_reserved = 0;
3636 /* step one make some room on all the devices */
3637 devices = &fs_info->fs_devices->devices;
3638 list_for_each_entry(device, devices, dev_list) {
3639 old_size = btrfs_device_get_total_bytes(device);
3640 size_to_free = div_factor(old_size, 1);
3641 size_to_free = min_t(u64, size_to_free, SZ_1M);
3642 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3643 btrfs_device_get_total_bytes(device) -
3644 btrfs_device_get_bytes_used(device) > size_to_free ||
3645 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3648 ret = btrfs_shrink_device(device, old_size - size_to_free);
3652 /* btrfs_shrink_device never returns ret > 0 */
3657 trans = btrfs_start_transaction(dev_root, 0);
3658 if (IS_ERR(trans)) {
3659 ret = PTR_ERR(trans);
3660 btrfs_info_in_rcu(fs_info,
3661 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3662 rcu_str_deref(device->name), ret,
3663 old_size, old_size - size_to_free);
3667 ret = btrfs_grow_device(trans, device, old_size);
3669 btrfs_end_transaction(trans);
3670 /* btrfs_grow_device never returns ret > 0 */
3672 btrfs_info_in_rcu(fs_info,
3673 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3674 rcu_str_deref(device->name), ret,
3675 old_size, old_size - size_to_free);
3679 btrfs_end_transaction(trans);
3682 /* step two, relocate all the chunks */
3683 path = btrfs_alloc_path();
3689 /* zero out stat counters */
3690 spin_lock(&fs_info->balance_lock);
3691 memset(&bctl->stat, 0, sizeof(bctl->stat));
3692 spin_unlock(&fs_info->balance_lock);
3696 * The single value limit and min/max limits use the same bytes
3699 bctl->data.limit = limit_data;
3700 bctl->meta.limit = limit_meta;
3701 bctl->sys.limit = limit_sys;
3703 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3704 key.offset = (u64)-1;
3705 key.type = BTRFS_CHUNK_ITEM_KEY;
3708 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3709 atomic_read(&fs_info->balance_cancel_req)) {
3714 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3715 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3717 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3722 * this shouldn't happen, it means the last relocate
3726 BUG(); /* FIXME break ? */
3728 ret = btrfs_previous_item(chunk_root, path, 0,
3729 BTRFS_CHUNK_ITEM_KEY);
3731 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3736 leaf = path->nodes[0];
3737 slot = path->slots[0];
3738 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3740 if (found_key.objectid != key.objectid) {
3741 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3745 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3746 chunk_type = btrfs_chunk_type(leaf, chunk);
3749 spin_lock(&fs_info->balance_lock);
3750 bctl->stat.considered++;
3751 spin_unlock(&fs_info->balance_lock);
3754 ret = should_balance_chunk(fs_info, leaf, chunk,
3757 btrfs_release_path(path);
3759 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3764 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3765 spin_lock(&fs_info->balance_lock);
3766 bctl->stat.expected++;
3767 spin_unlock(&fs_info->balance_lock);
3769 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3771 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3773 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3780 * Apply limit_min filter, no need to check if the LIMITS
3781 * filter is used, limit_min is 0 by default
3783 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3784 count_data < bctl->data.limit_min)
3785 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3786 count_meta < bctl->meta.limit_min)
3787 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3788 count_sys < bctl->sys.limit_min)) {
3789 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3793 if (!chunk_reserved) {
3795 * We may be relocating the only data chunk we have,
3796 * which could potentially end up with losing data's
3797 * raid profile, so lets allocate an empty one in
3800 ret = btrfs_may_alloc_data_chunk(fs_info,
3803 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3805 } else if (ret == 1) {
3810 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3811 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3812 if (ret && ret != -ENOSPC)
3814 if (ret == -ENOSPC) {
3817 spin_lock(&fs_info->balance_lock);
3818 bctl->stat.completed++;
3819 spin_unlock(&fs_info->balance_lock);
3822 if (found_key.offset == 0)
3824 key.offset = found_key.offset - 1;
3828 btrfs_release_path(path);
3833 btrfs_free_path(path);
3834 if (enospc_errors) {
3835 btrfs_info(fs_info, "%d enospc errors during balance",
3845 * alloc_profile_is_valid - see if a given profile is valid and reduced
3846 * @flags: profile to validate
3847 * @extended: if true @flags is treated as an extended profile
3849 static int alloc_profile_is_valid(u64 flags, int extended)
3851 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3852 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3854 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3856 /* 1) check that all other bits are zeroed */
3860 /* 2) see if profile is reduced */
3862 return !extended; /* "0" is valid for usual profiles */
3864 /* true if exactly one bit set */
3865 return (flags & (flags - 1)) == 0;
3868 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3870 /* cancel requested || normal exit path */
3871 return atomic_read(&fs_info->balance_cancel_req) ||
3872 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3873 atomic_read(&fs_info->balance_cancel_req) == 0);
3876 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3880 unset_balance_control(fs_info);
3881 ret = del_balance_item(fs_info);
3883 btrfs_handle_fs_error(fs_info, ret, NULL);
3885 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3888 /* Non-zero return value signifies invalidity */
3889 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3892 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3893 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3894 (bctl_arg->target & ~allowed)));
3898 * Should be called with both balance and volume mutexes held
3900 int btrfs_balance(struct btrfs_balance_control *bctl,
3901 struct btrfs_ioctl_balance_args *bargs)
3903 struct btrfs_fs_info *fs_info = bctl->fs_info;
3904 u64 meta_target, data_target;
3911 if (btrfs_fs_closing(fs_info) ||
3912 atomic_read(&fs_info->balance_pause_req) ||
3913 atomic_read(&fs_info->balance_cancel_req)) {
3918 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3919 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3923 * In case of mixed groups both data and meta should be picked,
3924 * and identical options should be given for both of them.
3926 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3927 if (mixed && (bctl->flags & allowed)) {
3928 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3929 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3930 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3932 "with mixed groups data and metadata balance options must be the same");
3938 num_devices = fs_info->fs_devices->num_devices;
3939 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
3940 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3941 BUG_ON(num_devices < 1);
3944 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
3945 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3946 if (num_devices > 1)
3947 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3948 if (num_devices > 2)
3949 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3950 if (num_devices > 3)
3951 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3952 BTRFS_BLOCK_GROUP_RAID6);
3953 if (validate_convert_profile(&bctl->data, allowed)) {
3955 "unable to start balance with target data profile %llu",
3960 if (validate_convert_profile(&bctl->meta, allowed)) {
3962 "unable to start balance with target metadata profile %llu",
3967 if (validate_convert_profile(&bctl->sys, allowed)) {
3969 "unable to start balance with target system profile %llu",
3975 /* allow to reduce meta or sys integrity only if force set */
3976 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3977 BTRFS_BLOCK_GROUP_RAID10 |
3978 BTRFS_BLOCK_GROUP_RAID5 |
3979 BTRFS_BLOCK_GROUP_RAID6;
3981 seq = read_seqbegin(&fs_info->profiles_lock);
3983 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3984 (fs_info->avail_system_alloc_bits & allowed) &&
3985 !(bctl->sys.target & allowed)) ||
3986 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3987 (fs_info->avail_metadata_alloc_bits & allowed) &&
3988 !(bctl->meta.target & allowed))) {
3989 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3991 "force reducing metadata integrity");
3994 "balance will reduce metadata integrity, use force if you want this");
3999 } while (read_seqretry(&fs_info->profiles_lock, seq));
4001 /* if we're not converting, the target field is uninitialized */
4002 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4003 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4004 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4005 bctl->data.target : fs_info->avail_data_alloc_bits;
4006 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4007 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4009 "metadata profile 0x%llx has lower redundancy than data profile 0x%llx",
4010 meta_target, data_target);
4013 ret = insert_balance_item(fs_info, bctl);
4014 if (ret && ret != -EEXIST)
4017 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4018 BUG_ON(ret == -EEXIST);
4019 set_balance_control(bctl);
4021 BUG_ON(ret != -EEXIST);
4022 spin_lock(&fs_info->balance_lock);
4023 update_balance_args(bctl);
4024 spin_unlock(&fs_info->balance_lock);
4027 atomic_inc(&fs_info->balance_running);
4028 mutex_unlock(&fs_info->balance_mutex);
4030 ret = __btrfs_balance(fs_info);
4032 mutex_lock(&fs_info->balance_mutex);
4033 atomic_dec(&fs_info->balance_running);
4036 memset(bargs, 0, sizeof(*bargs));
4037 update_ioctl_balance_args(fs_info, 0, bargs);
4040 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4041 balance_need_close(fs_info)) {
4042 __cancel_balance(fs_info);
4045 wake_up(&fs_info->balance_wait_q);
4049 if (bctl->flags & BTRFS_BALANCE_RESUME)
4050 __cancel_balance(fs_info);
4053 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4058 static int balance_kthread(void *data)
4060 struct btrfs_fs_info *fs_info = data;
4063 mutex_lock(&fs_info->volume_mutex);
4064 mutex_lock(&fs_info->balance_mutex);
4066 if (fs_info->balance_ctl) {
4067 btrfs_info(fs_info, "continuing balance");
4068 ret = btrfs_balance(fs_info->balance_ctl, NULL);
4071 mutex_unlock(&fs_info->balance_mutex);
4072 mutex_unlock(&fs_info->volume_mutex);
4077 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4079 struct task_struct *tsk;
4081 spin_lock(&fs_info->balance_lock);
4082 if (!fs_info->balance_ctl) {
4083 spin_unlock(&fs_info->balance_lock);
4086 spin_unlock(&fs_info->balance_lock);
4088 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4089 btrfs_info(fs_info, "force skipping balance");
4094 * A ro->rw remount sequence should continue with the paused balance
4095 * regardless of who pauses it, system or the user as of now, so set
4098 spin_lock(&fs_info->balance_lock);
4099 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4100 spin_unlock(&fs_info->balance_lock);
4102 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4103 return PTR_ERR_OR_ZERO(tsk);
4106 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4108 struct btrfs_balance_control *bctl;
4109 struct btrfs_balance_item *item;
4110 struct btrfs_disk_balance_args disk_bargs;
4111 struct btrfs_path *path;
4112 struct extent_buffer *leaf;
4113 struct btrfs_key key;
4116 path = btrfs_alloc_path();
4120 key.objectid = BTRFS_BALANCE_OBJECTID;
4121 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4124 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4127 if (ret > 0) { /* ret = -ENOENT; */
4132 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4138 leaf = path->nodes[0];
4139 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4141 bctl->fs_info = fs_info;
4142 bctl->flags = btrfs_balance_flags(leaf, item);
4143 bctl->flags |= BTRFS_BALANCE_RESUME;
4145 btrfs_balance_data(leaf, item, &disk_bargs);
4146 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4147 btrfs_balance_meta(leaf, item, &disk_bargs);
4148 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4149 btrfs_balance_sys(leaf, item, &disk_bargs);
4150 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4152 WARN_ON(test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4154 mutex_lock(&fs_info->volume_mutex);
4155 mutex_lock(&fs_info->balance_mutex);
4157 set_balance_control(bctl);
4159 mutex_unlock(&fs_info->balance_mutex);
4160 mutex_unlock(&fs_info->volume_mutex);
4162 btrfs_free_path(path);
4166 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4170 mutex_lock(&fs_info->balance_mutex);
4171 if (!fs_info->balance_ctl) {
4172 mutex_unlock(&fs_info->balance_mutex);
4176 if (atomic_read(&fs_info->balance_running)) {
4177 atomic_inc(&fs_info->balance_pause_req);
4178 mutex_unlock(&fs_info->balance_mutex);
4180 wait_event(fs_info->balance_wait_q,
4181 atomic_read(&fs_info->balance_running) == 0);
4183 mutex_lock(&fs_info->balance_mutex);
4184 /* we are good with balance_ctl ripped off from under us */
4185 BUG_ON(atomic_read(&fs_info->balance_running));
4186 atomic_dec(&fs_info->balance_pause_req);
4191 mutex_unlock(&fs_info->balance_mutex);
4195 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4197 if (sb_rdonly(fs_info->sb))
4200 mutex_lock(&fs_info->balance_mutex);
4201 if (!fs_info->balance_ctl) {
4202 mutex_unlock(&fs_info->balance_mutex);
4206 atomic_inc(&fs_info->balance_cancel_req);
4208 * if we are running just wait and return, balance item is
4209 * deleted in btrfs_balance in this case
4211 if (atomic_read(&fs_info->balance_running)) {
4212 mutex_unlock(&fs_info->balance_mutex);
4213 wait_event(fs_info->balance_wait_q,
4214 atomic_read(&fs_info->balance_running) == 0);
4215 mutex_lock(&fs_info->balance_mutex);
4217 /* __cancel_balance needs volume_mutex */
4218 mutex_unlock(&fs_info->balance_mutex);
4219 mutex_lock(&fs_info->volume_mutex);
4220 mutex_lock(&fs_info->balance_mutex);
4222 if (fs_info->balance_ctl)
4223 __cancel_balance(fs_info);
4225 mutex_unlock(&fs_info->volume_mutex);
4228 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
4229 atomic_dec(&fs_info->balance_cancel_req);
4230 mutex_unlock(&fs_info->balance_mutex);
4234 static int btrfs_uuid_scan_kthread(void *data)
4236 struct btrfs_fs_info *fs_info = data;
4237 struct btrfs_root *root = fs_info->tree_root;
4238 struct btrfs_key key;
4239 struct btrfs_path *path = NULL;
4241 struct extent_buffer *eb;
4243 struct btrfs_root_item root_item;
4245 struct btrfs_trans_handle *trans = NULL;
4247 path = btrfs_alloc_path();
4254 key.type = BTRFS_ROOT_ITEM_KEY;
4258 ret = btrfs_search_forward(root, &key, path,
4259 BTRFS_OLDEST_GENERATION);
4266 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4267 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4268 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4269 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4272 eb = path->nodes[0];
4273 slot = path->slots[0];
4274 item_size = btrfs_item_size_nr(eb, slot);
4275 if (item_size < sizeof(root_item))
4278 read_extent_buffer(eb, &root_item,
4279 btrfs_item_ptr_offset(eb, slot),
4280 (int)sizeof(root_item));
4281 if (btrfs_root_refs(&root_item) == 0)
4284 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4285 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4289 btrfs_release_path(path);
4291 * 1 - subvol uuid item
4292 * 1 - received_subvol uuid item
4294 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4295 if (IS_ERR(trans)) {
4296 ret = PTR_ERR(trans);
4304 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4305 ret = btrfs_uuid_tree_add(trans, fs_info,
4307 BTRFS_UUID_KEY_SUBVOL,
4310 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4316 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4317 ret = btrfs_uuid_tree_add(trans, fs_info,
4318 root_item.received_uuid,
4319 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4322 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4330 ret = btrfs_end_transaction(trans);
4336 btrfs_release_path(path);
4337 if (key.offset < (u64)-1) {
4339 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4341 key.type = BTRFS_ROOT_ITEM_KEY;
4342 } else if (key.objectid < (u64)-1) {
4344 key.type = BTRFS_ROOT_ITEM_KEY;
4353 btrfs_free_path(path);
4354 if (trans && !IS_ERR(trans))
4355 btrfs_end_transaction(trans);
4357 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4359 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4360 up(&fs_info->uuid_tree_rescan_sem);
4365 * Callback for btrfs_uuid_tree_iterate().
4367 * 0 check succeeded, the entry is not outdated.
4368 * < 0 if an error occurred.
4369 * > 0 if the check failed, which means the caller shall remove the entry.
4371 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4372 u8 *uuid, u8 type, u64 subid)
4374 struct btrfs_key key;
4376 struct btrfs_root *subvol_root;
4378 if (type != BTRFS_UUID_KEY_SUBVOL &&
4379 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4382 key.objectid = subid;
4383 key.type = BTRFS_ROOT_ITEM_KEY;
4384 key.offset = (u64)-1;
4385 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4386 if (IS_ERR(subvol_root)) {
4387 ret = PTR_ERR(subvol_root);
4394 case BTRFS_UUID_KEY_SUBVOL:
4395 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4398 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4399 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4409 static int btrfs_uuid_rescan_kthread(void *data)
4411 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4415 * 1st step is to iterate through the existing UUID tree and
4416 * to delete all entries that contain outdated data.
4417 * 2nd step is to add all missing entries to the UUID tree.
4419 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4421 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4422 up(&fs_info->uuid_tree_rescan_sem);
4425 return btrfs_uuid_scan_kthread(data);
4428 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4430 struct btrfs_trans_handle *trans;
4431 struct btrfs_root *tree_root = fs_info->tree_root;
4432 struct btrfs_root *uuid_root;
4433 struct task_struct *task;
4440 trans = btrfs_start_transaction(tree_root, 2);
4442 return PTR_ERR(trans);
4444 uuid_root = btrfs_create_tree(trans, fs_info,
4445 BTRFS_UUID_TREE_OBJECTID);
4446 if (IS_ERR(uuid_root)) {
4447 ret = PTR_ERR(uuid_root);
4448 btrfs_abort_transaction(trans, ret);
4449 btrfs_end_transaction(trans);
4453 fs_info->uuid_root = uuid_root;
4455 ret = btrfs_commit_transaction(trans);
4459 down(&fs_info->uuid_tree_rescan_sem);
4460 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4462 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4463 btrfs_warn(fs_info, "failed to start uuid_scan task");
4464 up(&fs_info->uuid_tree_rescan_sem);
4465 return PTR_ERR(task);
4471 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4473 struct task_struct *task;
4475 down(&fs_info->uuid_tree_rescan_sem);
4476 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4478 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4479 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4480 up(&fs_info->uuid_tree_rescan_sem);
4481 return PTR_ERR(task);
4488 * shrinking a device means finding all of the device extents past
4489 * the new size, and then following the back refs to the chunks.
4490 * The chunk relocation code actually frees the device extent
4492 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4494 struct btrfs_fs_info *fs_info = device->fs_info;
4495 struct btrfs_root *root = fs_info->dev_root;
4496 struct btrfs_trans_handle *trans;
4497 struct btrfs_dev_extent *dev_extent = NULL;
4498 struct btrfs_path *path;
4504 bool retried = false;
4505 bool checked_pending_chunks = false;
4506 struct extent_buffer *l;
4507 struct btrfs_key key;
4508 struct btrfs_super_block *super_copy = fs_info->super_copy;
4509 u64 old_total = btrfs_super_total_bytes(super_copy);
4510 u64 old_size = btrfs_device_get_total_bytes(device);
4513 new_size = round_down(new_size, fs_info->sectorsize);
4514 diff = round_down(old_size - new_size, fs_info->sectorsize);
4516 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4519 path = btrfs_alloc_path();
4523 path->reada = READA_FORWARD;
4525 mutex_lock(&fs_info->chunk_mutex);
4527 btrfs_device_set_total_bytes(device, new_size);
4528 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4529 device->fs_devices->total_rw_bytes -= diff;
4530 atomic64_sub(diff, &fs_info->free_chunk_space);
4532 mutex_unlock(&fs_info->chunk_mutex);
4535 key.objectid = device->devid;
4536 key.offset = (u64)-1;
4537 key.type = BTRFS_DEV_EXTENT_KEY;
4540 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4541 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4543 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4547 ret = btrfs_previous_item(root, path, 0, key.type);
4549 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4554 btrfs_release_path(path);
4559 slot = path->slots[0];
4560 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4562 if (key.objectid != device->devid) {
4563 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4564 btrfs_release_path(path);
4568 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4569 length = btrfs_dev_extent_length(l, dev_extent);
4571 if (key.offset + length <= new_size) {
4572 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4573 btrfs_release_path(path);
4577 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4578 btrfs_release_path(path);
4581 * We may be relocating the only data chunk we have,
4582 * which could potentially end up with losing data's
4583 * raid profile, so lets allocate an empty one in
4586 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4588 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4592 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4593 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4594 if (ret && ret != -ENOSPC)
4598 } while (key.offset-- > 0);
4600 if (failed && !retried) {
4604 } else if (failed && retried) {
4609 /* Shrinking succeeded, else we would be at "done". */
4610 trans = btrfs_start_transaction(root, 0);
4611 if (IS_ERR(trans)) {
4612 ret = PTR_ERR(trans);
4616 mutex_lock(&fs_info->chunk_mutex);
4619 * We checked in the above loop all device extents that were already in
4620 * the device tree. However before we have updated the device's
4621 * total_bytes to the new size, we might have had chunk allocations that
4622 * have not complete yet (new block groups attached to transaction
4623 * handles), and therefore their device extents were not yet in the
4624 * device tree and we missed them in the loop above. So if we have any
4625 * pending chunk using a device extent that overlaps the device range
4626 * that we can not use anymore, commit the current transaction and
4627 * repeat the search on the device tree - this way we guarantee we will
4628 * not have chunks using device extents that end beyond 'new_size'.
4630 if (!checked_pending_chunks) {
4631 u64 start = new_size;
4632 u64 len = old_size - new_size;
4634 if (contains_pending_extent(trans->transaction, device,
4636 mutex_unlock(&fs_info->chunk_mutex);
4637 checked_pending_chunks = true;
4640 ret = btrfs_commit_transaction(trans);
4647 btrfs_device_set_disk_total_bytes(device, new_size);
4648 if (list_empty(&device->resized_list))
4649 list_add_tail(&device->resized_list,
4650 &fs_info->fs_devices->resized_devices);
4652 WARN_ON(diff > old_total);
4653 btrfs_set_super_total_bytes(super_copy,
4654 round_down(old_total - diff, fs_info->sectorsize));
4655 mutex_unlock(&fs_info->chunk_mutex);
4657 /* Now btrfs_update_device() will change the on-disk size. */
4658 ret = btrfs_update_device(trans, device);
4659 btrfs_end_transaction(trans);
4661 btrfs_free_path(path);
4663 mutex_lock(&fs_info->chunk_mutex);
4664 btrfs_device_set_total_bytes(device, old_size);
4665 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4666 device->fs_devices->total_rw_bytes += diff;
4667 atomic64_add(diff, &fs_info->free_chunk_space);
4668 mutex_unlock(&fs_info->chunk_mutex);
4673 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4674 struct btrfs_key *key,
4675 struct btrfs_chunk *chunk, int item_size)
4677 struct btrfs_super_block *super_copy = fs_info->super_copy;
4678 struct btrfs_disk_key disk_key;
4682 mutex_lock(&fs_info->chunk_mutex);
4683 array_size = btrfs_super_sys_array_size(super_copy);
4684 if (array_size + item_size + sizeof(disk_key)
4685 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4686 mutex_unlock(&fs_info->chunk_mutex);
4690 ptr = super_copy->sys_chunk_array + array_size;
4691 btrfs_cpu_key_to_disk(&disk_key, key);
4692 memcpy(ptr, &disk_key, sizeof(disk_key));
4693 ptr += sizeof(disk_key);
4694 memcpy(ptr, chunk, item_size);
4695 item_size += sizeof(disk_key);
4696 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4697 mutex_unlock(&fs_info->chunk_mutex);
4703 * sort the devices in descending order by max_avail, total_avail
4705 static int btrfs_cmp_device_info(const void *a, const void *b)
4707 const struct btrfs_device_info *di_a = a;
4708 const struct btrfs_device_info *di_b = b;
4710 if (di_a->max_avail > di_b->max_avail)
4712 if (di_a->max_avail < di_b->max_avail)
4714 if (di_a->total_avail > di_b->total_avail)
4716 if (di_a->total_avail < di_b->total_avail)
4721 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4723 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4726 btrfs_set_fs_incompat(info, RAID56);
4729 #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \
4730 - sizeof(struct btrfs_chunk)) \
4731 / sizeof(struct btrfs_stripe) + 1)
4733 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4734 - 2 * sizeof(struct btrfs_disk_key) \
4735 - 2 * sizeof(struct btrfs_chunk)) \
4736 / sizeof(struct btrfs_stripe) + 1)
4738 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4739 u64 start, u64 type)
4741 struct btrfs_fs_info *info = trans->fs_info;
4742 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4743 struct btrfs_device *device;
4744 struct map_lookup *map = NULL;
4745 struct extent_map_tree *em_tree;
4746 struct extent_map *em;
4747 struct btrfs_device_info *devices_info = NULL;
4749 int num_stripes; /* total number of stripes to allocate */
4750 int data_stripes; /* number of stripes that count for
4752 int sub_stripes; /* sub_stripes info for map */
4753 int dev_stripes; /* stripes per dev */
4754 int devs_max; /* max devs to use */
4755 int devs_min; /* min devs needed */
4756 int devs_increment; /* ndevs has to be a multiple of this */
4757 int ncopies; /* how many copies to data has */
4759 u64 max_stripe_size;
4768 BUG_ON(!alloc_profile_is_valid(type, 0));
4770 if (list_empty(&fs_devices->alloc_list)) {
4771 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4772 btrfs_debug(info, "%s: no writable device", __func__);
4776 index = btrfs_bg_flags_to_raid_index(type);
4778 sub_stripes = btrfs_raid_array[index].sub_stripes;
4779 dev_stripes = btrfs_raid_array[index].dev_stripes;
4780 devs_max = btrfs_raid_array[index].devs_max;
4781 devs_min = btrfs_raid_array[index].devs_min;
4782 devs_increment = btrfs_raid_array[index].devs_increment;
4783 ncopies = btrfs_raid_array[index].ncopies;
4785 if (type & BTRFS_BLOCK_GROUP_DATA) {
4786 max_stripe_size = SZ_1G;
4787 max_chunk_size = 10 * max_stripe_size;
4789 devs_max = BTRFS_MAX_DEVS(info);
4790 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4791 /* for larger filesystems, use larger metadata chunks */
4792 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4793 max_stripe_size = SZ_1G;
4795 max_stripe_size = SZ_256M;
4796 max_chunk_size = max_stripe_size;
4798 devs_max = BTRFS_MAX_DEVS(info);
4799 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4800 max_stripe_size = SZ_32M;
4801 max_chunk_size = 2 * max_stripe_size;
4803 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4805 btrfs_err(info, "invalid chunk type 0x%llx requested",
4810 /* we don't want a chunk larger than 10% of writeable space */
4811 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4814 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4820 * in the first pass through the devices list, we gather information
4821 * about the available holes on each device.
4824 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4828 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4830 "BTRFS: read-only device in alloc_list\n");
4834 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4835 &device->dev_state) ||
4836 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4839 if (device->total_bytes > device->bytes_used)
4840 total_avail = device->total_bytes - device->bytes_used;
4844 /* If there is no space on this device, skip it. */
4845 if (total_avail == 0)
4848 ret = find_free_dev_extent(trans, device,
4849 max_stripe_size * dev_stripes,
4850 &dev_offset, &max_avail);
4851 if (ret && ret != -ENOSPC)
4855 max_avail = max_stripe_size * dev_stripes;
4857 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4858 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4860 "%s: devid %llu has no free space, have=%llu want=%u",
4861 __func__, device->devid, max_avail,
4862 BTRFS_STRIPE_LEN * dev_stripes);
4866 if (ndevs == fs_devices->rw_devices) {
4867 WARN(1, "%s: found more than %llu devices\n",
4868 __func__, fs_devices->rw_devices);
4871 devices_info[ndevs].dev_offset = dev_offset;
4872 devices_info[ndevs].max_avail = max_avail;
4873 devices_info[ndevs].total_avail = total_avail;
4874 devices_info[ndevs].dev = device;
4879 * now sort the devices by hole size / available space
4881 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4882 btrfs_cmp_device_info, NULL);
4884 /* round down to number of usable stripes */
4885 ndevs = round_down(ndevs, devs_increment);
4887 if (ndevs < devs_min) {
4889 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4891 "%s: not enough devices with free space: have=%d minimum required=%d",
4892 __func__, ndevs, devs_min);
4897 ndevs = min(ndevs, devs_max);
4900 * The primary goal is to maximize the number of stripes, so use as
4901 * many devices as possible, even if the stripes are not maximum sized.
4903 * The DUP profile stores more than one stripe per device, the
4904 * max_avail is the total size so we have to adjust.
4906 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4907 num_stripes = ndevs * dev_stripes;
4910 * this will have to be fixed for RAID1 and RAID10 over
4913 data_stripes = num_stripes / ncopies;
4915 if (type & BTRFS_BLOCK_GROUP_RAID5)
4916 data_stripes = num_stripes - 1;
4918 if (type & BTRFS_BLOCK_GROUP_RAID6)
4919 data_stripes = num_stripes - 2;
4922 * Use the number of data stripes to figure out how big this chunk
4923 * is really going to be in terms of logical address space,
4924 * and compare that answer with the max chunk size
4926 if (stripe_size * data_stripes > max_chunk_size) {
4927 stripe_size = div_u64(max_chunk_size, data_stripes);
4929 /* bump the answer up to a 16MB boundary */
4930 stripe_size = round_up(stripe_size, SZ_16M);
4933 * But don't go higher than the limits we found while searching
4936 stripe_size = min(devices_info[ndevs - 1].max_avail,
4940 /* align to BTRFS_STRIPE_LEN */
4941 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4943 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4948 map->num_stripes = num_stripes;
4950 for (i = 0; i < ndevs; ++i) {
4951 for (j = 0; j < dev_stripes; ++j) {
4952 int s = i * dev_stripes + j;
4953 map->stripes[s].dev = devices_info[i].dev;
4954 map->stripes[s].physical = devices_info[i].dev_offset +
4958 map->stripe_len = BTRFS_STRIPE_LEN;
4959 map->io_align = BTRFS_STRIPE_LEN;
4960 map->io_width = BTRFS_STRIPE_LEN;
4962 map->sub_stripes = sub_stripes;
4964 num_bytes = stripe_size * data_stripes;
4966 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4968 em = alloc_extent_map();
4974 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4975 em->map_lookup = map;
4977 em->len = num_bytes;
4978 em->block_start = 0;
4979 em->block_len = em->len;
4980 em->orig_block_len = stripe_size;
4982 em_tree = &info->mapping_tree.map_tree;
4983 write_lock(&em_tree->lock);
4984 ret = add_extent_mapping(em_tree, em, 0);
4986 write_unlock(&em_tree->lock);
4987 free_extent_map(em);
4991 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4992 refcount_inc(&em->refs);
4993 write_unlock(&em_tree->lock);
4995 ret = btrfs_make_block_group(trans, info, 0, type, start, num_bytes);
4997 goto error_del_extent;
4999 for (i = 0; i < map->num_stripes; i++) {
5000 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
5001 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
5004 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
5006 free_extent_map(em);
5007 check_raid56_incompat_flag(info, type);
5009 kfree(devices_info);
5013 write_lock(&em_tree->lock);
5014 remove_extent_mapping(em_tree, em);
5015 write_unlock(&em_tree->lock);
5017 /* One for our allocation */
5018 free_extent_map(em);
5019 /* One for the tree reference */
5020 free_extent_map(em);
5021 /* One for the pending_chunks list reference */
5022 free_extent_map(em);
5024 kfree(devices_info);
5028 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5029 struct btrfs_fs_info *fs_info,
5030 u64 chunk_offset, u64 chunk_size)
5032 struct btrfs_root *extent_root = fs_info->extent_root;
5033 struct btrfs_root *chunk_root = fs_info->chunk_root;
5034 struct btrfs_key key;
5035 struct btrfs_device *device;
5036 struct btrfs_chunk *chunk;
5037 struct btrfs_stripe *stripe;
5038 struct extent_map *em;
5039 struct map_lookup *map;
5046 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
5050 map = em->map_lookup;
5051 item_size = btrfs_chunk_item_size(map->num_stripes);
5052 stripe_size = em->orig_block_len;
5054 chunk = kzalloc(item_size, GFP_NOFS);
5061 * Take the device list mutex to prevent races with the final phase of
5062 * a device replace operation that replaces the device object associated
5063 * with the map's stripes, because the device object's id can change
5064 * at any time during that final phase of the device replace operation
5065 * (dev-replace.c:btrfs_dev_replace_finishing()).
5067 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5068 for (i = 0; i < map->num_stripes; i++) {
5069 device = map->stripes[i].dev;
5070 dev_offset = map->stripes[i].physical;
5072 ret = btrfs_update_device(trans, device);
5075 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5076 dev_offset, stripe_size);
5081 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5085 stripe = &chunk->stripe;
5086 for (i = 0; i < map->num_stripes; i++) {
5087 device = map->stripes[i].dev;
5088 dev_offset = map->stripes[i].physical;
5090 btrfs_set_stack_stripe_devid(stripe, device->devid);
5091 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5092 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5095 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5097 btrfs_set_stack_chunk_length(chunk, chunk_size);
5098 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5099 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5100 btrfs_set_stack_chunk_type(chunk, map->type);
5101 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5102 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5103 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5104 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5105 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5107 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5108 key.type = BTRFS_CHUNK_ITEM_KEY;
5109 key.offset = chunk_offset;
5111 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5112 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5114 * TODO: Cleanup of inserted chunk root in case of
5117 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5122 free_extent_map(em);
5127 * Chunk allocation falls into two parts. The first part does works
5128 * that make the new allocated chunk useable, but not do any operation
5129 * that modifies the chunk tree. The second part does the works that
5130 * require modifying the chunk tree. This division is important for the
5131 * bootstrap process of adding storage to a seed btrfs.
5133 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
5134 struct btrfs_fs_info *fs_info, u64 type)
5138 lockdep_assert_held(&fs_info->chunk_mutex);
5139 chunk_offset = find_next_chunk(fs_info);
5140 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5143 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5144 struct btrfs_fs_info *fs_info)
5147 u64 sys_chunk_offset;
5151 chunk_offset = find_next_chunk(fs_info);
5152 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5153 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5157 sys_chunk_offset = find_next_chunk(fs_info);
5158 alloc_profile = btrfs_system_alloc_profile(fs_info);
5159 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5163 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5167 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5168 BTRFS_BLOCK_GROUP_RAID10 |
5169 BTRFS_BLOCK_GROUP_RAID5 |
5170 BTRFS_BLOCK_GROUP_DUP)) {
5172 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5181 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5183 struct extent_map *em;
5184 struct map_lookup *map;
5189 em = get_chunk_map(fs_info, chunk_offset, 1);
5193 map = em->map_lookup;
5194 for (i = 0; i < map->num_stripes; i++) {
5195 if (test_bit(BTRFS_DEV_STATE_MISSING,
5196 &map->stripes[i].dev->dev_state)) {
5200 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5201 &map->stripes[i].dev->dev_state)) {
5208 * If the number of missing devices is larger than max errors,
5209 * we can not write the data into that chunk successfully, so
5212 if (miss_ndevs > btrfs_chunk_max_errors(map))
5215 free_extent_map(em);
5219 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5221 extent_map_tree_init(&tree->map_tree);
5224 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5226 struct extent_map *em;
5229 write_lock(&tree->map_tree.lock);
5230 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5232 remove_extent_mapping(&tree->map_tree, em);
5233 write_unlock(&tree->map_tree.lock);
5237 free_extent_map(em);
5238 /* once for the tree */
5239 free_extent_map(em);
5243 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5245 struct extent_map *em;
5246 struct map_lookup *map;
5249 em = get_chunk_map(fs_info, logical, len);
5252 * We could return errors for these cases, but that could get
5253 * ugly and we'd probably do the same thing which is just not do
5254 * anything else and exit, so return 1 so the callers don't try
5255 * to use other copies.
5259 map = em->map_lookup;
5260 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5261 ret = map->num_stripes;
5262 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5263 ret = map->sub_stripes;
5264 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5266 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5268 * There could be two corrupted data stripes, we need
5269 * to loop retry in order to rebuild the correct data.
5271 * Fail a stripe at a time on every retry except the
5272 * stripe under reconstruction.
5274 ret = map->num_stripes;
5277 free_extent_map(em);
5279 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
5280 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5281 fs_info->dev_replace.tgtdev)
5283 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
5288 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5291 struct extent_map *em;
5292 struct map_lookup *map;
5293 unsigned long len = fs_info->sectorsize;
5295 em = get_chunk_map(fs_info, logical, len);
5297 if (!WARN_ON(IS_ERR(em))) {
5298 map = em->map_lookup;
5299 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5300 len = map->stripe_len * nr_data_stripes(map);
5301 free_extent_map(em);
5306 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5308 struct extent_map *em;
5309 struct map_lookup *map;
5312 em = get_chunk_map(fs_info, logical, len);
5314 if(!WARN_ON(IS_ERR(em))) {
5315 map = em->map_lookup;
5316 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5318 free_extent_map(em);
5323 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5324 struct map_lookup *map, int first,
5325 int dev_replace_is_ongoing)
5329 int preferred_mirror;
5331 struct btrfs_device *srcdev;
5334 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5336 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5337 num_stripes = map->sub_stripes;
5339 num_stripes = map->num_stripes;
5341 preferred_mirror = first + current->pid % num_stripes;
5343 if (dev_replace_is_ongoing &&
5344 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5345 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5346 srcdev = fs_info->dev_replace.srcdev;
5351 * try to avoid the drive that is the source drive for a
5352 * dev-replace procedure, only choose it if no other non-missing
5353 * mirror is available
5355 for (tolerance = 0; tolerance < 2; tolerance++) {
5356 if (map->stripes[preferred_mirror].dev->bdev &&
5357 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5358 return preferred_mirror;
5359 for (i = first; i < first + num_stripes; i++) {
5360 if (map->stripes[i].dev->bdev &&
5361 (tolerance || map->stripes[i].dev != srcdev))
5366 /* we couldn't find one that doesn't fail. Just return something
5367 * and the io error handling code will clean up eventually
5369 return preferred_mirror;
5372 static inline int parity_smaller(u64 a, u64 b)
5377 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5378 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5380 struct btrfs_bio_stripe s;
5387 for (i = 0; i < num_stripes - 1; i++) {
5388 if (parity_smaller(bbio->raid_map[i],
5389 bbio->raid_map[i+1])) {
5390 s = bbio->stripes[i];
5391 l = bbio->raid_map[i];
5392 bbio->stripes[i] = bbio->stripes[i+1];
5393 bbio->raid_map[i] = bbio->raid_map[i+1];
5394 bbio->stripes[i+1] = s;
5395 bbio->raid_map[i+1] = l;
5403 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5405 struct btrfs_bio *bbio = kzalloc(
5406 /* the size of the btrfs_bio */
5407 sizeof(struct btrfs_bio) +
5408 /* plus the variable array for the stripes */
5409 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5410 /* plus the variable array for the tgt dev */
5411 sizeof(int) * (real_stripes) +
5413 * plus the raid_map, which includes both the tgt dev
5416 sizeof(u64) * (total_stripes),
5417 GFP_NOFS|__GFP_NOFAIL);
5419 atomic_set(&bbio->error, 0);
5420 refcount_set(&bbio->refs, 1);
5425 void btrfs_get_bbio(struct btrfs_bio *bbio)
5427 WARN_ON(!refcount_read(&bbio->refs));
5428 refcount_inc(&bbio->refs);
5431 void btrfs_put_bbio(struct btrfs_bio *bbio)
5435 if (refcount_dec_and_test(&bbio->refs))
5439 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5441 * Please note that, discard won't be sent to target device of device
5444 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5445 u64 logical, u64 length,
5446 struct btrfs_bio **bbio_ret)
5448 struct extent_map *em;
5449 struct map_lookup *map;
5450 struct btrfs_bio *bbio;
5454 u64 stripe_end_offset;
5461 u32 sub_stripes = 0;
5462 u64 stripes_per_dev = 0;
5463 u32 remaining_stripes = 0;
5464 u32 last_stripe = 0;
5468 /* discard always return a bbio */
5471 em = get_chunk_map(fs_info, logical, length);
5475 map = em->map_lookup;
5476 /* we don't discard raid56 yet */
5477 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5482 offset = logical - em->start;
5483 length = min_t(u64, em->len - offset, length);
5485 stripe_len = map->stripe_len;
5487 * stripe_nr counts the total number of stripes we have to stride
5488 * to get to this block
5490 stripe_nr = div64_u64(offset, stripe_len);
5492 /* stripe_offset is the offset of this block in its stripe */
5493 stripe_offset = offset - stripe_nr * stripe_len;
5495 stripe_nr_end = round_up(offset + length, map->stripe_len);
5496 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5497 stripe_cnt = stripe_nr_end - stripe_nr;
5498 stripe_end_offset = stripe_nr_end * map->stripe_len -
5501 * after this, stripe_nr is the number of stripes on this
5502 * device we have to walk to find the data, and stripe_index is
5503 * the number of our device in the stripe array
5507 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5508 BTRFS_BLOCK_GROUP_RAID10)) {
5509 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5512 sub_stripes = map->sub_stripes;
5514 factor = map->num_stripes / sub_stripes;
5515 num_stripes = min_t(u64, map->num_stripes,
5516 sub_stripes * stripe_cnt);
5517 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5518 stripe_index *= sub_stripes;
5519 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5520 &remaining_stripes);
5521 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5522 last_stripe *= sub_stripes;
5523 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5524 BTRFS_BLOCK_GROUP_DUP)) {
5525 num_stripes = map->num_stripes;
5527 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5531 bbio = alloc_btrfs_bio(num_stripes, 0);
5537 for (i = 0; i < num_stripes; i++) {
5538 bbio->stripes[i].physical =
5539 map->stripes[stripe_index].physical +
5540 stripe_offset + stripe_nr * map->stripe_len;
5541 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5543 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5544 BTRFS_BLOCK_GROUP_RAID10)) {
5545 bbio->stripes[i].length = stripes_per_dev *
5548 if (i / sub_stripes < remaining_stripes)
5549 bbio->stripes[i].length +=
5553 * Special for the first stripe and
5556 * |-------|...|-------|
5560 if (i < sub_stripes)
5561 bbio->stripes[i].length -=
5564 if (stripe_index >= last_stripe &&
5565 stripe_index <= (last_stripe +
5567 bbio->stripes[i].length -=
5570 if (i == sub_stripes - 1)
5573 bbio->stripes[i].length = length;
5577 if (stripe_index == map->num_stripes) {
5584 bbio->map_type = map->type;
5585 bbio->num_stripes = num_stripes;
5587 free_extent_map(em);
5592 * In dev-replace case, for repair case (that's the only case where the mirror
5593 * is selected explicitly when calling btrfs_map_block), blocks left of the
5594 * left cursor can also be read from the target drive.
5596 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5598 * For READ, it also needs to be supported using the same mirror number.
5600 * If the requested block is not left of the left cursor, EIO is returned. This
5601 * can happen because btrfs_num_copies() returns one more in the dev-replace
5604 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5605 u64 logical, u64 length,
5606 u64 srcdev_devid, int *mirror_num,
5609 struct btrfs_bio *bbio = NULL;
5611 int index_srcdev = 0;
5613 u64 physical_of_found = 0;
5617 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5618 logical, &length, &bbio, 0, 0);
5620 ASSERT(bbio == NULL);
5624 num_stripes = bbio->num_stripes;
5625 if (*mirror_num > num_stripes) {
5627 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5628 * that means that the requested area is not left of the left
5631 btrfs_put_bbio(bbio);
5636 * process the rest of the function using the mirror_num of the source
5637 * drive. Therefore look it up first. At the end, patch the device
5638 * pointer to the one of the target drive.
5640 for (i = 0; i < num_stripes; i++) {
5641 if (bbio->stripes[i].dev->devid != srcdev_devid)
5645 * In case of DUP, in order to keep it simple, only add the
5646 * mirror with the lowest physical address
5649 physical_of_found <= bbio->stripes[i].physical)
5654 physical_of_found = bbio->stripes[i].physical;
5657 btrfs_put_bbio(bbio);
5663 *mirror_num = index_srcdev + 1;
5664 *physical = physical_of_found;
5668 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5669 struct btrfs_bio **bbio_ret,
5670 struct btrfs_dev_replace *dev_replace,
5671 int *num_stripes_ret, int *max_errors_ret)
5673 struct btrfs_bio *bbio = *bbio_ret;
5674 u64 srcdev_devid = dev_replace->srcdev->devid;
5675 int tgtdev_indexes = 0;
5676 int num_stripes = *num_stripes_ret;
5677 int max_errors = *max_errors_ret;
5680 if (op == BTRFS_MAP_WRITE) {
5681 int index_where_to_add;
5684 * duplicate the write operations while the dev replace
5685 * procedure is running. Since the copying of the old disk to
5686 * the new disk takes place at run time while the filesystem is
5687 * mounted writable, the regular write operations to the old
5688 * disk have to be duplicated to go to the new disk as well.
5690 * Note that device->missing is handled by the caller, and that
5691 * the write to the old disk is already set up in the stripes
5694 index_where_to_add = num_stripes;
5695 for (i = 0; i < num_stripes; i++) {
5696 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5697 /* write to new disk, too */
5698 struct btrfs_bio_stripe *new =
5699 bbio->stripes + index_where_to_add;
5700 struct btrfs_bio_stripe *old =
5703 new->physical = old->physical;
5704 new->length = old->length;
5705 new->dev = dev_replace->tgtdev;
5706 bbio->tgtdev_map[i] = index_where_to_add;
5707 index_where_to_add++;
5712 num_stripes = index_where_to_add;
5713 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5714 int index_srcdev = 0;
5716 u64 physical_of_found = 0;
5719 * During the dev-replace procedure, the target drive can also
5720 * be used to read data in case it is needed to repair a corrupt
5721 * block elsewhere. This is possible if the requested area is
5722 * left of the left cursor. In this area, the target drive is a
5723 * full copy of the source drive.
5725 for (i = 0; i < num_stripes; i++) {
5726 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5728 * In case of DUP, in order to keep it simple,
5729 * only add the mirror with the lowest physical
5733 physical_of_found <=
5734 bbio->stripes[i].physical)
5738 physical_of_found = bbio->stripes[i].physical;
5742 struct btrfs_bio_stripe *tgtdev_stripe =
5743 bbio->stripes + num_stripes;
5745 tgtdev_stripe->physical = physical_of_found;
5746 tgtdev_stripe->length =
5747 bbio->stripes[index_srcdev].length;
5748 tgtdev_stripe->dev = dev_replace->tgtdev;
5749 bbio->tgtdev_map[index_srcdev] = num_stripes;
5756 *num_stripes_ret = num_stripes;
5757 *max_errors_ret = max_errors;
5758 bbio->num_tgtdevs = tgtdev_indexes;
5762 static bool need_full_stripe(enum btrfs_map_op op)
5764 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5767 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5768 enum btrfs_map_op op,
5769 u64 logical, u64 *length,
5770 struct btrfs_bio **bbio_ret,
5771 int mirror_num, int need_raid_map)
5773 struct extent_map *em;
5774 struct map_lookup *map;
5784 int tgtdev_indexes = 0;
5785 struct btrfs_bio *bbio = NULL;
5786 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5787 int dev_replace_is_ongoing = 0;
5788 int num_alloc_stripes;
5789 int patch_the_first_stripe_for_dev_replace = 0;
5790 u64 physical_to_patch_in_first_stripe = 0;
5791 u64 raid56_full_stripe_start = (u64)-1;
5793 if (op == BTRFS_MAP_DISCARD)
5794 return __btrfs_map_block_for_discard(fs_info, logical,
5797 em = get_chunk_map(fs_info, logical, *length);
5801 map = em->map_lookup;
5802 offset = logical - em->start;
5804 stripe_len = map->stripe_len;
5807 * stripe_nr counts the total number of stripes we have to stride
5808 * to get to this block
5810 stripe_nr = div64_u64(stripe_nr, stripe_len);
5812 stripe_offset = stripe_nr * stripe_len;
5813 if (offset < stripe_offset) {
5815 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5816 stripe_offset, offset, em->start, logical,
5818 free_extent_map(em);
5822 /* stripe_offset is the offset of this block in its stripe*/
5823 stripe_offset = offset - stripe_offset;
5825 /* if we're here for raid56, we need to know the stripe aligned start */
5826 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5827 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5828 raid56_full_stripe_start = offset;
5830 /* allow a write of a full stripe, but make sure we don't
5831 * allow straddling of stripes
5833 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5835 raid56_full_stripe_start *= full_stripe_len;
5838 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5840 /* For writes to RAID[56], allow a full stripeset across all disks.
5841 For other RAID types and for RAID[56] reads, just allow a single
5842 stripe (on a single disk). */
5843 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5844 (op == BTRFS_MAP_WRITE)) {
5845 max_len = stripe_len * nr_data_stripes(map) -
5846 (offset - raid56_full_stripe_start);
5848 /* we limit the length of each bio to what fits in a stripe */
5849 max_len = stripe_len - stripe_offset;
5851 *length = min_t(u64, em->len - offset, max_len);
5853 *length = em->len - offset;
5856 /* This is for when we're called from btrfs_merge_bio_hook() and all
5857 it cares about is the length */
5861 btrfs_dev_replace_read_lock(dev_replace);
5862 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5863 if (!dev_replace_is_ongoing)
5864 btrfs_dev_replace_read_unlock(dev_replace);
5866 btrfs_dev_replace_set_lock_blocking(dev_replace);
5868 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5869 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5870 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5871 dev_replace->srcdev->devid,
5873 &physical_to_patch_in_first_stripe);
5877 patch_the_first_stripe_for_dev_replace = 1;
5878 } else if (mirror_num > map->num_stripes) {
5884 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5885 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5887 if (!need_full_stripe(op))
5889 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5890 if (need_full_stripe(op))
5891 num_stripes = map->num_stripes;
5892 else if (mirror_num)
5893 stripe_index = mirror_num - 1;
5895 stripe_index = find_live_mirror(fs_info, map, 0,
5896 dev_replace_is_ongoing);
5897 mirror_num = stripe_index + 1;
5900 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5901 if (need_full_stripe(op)) {
5902 num_stripes = map->num_stripes;
5903 } else if (mirror_num) {
5904 stripe_index = mirror_num - 1;
5909 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5910 u32 factor = map->num_stripes / map->sub_stripes;
5912 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5913 stripe_index *= map->sub_stripes;
5915 if (need_full_stripe(op))
5916 num_stripes = map->sub_stripes;
5917 else if (mirror_num)
5918 stripe_index += mirror_num - 1;
5920 int old_stripe_index = stripe_index;
5921 stripe_index = find_live_mirror(fs_info, map,
5923 dev_replace_is_ongoing);
5924 mirror_num = stripe_index - old_stripe_index + 1;
5927 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5928 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5929 /* push stripe_nr back to the start of the full stripe */
5930 stripe_nr = div64_u64(raid56_full_stripe_start,
5931 stripe_len * nr_data_stripes(map));
5933 /* RAID[56] write or recovery. Return all stripes */
5934 num_stripes = map->num_stripes;
5935 max_errors = nr_parity_stripes(map);
5937 *length = map->stripe_len;
5942 * Mirror #0 or #1 means the original data block.
5943 * Mirror #2 is RAID5 parity block.
5944 * Mirror #3 is RAID6 Q block.
5946 stripe_nr = div_u64_rem(stripe_nr,
5947 nr_data_stripes(map), &stripe_index);
5949 stripe_index = nr_data_stripes(map) +
5952 /* We distribute the parity blocks across stripes */
5953 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5955 if (!need_full_stripe(op) && mirror_num <= 1)
5960 * after this, stripe_nr is the number of stripes on this
5961 * device we have to walk to find the data, and stripe_index is
5962 * the number of our device in the stripe array
5964 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5966 mirror_num = stripe_index + 1;
5968 if (stripe_index >= map->num_stripes) {
5970 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5971 stripe_index, map->num_stripes);
5976 num_alloc_stripes = num_stripes;
5977 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5978 if (op == BTRFS_MAP_WRITE)
5979 num_alloc_stripes <<= 1;
5980 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5981 num_alloc_stripes++;
5982 tgtdev_indexes = num_stripes;
5985 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5990 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5991 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5993 /* build raid_map */
5994 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5995 (need_full_stripe(op) || mirror_num > 1)) {
5999 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6000 sizeof(struct btrfs_bio_stripe) *
6002 sizeof(int) * tgtdev_indexes);
6004 /* Work out the disk rotation on this stripe-set */
6005 div_u64_rem(stripe_nr, num_stripes, &rot);
6007 /* Fill in the logical address of each stripe */
6008 tmp = stripe_nr * nr_data_stripes(map);
6009 for (i = 0; i < nr_data_stripes(map); i++)
6010 bbio->raid_map[(i+rot) % num_stripes] =
6011 em->start + (tmp + i) * map->stripe_len;
6013 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6014 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6015 bbio->raid_map[(i+rot+1) % num_stripes] =
6020 for (i = 0; i < num_stripes; i++) {
6021 bbio->stripes[i].physical =
6022 map->stripes[stripe_index].physical +
6024 stripe_nr * map->stripe_len;
6025 bbio->stripes[i].dev =
6026 map->stripes[stripe_index].dev;
6030 if (need_full_stripe(op))
6031 max_errors = btrfs_chunk_max_errors(map);
6034 sort_parity_stripes(bbio, num_stripes);
6036 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6037 need_full_stripe(op)) {
6038 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6043 bbio->map_type = map->type;
6044 bbio->num_stripes = num_stripes;
6045 bbio->max_errors = max_errors;
6046 bbio->mirror_num = mirror_num;
6049 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6050 * mirror_num == num_stripes + 1 && dev_replace target drive is
6051 * available as a mirror
6053 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6054 WARN_ON(num_stripes > 1);
6055 bbio->stripes[0].dev = dev_replace->tgtdev;
6056 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6057 bbio->mirror_num = map->num_stripes + 1;
6060 if (dev_replace_is_ongoing) {
6061 btrfs_dev_replace_clear_lock_blocking(dev_replace);
6062 btrfs_dev_replace_read_unlock(dev_replace);
6064 free_extent_map(em);
6068 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6069 u64 logical, u64 *length,
6070 struct btrfs_bio **bbio_ret, int mirror_num)
6072 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6076 /* For Scrub/replace */
6077 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6078 u64 logical, u64 *length,
6079 struct btrfs_bio **bbio_ret)
6081 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6084 int btrfs_rmap_block(struct btrfs_fs_info *fs_info,
6085 u64 chunk_start, u64 physical, u64 devid,
6086 u64 **logical, int *naddrs, int *stripe_len)
6088 struct extent_map *em;
6089 struct map_lookup *map;
6097 em = get_chunk_map(fs_info, chunk_start, 1);
6101 map = em->map_lookup;
6103 rmap_len = map->stripe_len;
6105 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6106 length = div_u64(length, map->num_stripes / map->sub_stripes);
6107 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6108 length = div_u64(length, map->num_stripes);
6109 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6110 length = div_u64(length, nr_data_stripes(map));
6111 rmap_len = map->stripe_len * nr_data_stripes(map);
6114 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6115 BUG_ON(!buf); /* -ENOMEM */
6117 for (i = 0; i < map->num_stripes; i++) {
6118 if (devid && map->stripes[i].dev->devid != devid)
6120 if (map->stripes[i].physical > physical ||
6121 map->stripes[i].physical + length <= physical)
6124 stripe_nr = physical - map->stripes[i].physical;
6125 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6127 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6128 stripe_nr = stripe_nr * map->num_stripes + i;
6129 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6130 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6131 stripe_nr = stripe_nr * map->num_stripes + i;
6132 } /* else if RAID[56], multiply by nr_data_stripes().
6133 * Alternatively, just use rmap_len below instead of
6134 * map->stripe_len */
6136 bytenr = chunk_start + stripe_nr * rmap_len;
6137 WARN_ON(nr >= map->num_stripes);
6138 for (j = 0; j < nr; j++) {
6139 if (buf[j] == bytenr)
6143 WARN_ON(nr >= map->num_stripes);
6150 *stripe_len = rmap_len;
6152 free_extent_map(em);
6156 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6158 bio->bi_private = bbio->private;
6159 bio->bi_end_io = bbio->end_io;
6162 btrfs_put_bbio(bbio);
6165 static void btrfs_end_bio(struct bio *bio)
6167 struct btrfs_bio *bbio = bio->bi_private;
6168 int is_orig_bio = 0;
6170 if (bio->bi_status) {
6171 atomic_inc(&bbio->error);
6172 if (bio->bi_status == BLK_STS_IOERR ||
6173 bio->bi_status == BLK_STS_TARGET) {
6174 unsigned int stripe_index =
6175 btrfs_io_bio(bio)->stripe_index;
6176 struct btrfs_device *dev;
6178 BUG_ON(stripe_index >= bbio->num_stripes);
6179 dev = bbio->stripes[stripe_index].dev;
6181 if (bio_op(bio) == REQ_OP_WRITE)
6182 btrfs_dev_stat_inc_and_print(dev,
6183 BTRFS_DEV_STAT_WRITE_ERRS);
6185 btrfs_dev_stat_inc_and_print(dev,
6186 BTRFS_DEV_STAT_READ_ERRS);
6187 if (bio->bi_opf & REQ_PREFLUSH)
6188 btrfs_dev_stat_inc_and_print(dev,
6189 BTRFS_DEV_STAT_FLUSH_ERRS);
6194 if (bio == bbio->orig_bio)
6197 btrfs_bio_counter_dec(bbio->fs_info);
6199 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6202 bio = bbio->orig_bio;
6205 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6206 /* only send an error to the higher layers if it is
6207 * beyond the tolerance of the btrfs bio
6209 if (atomic_read(&bbio->error) > bbio->max_errors) {
6210 bio->bi_status = BLK_STS_IOERR;
6213 * this bio is actually up to date, we didn't
6214 * go over the max number of errors
6216 bio->bi_status = BLK_STS_OK;
6219 btrfs_end_bbio(bbio, bio);
6220 } else if (!is_orig_bio) {
6226 * see run_scheduled_bios for a description of why bios are collected for
6229 * This will add one bio to the pending list for a device and make sure
6230 * the work struct is scheduled.
6232 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6235 struct btrfs_fs_info *fs_info = device->fs_info;
6236 int should_queue = 1;
6237 struct btrfs_pending_bios *pending_bios;
6239 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state) ||
6245 /* don't bother with additional async steps for reads, right now */
6246 if (bio_op(bio) == REQ_OP_READ) {
6247 btrfsic_submit_bio(bio);
6251 WARN_ON(bio->bi_next);
6252 bio->bi_next = NULL;
6254 spin_lock(&device->io_lock);
6255 if (op_is_sync(bio->bi_opf))
6256 pending_bios = &device->pending_sync_bios;
6258 pending_bios = &device->pending_bios;
6260 if (pending_bios->tail)
6261 pending_bios->tail->bi_next = bio;
6263 pending_bios->tail = bio;
6264 if (!pending_bios->head)
6265 pending_bios->head = bio;
6266 if (device->running_pending)
6269 spin_unlock(&device->io_lock);
6272 btrfs_queue_work(fs_info->submit_workers, &device->work);
6275 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6276 u64 physical, int dev_nr, int async)
6278 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6279 struct btrfs_fs_info *fs_info = bbio->fs_info;
6281 bio->bi_private = bbio;
6282 btrfs_io_bio(bio)->stripe_index = dev_nr;
6283 bio->bi_end_io = btrfs_end_bio;
6284 bio->bi_iter.bi_sector = physical >> 9;
6287 struct rcu_string *name;
6290 name = rcu_dereference(dev->name);
6291 btrfs_debug(fs_info,
6292 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6293 bio_op(bio), bio->bi_opf,
6294 (u64)bio->bi_iter.bi_sector,
6295 (u_long)dev->bdev->bd_dev, name->str, dev->devid,
6296 bio->bi_iter.bi_size);
6300 bio_set_dev(bio, dev->bdev);
6302 btrfs_bio_counter_inc_noblocked(fs_info);
6305 btrfs_schedule_bio(dev, bio);
6307 btrfsic_submit_bio(bio);
6310 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6312 atomic_inc(&bbio->error);
6313 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6314 /* Should be the original bio. */
6315 WARN_ON(bio != bbio->orig_bio);
6317 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6318 bio->bi_iter.bi_sector = logical >> 9;
6319 if (atomic_read(&bbio->error) > bbio->max_errors)
6320 bio->bi_status = BLK_STS_IOERR;
6322 bio->bi_status = BLK_STS_OK;
6323 btrfs_end_bbio(bbio, bio);
6327 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6328 int mirror_num, int async_submit)
6330 struct btrfs_device *dev;
6331 struct bio *first_bio = bio;
6332 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6338 struct btrfs_bio *bbio = NULL;
6340 length = bio->bi_iter.bi_size;
6341 map_length = length;
6343 btrfs_bio_counter_inc_blocked(fs_info);
6344 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6345 &map_length, &bbio, mirror_num, 1);
6347 btrfs_bio_counter_dec(fs_info);
6348 return errno_to_blk_status(ret);
6351 total_devs = bbio->num_stripes;
6352 bbio->orig_bio = first_bio;
6353 bbio->private = first_bio->bi_private;
6354 bbio->end_io = first_bio->bi_end_io;
6355 bbio->fs_info = fs_info;
6356 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6358 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6359 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6360 /* In this case, map_length has been set to the length of
6361 a single stripe; not the whole write */
6362 if (bio_op(bio) == REQ_OP_WRITE) {
6363 ret = raid56_parity_write(fs_info, bio, bbio,
6366 ret = raid56_parity_recover(fs_info, bio, bbio,
6367 map_length, mirror_num, 1);
6370 btrfs_bio_counter_dec(fs_info);
6371 return errno_to_blk_status(ret);
6374 if (map_length < length) {
6376 "mapping failed logical %llu bio len %llu len %llu",
6377 logical, length, map_length);
6381 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6382 dev = bbio->stripes[dev_nr].dev;
6383 if (!dev || !dev->bdev ||
6384 (bio_op(first_bio) == REQ_OP_WRITE &&
6385 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6386 bbio_error(bbio, first_bio, logical);
6390 if (dev_nr < total_devs - 1)
6391 bio = btrfs_bio_clone(first_bio);
6395 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6396 dev_nr, async_submit);
6398 btrfs_bio_counter_dec(fs_info);
6402 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6405 struct btrfs_device *device;
6406 struct btrfs_fs_devices *cur_devices;
6408 cur_devices = fs_info->fs_devices;
6409 while (cur_devices) {
6411 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6412 device = find_device(cur_devices, devid, uuid);
6416 cur_devices = cur_devices->seed;
6421 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6422 u64 devid, u8 *dev_uuid)
6424 struct btrfs_device *device;
6426 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6430 list_add(&device->dev_list, &fs_devices->devices);
6431 device->fs_devices = fs_devices;
6432 fs_devices->num_devices++;
6434 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6435 fs_devices->missing_devices++;
6441 * btrfs_alloc_device - allocate struct btrfs_device
6442 * @fs_info: used only for generating a new devid, can be NULL if
6443 * devid is provided (i.e. @devid != NULL).
6444 * @devid: a pointer to devid for this device. If NULL a new devid
6446 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6449 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6450 * on error. Returned struct is not linked onto any lists and must be
6451 * destroyed with free_device.
6453 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6457 struct btrfs_device *dev;
6460 if (WARN_ON(!devid && !fs_info))
6461 return ERR_PTR(-EINVAL);
6463 dev = __alloc_device();
6472 ret = find_next_devid(fs_info, &tmp);
6475 return ERR_PTR(ret);
6481 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6483 generate_random_uuid(dev->uuid);
6485 btrfs_init_work(&dev->work, btrfs_submit_helper,
6486 pending_bios_fn, NULL, NULL);
6491 /* Return -EIO if any error, otherwise return 0. */
6492 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6493 struct extent_buffer *leaf,
6494 struct btrfs_chunk *chunk, u64 logical)
6502 length = btrfs_chunk_length(leaf, chunk);
6503 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6504 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6505 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6506 type = btrfs_chunk_type(leaf, chunk);
6509 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6513 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6514 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6517 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6518 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6519 btrfs_chunk_sector_size(leaf, chunk));
6522 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6523 btrfs_err(fs_info, "invalid chunk length %llu", length);
6526 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6527 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6531 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6533 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6534 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6535 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6536 btrfs_chunk_type(leaf, chunk));
6539 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6540 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6541 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6542 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6543 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6544 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6545 num_stripes != 1)) {
6547 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6548 num_stripes, sub_stripes,
6549 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6556 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6557 u64 devid, u8 *uuid, bool error)
6560 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6563 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6567 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6568 struct extent_buffer *leaf,
6569 struct btrfs_chunk *chunk)
6571 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6572 struct map_lookup *map;
6573 struct extent_map *em;
6577 u8 uuid[BTRFS_UUID_SIZE];
6582 logical = key->offset;
6583 length = btrfs_chunk_length(leaf, chunk);
6584 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6586 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6590 read_lock(&map_tree->map_tree.lock);
6591 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6592 read_unlock(&map_tree->map_tree.lock);
6594 /* already mapped? */
6595 if (em && em->start <= logical && em->start + em->len > logical) {
6596 free_extent_map(em);
6599 free_extent_map(em);
6602 em = alloc_extent_map();
6605 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6607 free_extent_map(em);
6611 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6612 em->map_lookup = map;
6613 em->start = logical;
6616 em->block_start = 0;
6617 em->block_len = em->len;
6619 map->num_stripes = num_stripes;
6620 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6621 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6622 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6623 map->type = btrfs_chunk_type(leaf, chunk);
6624 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6625 for (i = 0; i < num_stripes; i++) {
6626 map->stripes[i].physical =
6627 btrfs_stripe_offset_nr(leaf, chunk, i);
6628 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6629 read_extent_buffer(leaf, uuid, (unsigned long)
6630 btrfs_stripe_dev_uuid_nr(chunk, i),
6632 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6634 if (!map->stripes[i].dev &&
6635 !btrfs_test_opt(fs_info, DEGRADED)) {
6636 free_extent_map(em);
6637 btrfs_report_missing_device(fs_info, devid, uuid, true);
6640 if (!map->stripes[i].dev) {
6641 map->stripes[i].dev =
6642 add_missing_dev(fs_info->fs_devices, devid,
6644 if (IS_ERR(map->stripes[i].dev)) {
6645 free_extent_map(em);
6647 "failed to init missing dev %llu: %ld",
6648 devid, PTR_ERR(map->stripes[i].dev));
6649 return PTR_ERR(map->stripes[i].dev);
6651 btrfs_report_missing_device(fs_info, devid, uuid, false);
6653 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6654 &(map->stripes[i].dev->dev_state));
6658 write_lock(&map_tree->map_tree.lock);
6659 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6660 write_unlock(&map_tree->map_tree.lock);
6661 BUG_ON(ret); /* Tree corruption */
6662 free_extent_map(em);
6667 static void fill_device_from_item(struct extent_buffer *leaf,
6668 struct btrfs_dev_item *dev_item,
6669 struct btrfs_device *device)
6673 device->devid = btrfs_device_id(leaf, dev_item);
6674 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6675 device->total_bytes = device->disk_total_bytes;
6676 device->commit_total_bytes = device->disk_total_bytes;
6677 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6678 device->commit_bytes_used = device->bytes_used;
6679 device->type = btrfs_device_type(leaf, dev_item);
6680 device->io_align = btrfs_device_io_align(leaf, dev_item);
6681 device->io_width = btrfs_device_io_width(leaf, dev_item);
6682 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6683 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6684 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6686 ptr = btrfs_device_uuid(dev_item);
6687 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6690 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6693 struct btrfs_fs_devices *fs_devices;
6696 lockdep_assert_held(&uuid_mutex);
6699 fs_devices = fs_info->fs_devices->seed;
6700 while (fs_devices) {
6701 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6704 fs_devices = fs_devices->seed;
6707 fs_devices = find_fsid(fsid);
6709 if (!btrfs_test_opt(fs_info, DEGRADED))
6710 return ERR_PTR(-ENOENT);
6712 fs_devices = alloc_fs_devices(fsid);
6713 if (IS_ERR(fs_devices))
6716 fs_devices->seeding = 1;
6717 fs_devices->opened = 1;
6721 fs_devices = clone_fs_devices(fs_devices);
6722 if (IS_ERR(fs_devices))
6725 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6727 free_fs_devices(fs_devices);
6728 fs_devices = ERR_PTR(ret);
6732 if (!fs_devices->seeding) {
6733 close_fs_devices(fs_devices);
6734 free_fs_devices(fs_devices);
6735 fs_devices = ERR_PTR(-EINVAL);
6739 fs_devices->seed = fs_info->fs_devices->seed;
6740 fs_info->fs_devices->seed = fs_devices;
6745 static int read_one_dev(struct btrfs_fs_info *fs_info,
6746 struct extent_buffer *leaf,
6747 struct btrfs_dev_item *dev_item)
6749 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6750 struct btrfs_device *device;
6753 u8 fs_uuid[BTRFS_FSID_SIZE];
6754 u8 dev_uuid[BTRFS_UUID_SIZE];
6756 devid = btrfs_device_id(leaf, dev_item);
6757 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6759 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6762 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6763 fs_devices = open_seed_devices(fs_info, fs_uuid);
6764 if (IS_ERR(fs_devices))
6765 return PTR_ERR(fs_devices);
6768 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6770 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6771 btrfs_report_missing_device(fs_info, devid,
6776 device = add_missing_dev(fs_devices, devid, dev_uuid);
6777 if (IS_ERR(device)) {
6779 "failed to add missing dev %llu: %ld",
6780 devid, PTR_ERR(device));
6781 return PTR_ERR(device);
6783 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6785 if (!device->bdev) {
6786 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6787 btrfs_report_missing_device(fs_info,
6788 devid, dev_uuid, true);
6791 btrfs_report_missing_device(fs_info, devid,
6795 if (!device->bdev &&
6796 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6798 * this happens when a device that was properly setup
6799 * in the device info lists suddenly goes bad.
6800 * device->bdev is NULL, and so we have to set
6801 * device->missing to one here
6803 device->fs_devices->missing_devices++;
6804 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6807 /* Move the device to its own fs_devices */
6808 if (device->fs_devices != fs_devices) {
6809 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6810 &device->dev_state));
6812 list_move(&device->dev_list, &fs_devices->devices);
6813 device->fs_devices->num_devices--;
6814 fs_devices->num_devices++;
6816 device->fs_devices->missing_devices--;
6817 fs_devices->missing_devices++;
6819 device->fs_devices = fs_devices;
6823 if (device->fs_devices != fs_info->fs_devices) {
6824 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6825 if (device->generation !=
6826 btrfs_device_generation(leaf, dev_item))
6830 fill_device_from_item(leaf, dev_item, device);
6831 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6832 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6833 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6834 device->fs_devices->total_rw_bytes += device->total_bytes;
6835 atomic64_add(device->total_bytes - device->bytes_used,
6836 &fs_info->free_chunk_space);
6842 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6844 struct btrfs_root *root = fs_info->tree_root;
6845 struct btrfs_super_block *super_copy = fs_info->super_copy;
6846 struct extent_buffer *sb;
6847 struct btrfs_disk_key *disk_key;
6848 struct btrfs_chunk *chunk;
6850 unsigned long sb_array_offset;
6857 struct btrfs_key key;
6859 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6861 * This will create extent buffer of nodesize, superblock size is
6862 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6863 * overallocate but we can keep it as-is, only the first page is used.
6865 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6868 set_extent_buffer_uptodate(sb);
6869 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6871 * The sb extent buffer is artificial and just used to read the system array.
6872 * set_extent_buffer_uptodate() call does not properly mark all it's
6873 * pages up-to-date when the page is larger: extent does not cover the
6874 * whole page and consequently check_page_uptodate does not find all
6875 * the page's extents up-to-date (the hole beyond sb),
6876 * write_extent_buffer then triggers a WARN_ON.
6878 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6879 * but sb spans only this function. Add an explicit SetPageUptodate call
6880 * to silence the warning eg. on PowerPC 64.
6882 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6883 SetPageUptodate(sb->pages[0]);
6885 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6886 array_size = btrfs_super_sys_array_size(super_copy);
6888 array_ptr = super_copy->sys_chunk_array;
6889 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6892 while (cur_offset < array_size) {
6893 disk_key = (struct btrfs_disk_key *)array_ptr;
6894 len = sizeof(*disk_key);
6895 if (cur_offset + len > array_size)
6896 goto out_short_read;
6898 btrfs_disk_key_to_cpu(&key, disk_key);
6901 sb_array_offset += len;
6904 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6905 chunk = (struct btrfs_chunk *)sb_array_offset;
6907 * At least one btrfs_chunk with one stripe must be
6908 * present, exact stripe count check comes afterwards
6910 len = btrfs_chunk_item_size(1);
6911 if (cur_offset + len > array_size)
6912 goto out_short_read;
6914 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6917 "invalid number of stripes %u in sys_array at offset %u",
6918 num_stripes, cur_offset);
6923 type = btrfs_chunk_type(sb, chunk);
6924 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6926 "invalid chunk type %llu in sys_array at offset %u",
6932 len = btrfs_chunk_item_size(num_stripes);
6933 if (cur_offset + len > array_size)
6934 goto out_short_read;
6936 ret = read_one_chunk(fs_info, &key, sb, chunk);
6941 "unexpected item type %u in sys_array at offset %u",
6942 (u32)key.type, cur_offset);
6947 sb_array_offset += len;
6950 clear_extent_buffer_uptodate(sb);
6951 free_extent_buffer_stale(sb);
6955 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6957 clear_extent_buffer_uptodate(sb);
6958 free_extent_buffer_stale(sb);
6963 * Check if all chunks in the fs are OK for read-write degraded mount
6965 * If the @failing_dev is specified, it's accounted as missing.
6967 * Return true if all chunks meet the minimal RW mount requirements.
6968 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6970 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6971 struct btrfs_device *failing_dev)
6973 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6974 struct extent_map *em;
6978 read_lock(&map_tree->map_tree.lock);
6979 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6980 read_unlock(&map_tree->map_tree.lock);
6981 /* No chunk at all? Return false anyway */
6987 struct map_lookup *map;
6992 map = em->map_lookup;
6994 btrfs_get_num_tolerated_disk_barrier_failures(
6996 for (i = 0; i < map->num_stripes; i++) {
6997 struct btrfs_device *dev = map->stripes[i].dev;
6999 if (!dev || !dev->bdev ||
7000 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7001 dev->last_flush_error)
7003 else if (failing_dev && failing_dev == dev)
7006 if (missing > max_tolerated) {
7009 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
7010 em->start, missing, max_tolerated);
7011 free_extent_map(em);
7015 next_start = extent_map_end(em);
7016 free_extent_map(em);
7018 read_lock(&map_tree->map_tree.lock);
7019 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
7020 (u64)(-1) - next_start);
7021 read_unlock(&map_tree->map_tree.lock);
7027 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7029 struct btrfs_root *root = fs_info->chunk_root;
7030 struct btrfs_path *path;
7031 struct extent_buffer *leaf;
7032 struct btrfs_key key;
7033 struct btrfs_key found_key;
7038 path = btrfs_alloc_path();
7042 mutex_lock(&uuid_mutex);
7043 mutex_lock(&fs_info->chunk_mutex);
7046 * Read all device items, and then all the chunk items. All
7047 * device items are found before any chunk item (their object id
7048 * is smaller than the lowest possible object id for a chunk
7049 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7051 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7054 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7058 leaf = path->nodes[0];
7059 slot = path->slots[0];
7060 if (slot >= btrfs_header_nritems(leaf)) {
7061 ret = btrfs_next_leaf(root, path);
7068 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7069 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7070 struct btrfs_dev_item *dev_item;
7071 dev_item = btrfs_item_ptr(leaf, slot,
7072 struct btrfs_dev_item);
7073 ret = read_one_dev(fs_info, leaf, dev_item);
7077 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7078 struct btrfs_chunk *chunk;
7079 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7080 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
7088 * After loading chunk tree, we've got all device information,
7089 * do another round of validation checks.
7091 if (total_dev != fs_info->fs_devices->total_devices) {
7093 "super_num_devices %llu mismatch with num_devices %llu found here",
7094 btrfs_super_num_devices(fs_info->super_copy),
7099 if (btrfs_super_total_bytes(fs_info->super_copy) <
7100 fs_info->fs_devices->total_rw_bytes) {
7102 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7103 btrfs_super_total_bytes(fs_info->super_copy),
7104 fs_info->fs_devices->total_rw_bytes);
7110 mutex_unlock(&fs_info->chunk_mutex);
7111 mutex_unlock(&uuid_mutex);
7113 btrfs_free_path(path);
7117 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7119 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7120 struct btrfs_device *device;
7122 while (fs_devices) {
7123 mutex_lock(&fs_devices->device_list_mutex);
7124 list_for_each_entry(device, &fs_devices->devices, dev_list)
7125 device->fs_info = fs_info;
7126 mutex_unlock(&fs_devices->device_list_mutex);
7128 fs_devices = fs_devices->seed;
7132 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7136 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7137 btrfs_dev_stat_reset(dev, i);
7140 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7142 struct btrfs_key key;
7143 struct btrfs_key found_key;
7144 struct btrfs_root *dev_root = fs_info->dev_root;
7145 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7146 struct extent_buffer *eb;
7149 struct btrfs_device *device;
7150 struct btrfs_path *path = NULL;
7153 path = btrfs_alloc_path();
7159 mutex_lock(&fs_devices->device_list_mutex);
7160 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7162 struct btrfs_dev_stats_item *ptr;
7164 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7165 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7166 key.offset = device->devid;
7167 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7169 __btrfs_reset_dev_stats(device);
7170 device->dev_stats_valid = 1;
7171 btrfs_release_path(path);
7174 slot = path->slots[0];
7175 eb = path->nodes[0];
7176 btrfs_item_key_to_cpu(eb, &found_key, slot);
7177 item_size = btrfs_item_size_nr(eb, slot);
7179 ptr = btrfs_item_ptr(eb, slot,
7180 struct btrfs_dev_stats_item);
7182 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7183 if (item_size >= (1 + i) * sizeof(__le64))
7184 btrfs_dev_stat_set(device, i,
7185 btrfs_dev_stats_value(eb, ptr, i));
7187 btrfs_dev_stat_reset(device, i);
7190 device->dev_stats_valid = 1;
7191 btrfs_dev_stat_print_on_load(device);
7192 btrfs_release_path(path);
7194 mutex_unlock(&fs_devices->device_list_mutex);
7197 btrfs_free_path(path);
7198 return ret < 0 ? ret : 0;
7201 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7202 struct btrfs_fs_info *fs_info,
7203 struct btrfs_device *device)
7205 struct btrfs_root *dev_root = fs_info->dev_root;
7206 struct btrfs_path *path;
7207 struct btrfs_key key;
7208 struct extent_buffer *eb;
7209 struct btrfs_dev_stats_item *ptr;
7213 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7214 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7215 key.offset = device->devid;
7217 path = btrfs_alloc_path();
7220 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7222 btrfs_warn_in_rcu(fs_info,
7223 "error %d while searching for dev_stats item for device %s",
7224 ret, rcu_str_deref(device->name));
7229 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7230 /* need to delete old one and insert a new one */
7231 ret = btrfs_del_item(trans, dev_root, path);
7233 btrfs_warn_in_rcu(fs_info,
7234 "delete too small dev_stats item for device %s failed %d",
7235 rcu_str_deref(device->name), ret);
7242 /* need to insert a new item */
7243 btrfs_release_path(path);
7244 ret = btrfs_insert_empty_item(trans, dev_root, path,
7245 &key, sizeof(*ptr));
7247 btrfs_warn_in_rcu(fs_info,
7248 "insert dev_stats item for device %s failed %d",
7249 rcu_str_deref(device->name), ret);
7254 eb = path->nodes[0];
7255 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7256 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7257 btrfs_set_dev_stats_value(eb, ptr, i,
7258 btrfs_dev_stat_read(device, i));
7259 btrfs_mark_buffer_dirty(eb);
7262 btrfs_free_path(path);
7267 * called from commit_transaction. Writes all changed device stats to disk.
7269 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7270 struct btrfs_fs_info *fs_info)
7272 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7273 struct btrfs_device *device;
7277 mutex_lock(&fs_devices->device_list_mutex);
7278 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7279 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7280 if (!device->dev_stats_valid || stats_cnt == 0)
7285 * There is a LOAD-LOAD control dependency between the value of
7286 * dev_stats_ccnt and updating the on-disk values which requires
7287 * reading the in-memory counters. Such control dependencies
7288 * require explicit read memory barriers.
7290 * This memory barriers pairs with smp_mb__before_atomic in
7291 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7292 * barrier implied by atomic_xchg in
7293 * btrfs_dev_stats_read_and_reset
7297 ret = update_dev_stat_item(trans, fs_info, device);
7299 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7301 mutex_unlock(&fs_devices->device_list_mutex);
7306 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7308 btrfs_dev_stat_inc(dev, index);
7309 btrfs_dev_stat_print_on_error(dev);
7312 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7314 if (!dev->dev_stats_valid)
7316 btrfs_err_rl_in_rcu(dev->fs_info,
7317 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7318 rcu_str_deref(dev->name),
7319 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7320 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7321 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7322 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7323 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7326 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7330 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7331 if (btrfs_dev_stat_read(dev, i) != 0)
7333 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7334 return; /* all values == 0, suppress message */
7336 btrfs_info_in_rcu(dev->fs_info,
7337 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7338 rcu_str_deref(dev->name),
7339 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7340 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7341 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7342 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7343 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7346 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7347 struct btrfs_ioctl_get_dev_stats *stats)
7349 struct btrfs_device *dev;
7350 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7353 mutex_lock(&fs_devices->device_list_mutex);
7354 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7355 mutex_unlock(&fs_devices->device_list_mutex);
7358 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7360 } else if (!dev->dev_stats_valid) {
7361 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7363 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7364 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7365 if (stats->nr_items > i)
7367 btrfs_dev_stat_read_and_reset(dev, i);
7369 btrfs_dev_stat_reset(dev, i);
7372 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7373 if (stats->nr_items > i)
7374 stats->values[i] = btrfs_dev_stat_read(dev, i);
7376 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7377 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7381 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7383 struct buffer_head *bh;
7384 struct btrfs_super_block *disk_super;
7390 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7393 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7396 disk_super = (struct btrfs_super_block *)bh->b_data;
7398 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7399 set_buffer_dirty(bh);
7400 sync_dirty_buffer(bh);
7404 /* Notify udev that device has changed */
7405 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7407 /* Update ctime/mtime for device path for libblkid */
7408 update_dev_time(device_path);
7412 * Update the size of all devices, which is used for writing out the
7415 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7417 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7418 struct btrfs_device *curr, *next;
7420 if (list_empty(&fs_devices->resized_devices))
7423 mutex_lock(&fs_devices->device_list_mutex);
7424 mutex_lock(&fs_info->chunk_mutex);
7425 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7427 list_del_init(&curr->resized_list);
7428 curr->commit_total_bytes = curr->disk_total_bytes;
7430 mutex_unlock(&fs_info->chunk_mutex);
7431 mutex_unlock(&fs_devices->device_list_mutex);
7434 /* Must be invoked during the transaction commit */
7435 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7437 struct btrfs_fs_info *fs_info = trans->fs_info;
7438 struct extent_map *em;
7439 struct map_lookup *map;
7440 struct btrfs_device *dev;
7443 if (list_empty(&trans->pending_chunks))
7446 /* In order to kick the device replace finish process */
7447 mutex_lock(&fs_info->chunk_mutex);
7448 list_for_each_entry(em, &trans->pending_chunks, list) {
7449 map = em->map_lookup;
7451 for (i = 0; i < map->num_stripes; i++) {
7452 dev = map->stripes[i].dev;
7453 dev->commit_bytes_used = dev->bytes_used;
7456 mutex_unlock(&fs_info->chunk_mutex);
7459 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7461 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7462 while (fs_devices) {
7463 fs_devices->fs_info = fs_info;
7464 fs_devices = fs_devices->seed;
7468 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7470 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7471 while (fs_devices) {
7472 fs_devices->fs_info = NULL;
7473 fs_devices = fs_devices->seed;