1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
8 #include <linux/slab.h>
9 #include <linux/buffer_head.h>
10 #include <linux/blkdev.h>
11 #include <linux/ratelimit.h>
12 #include <linux/kthread.h>
13 #include <linux/raid/pq.h>
14 #include <linux/semaphore.h>
15 #include <linux/uuid.h>
16 #include <linux/list_sort.h>
18 #include "extent_map.h"
20 #include "transaction.h"
21 #include "print-tree.h"
24 #include "async-thread.h"
25 #include "check-integrity.h"
26 #include "rcu-string.h"
28 #include "dev-replace.h"
31 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
32 [BTRFS_RAID_RAID10] = {
35 .devs_max = 0, /* 0 == as many as possible */
37 .tolerated_failures = 1,
41 .raid_name = "raid10",
42 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
43 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
45 [BTRFS_RAID_RAID1] = {
50 .tolerated_failures = 1,
55 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
56 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
63 .tolerated_failures = 0,
68 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
71 [BTRFS_RAID_RAID0] = {
76 .tolerated_failures = 0,
81 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
84 [BTRFS_RAID_SINGLE] = {
89 .tolerated_failures = 0,
93 .raid_name = "single",
97 [BTRFS_RAID_RAID5] = {
102 .tolerated_failures = 1,
106 .raid_name = "raid5",
107 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
108 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
110 [BTRFS_RAID_RAID6] = {
115 .tolerated_failures = 2,
119 .raid_name = "raid6",
120 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
121 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
125 const char *get_raid_name(enum btrfs_raid_types type)
127 if (type >= BTRFS_NR_RAID_TYPES)
130 return btrfs_raid_array[type].raid_name;
133 static int init_first_rw_device(struct btrfs_trans_handle *trans,
134 struct btrfs_fs_info *fs_info);
135 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
136 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
137 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
138 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
139 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
140 enum btrfs_map_op op,
141 u64 logical, u64 *length,
142 struct btrfs_bio **bbio_ret,
143 int mirror_num, int need_raid_map);
149 * There are several mutexes that protect manipulation of devices and low-level
150 * structures like chunks but not block groups, extents or files
152 * uuid_mutex (global lock)
153 * ------------------------
154 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
155 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
156 * device) or requested by the device= mount option
158 * the mutex can be very coarse and can cover long-running operations
160 * protects: updates to fs_devices counters like missing devices, rw devices,
161 * seeding, structure cloning, openning/closing devices at mount/umount time
163 * global::fs_devs - add, remove, updates to the global list
165 * does not protect: manipulation of the fs_devices::devices list!
167 * btrfs_device::name - renames (write side), read is RCU
169 * fs_devices::device_list_mutex (per-fs, with RCU)
170 * ------------------------------------------------
171 * protects updates to fs_devices::devices, ie. adding and deleting
173 * simple list traversal with read-only actions can be done with RCU protection
175 * may be used to exclude some operations from running concurrently without any
176 * modifications to the list (see write_all_supers)
180 * protects balance structures (status, state) and context accessed from
181 * several places (internally, ioctl)
185 * protects chunks, adding or removing during allocation, trim or when a new
186 * device is added/removed
190 * a big lock that is held by the cleaner thread and prevents running subvolume
191 * cleaning together with relocation or delayed iputs
204 * Exclusive operations, BTRFS_FS_EXCL_OP
205 * ======================================
207 * Maintains the exclusivity of the following operations that apply to the
208 * whole filesystem and cannot run in parallel.
213 * - Device replace (*)
216 * The device operations (as above) can be in one of the following states:
222 * Only device operations marked with (*) can go into the Paused state for the
225 * - ioctl (only Balance can be Paused through ioctl)
226 * - filesystem remounted as read-only
227 * - filesystem unmounted and mounted as read-only
228 * - system power-cycle and filesystem mounted as read-only
229 * - filesystem or device errors leading to forced read-only
231 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
232 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
233 * A device operation in Paused or Running state can be canceled or resumed
234 * either by ioctl (Balance only) or when remounted as read-write.
235 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
239 DEFINE_MUTEX(uuid_mutex);
240 static LIST_HEAD(fs_uuids);
241 struct list_head *btrfs_get_fs_uuids(void)
247 * alloc_fs_devices - allocate struct btrfs_fs_devices
248 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
250 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
251 * The returned struct is not linked onto any lists and can be destroyed with
252 * kfree() right away.
254 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
256 struct btrfs_fs_devices *fs_devs;
258 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
260 return ERR_PTR(-ENOMEM);
262 mutex_init(&fs_devs->device_list_mutex);
264 INIT_LIST_HEAD(&fs_devs->devices);
265 INIT_LIST_HEAD(&fs_devs->resized_devices);
266 INIT_LIST_HEAD(&fs_devs->alloc_list);
267 INIT_LIST_HEAD(&fs_devs->fs_list);
269 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
274 void btrfs_free_device(struct btrfs_device *device)
276 rcu_string_free(device->name);
277 bio_put(device->flush_bio);
281 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
283 struct btrfs_device *device;
284 WARN_ON(fs_devices->opened);
285 while (!list_empty(&fs_devices->devices)) {
286 device = list_entry(fs_devices->devices.next,
287 struct btrfs_device, dev_list);
288 list_del(&device->dev_list);
289 btrfs_free_device(device);
294 static void btrfs_kobject_uevent(struct block_device *bdev,
295 enum kobject_action action)
299 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
301 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
303 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
304 &disk_to_dev(bdev->bd_disk)->kobj);
307 void __exit btrfs_cleanup_fs_uuids(void)
309 struct btrfs_fs_devices *fs_devices;
311 while (!list_empty(&fs_uuids)) {
312 fs_devices = list_entry(fs_uuids.next,
313 struct btrfs_fs_devices, fs_list);
314 list_del(&fs_devices->fs_list);
315 free_fs_devices(fs_devices);
320 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
321 * Returned struct is not linked onto any lists and must be destroyed using
324 static struct btrfs_device *__alloc_device(void)
326 struct btrfs_device *dev;
328 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
330 return ERR_PTR(-ENOMEM);
333 * Preallocate a bio that's always going to be used for flushing device
334 * barriers and matches the device lifespan
336 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
337 if (!dev->flush_bio) {
339 return ERR_PTR(-ENOMEM);
342 INIT_LIST_HEAD(&dev->dev_list);
343 INIT_LIST_HEAD(&dev->dev_alloc_list);
344 INIT_LIST_HEAD(&dev->resized_list);
346 spin_lock_init(&dev->io_lock);
348 atomic_set(&dev->reada_in_flight, 0);
349 atomic_set(&dev->dev_stats_ccnt, 0);
350 btrfs_device_data_ordered_init(dev);
351 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
352 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
358 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
361 * If devid and uuid are both specified, the match must be exact, otherwise
362 * only devid is used.
364 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
365 u64 devid, const u8 *uuid)
367 struct btrfs_device *dev;
369 list_for_each_entry(dev, &fs_devices->devices, dev_list) {
370 if (dev->devid == devid &&
371 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
378 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
380 struct btrfs_fs_devices *fs_devices;
382 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
383 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
390 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
391 int flush, struct block_device **bdev,
392 struct buffer_head **bh)
396 *bdev = blkdev_get_by_path(device_path, flags, holder);
399 ret = PTR_ERR(*bdev);
404 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
405 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
407 blkdev_put(*bdev, flags);
410 invalidate_bdev(*bdev);
411 *bh = btrfs_read_dev_super(*bdev);
414 blkdev_put(*bdev, flags);
426 static void requeue_list(struct btrfs_pending_bios *pending_bios,
427 struct bio *head, struct bio *tail)
430 struct bio *old_head;
432 old_head = pending_bios->head;
433 pending_bios->head = head;
434 if (pending_bios->tail)
435 tail->bi_next = old_head;
437 pending_bios->tail = tail;
441 * we try to collect pending bios for a device so we don't get a large
442 * number of procs sending bios down to the same device. This greatly
443 * improves the schedulers ability to collect and merge the bios.
445 * But, it also turns into a long list of bios to process and that is sure
446 * to eventually make the worker thread block. The solution here is to
447 * make some progress and then put this work struct back at the end of
448 * the list if the block device is congested. This way, multiple devices
449 * can make progress from a single worker thread.
451 static noinline void run_scheduled_bios(struct btrfs_device *device)
453 struct btrfs_fs_info *fs_info = device->fs_info;
455 struct backing_dev_info *bdi;
456 struct btrfs_pending_bios *pending_bios;
460 unsigned long num_run;
461 unsigned long batch_run = 0;
462 unsigned long last_waited = 0;
464 int sync_pending = 0;
465 struct blk_plug plug;
468 * this function runs all the bios we've collected for
469 * a particular device. We don't want to wander off to
470 * another device without first sending all of these down.
471 * So, setup a plug here and finish it off before we return
473 blk_start_plug(&plug);
475 bdi = device->bdev->bd_bdi;
478 spin_lock(&device->io_lock);
483 /* take all the bios off the list at once and process them
484 * later on (without the lock held). But, remember the
485 * tail and other pointers so the bios can be properly reinserted
486 * into the list if we hit congestion
488 if (!force_reg && device->pending_sync_bios.head) {
489 pending_bios = &device->pending_sync_bios;
492 pending_bios = &device->pending_bios;
496 pending = pending_bios->head;
497 tail = pending_bios->tail;
498 WARN_ON(pending && !tail);
501 * if pending was null this time around, no bios need processing
502 * at all and we can stop. Otherwise it'll loop back up again
503 * and do an additional check so no bios are missed.
505 * device->running_pending is used to synchronize with the
508 if (device->pending_sync_bios.head == NULL &&
509 device->pending_bios.head == NULL) {
511 device->running_pending = 0;
514 device->running_pending = 1;
517 pending_bios->head = NULL;
518 pending_bios->tail = NULL;
520 spin_unlock(&device->io_lock);
525 /* we want to work on both lists, but do more bios on the
526 * sync list than the regular list
529 pending_bios != &device->pending_sync_bios &&
530 device->pending_sync_bios.head) ||
531 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
532 device->pending_bios.head)) {
533 spin_lock(&device->io_lock);
534 requeue_list(pending_bios, pending, tail);
539 pending = pending->bi_next;
542 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
545 * if we're doing the sync list, record that our
546 * plug has some sync requests on it
548 * If we're doing the regular list and there are
549 * sync requests sitting around, unplug before
552 if (pending_bios == &device->pending_sync_bios) {
554 } else if (sync_pending) {
555 blk_finish_plug(&plug);
556 blk_start_plug(&plug);
560 btrfsic_submit_bio(cur);
567 * we made progress, there is more work to do and the bdi
568 * is now congested. Back off and let other work structs
571 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
572 fs_info->fs_devices->open_devices > 1) {
573 struct io_context *ioc;
575 ioc = current->io_context;
578 * the main goal here is that we don't want to
579 * block if we're going to be able to submit
580 * more requests without blocking.
582 * This code does two great things, it pokes into
583 * the elevator code from a filesystem _and_
584 * it makes assumptions about how batching works.
586 if (ioc && ioc->nr_batch_requests > 0 &&
587 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
589 ioc->last_waited == last_waited)) {
591 * we want to go through our batch of
592 * requests and stop. So, we copy out
593 * the ioc->last_waited time and test
594 * against it before looping
596 last_waited = ioc->last_waited;
600 spin_lock(&device->io_lock);
601 requeue_list(pending_bios, pending, tail);
602 device->running_pending = 1;
604 spin_unlock(&device->io_lock);
605 btrfs_queue_work(fs_info->submit_workers,
615 spin_lock(&device->io_lock);
616 if (device->pending_bios.head || device->pending_sync_bios.head)
618 spin_unlock(&device->io_lock);
621 blk_finish_plug(&plug);
624 static void pending_bios_fn(struct btrfs_work *work)
626 struct btrfs_device *device;
628 device = container_of(work, struct btrfs_device, work);
629 run_scheduled_bios(device);
633 * Search and remove all stale (devices which are not mounted) devices.
634 * When both inputs are NULL, it will search and release all stale devices.
635 * path: Optional. When provided will it release all unmounted devices
636 * matching this path only.
637 * skip_dev: Optional. Will skip this device when searching for the stale
640 static void btrfs_free_stale_devices(const char *path,
641 struct btrfs_device *skip_device)
643 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
644 struct btrfs_device *device, *tmp_device;
646 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
647 mutex_lock(&fs_devices->device_list_mutex);
648 if (fs_devices->opened) {
649 mutex_unlock(&fs_devices->device_list_mutex);
653 list_for_each_entry_safe(device, tmp_device,
654 &fs_devices->devices, dev_list) {
657 if (skip_device && skip_device == device)
659 if (path && !device->name)
664 not_found = strcmp(rcu_str_deref(device->name),
670 /* delete the stale device */
671 fs_devices->num_devices--;
672 list_del(&device->dev_list);
673 btrfs_free_device(device);
675 if (fs_devices->num_devices == 0)
678 mutex_unlock(&fs_devices->device_list_mutex);
679 if (fs_devices->num_devices == 0) {
680 btrfs_sysfs_remove_fsid(fs_devices);
681 list_del(&fs_devices->fs_list);
682 free_fs_devices(fs_devices);
687 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
688 struct btrfs_device *device, fmode_t flags,
691 struct request_queue *q;
692 struct block_device *bdev;
693 struct buffer_head *bh;
694 struct btrfs_super_block *disk_super;
703 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
708 disk_super = (struct btrfs_super_block *)bh->b_data;
709 devid = btrfs_stack_device_id(&disk_super->dev_item);
710 if (devid != device->devid)
713 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
716 device->generation = btrfs_super_generation(disk_super);
718 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
719 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
720 fs_devices->seeding = 1;
722 if (bdev_read_only(bdev))
723 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
725 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
728 q = bdev_get_queue(bdev);
729 if (!blk_queue_nonrot(q))
730 fs_devices->rotating = 1;
733 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
734 device->mode = flags;
736 fs_devices->open_devices++;
737 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
738 device->devid != BTRFS_DEV_REPLACE_DEVID) {
739 fs_devices->rw_devices++;
740 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
748 blkdev_put(bdev, flags);
754 * Add new device to list of registered devices
757 * device pointer which was just added or updated when successful
758 * error pointer when failed
760 static noinline struct btrfs_device *device_list_add(const char *path,
761 struct btrfs_super_block *disk_super,
762 bool *new_device_added)
764 struct btrfs_device *device;
765 struct btrfs_fs_devices *fs_devices;
766 struct rcu_string *name;
767 u64 found_transid = btrfs_super_generation(disk_super);
768 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
770 fs_devices = find_fsid(disk_super->fsid);
772 fs_devices = alloc_fs_devices(disk_super->fsid);
773 if (IS_ERR(fs_devices))
774 return ERR_CAST(fs_devices);
776 mutex_lock(&fs_devices->device_list_mutex);
777 list_add(&fs_devices->fs_list, &fs_uuids);
781 mutex_lock(&fs_devices->device_list_mutex);
782 device = find_device(fs_devices, devid,
783 disk_super->dev_item.uuid);
787 if (fs_devices->opened) {
788 mutex_unlock(&fs_devices->device_list_mutex);
789 return ERR_PTR(-EBUSY);
792 device = btrfs_alloc_device(NULL, &devid,
793 disk_super->dev_item.uuid);
794 if (IS_ERR(device)) {
795 mutex_unlock(&fs_devices->device_list_mutex);
796 /* we can safely leave the fs_devices entry around */
800 name = rcu_string_strdup(path, GFP_NOFS);
802 btrfs_free_device(device);
803 mutex_unlock(&fs_devices->device_list_mutex);
804 return ERR_PTR(-ENOMEM);
806 rcu_assign_pointer(device->name, name);
808 list_add_rcu(&device->dev_list, &fs_devices->devices);
809 fs_devices->num_devices++;
811 device->fs_devices = fs_devices;
812 *new_device_added = true;
814 if (disk_super->label[0])
815 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
816 disk_super->label, devid, found_transid, path);
818 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
819 disk_super->fsid, devid, found_transid, path);
821 } else if (!device->name || strcmp(device->name->str, path)) {
823 * When FS is already mounted.
824 * 1. If you are here and if the device->name is NULL that
825 * means this device was missing at time of FS mount.
826 * 2. If you are here and if the device->name is different
827 * from 'path' that means either
828 * a. The same device disappeared and reappeared with
830 * b. The missing-disk-which-was-replaced, has
833 * We must allow 1 and 2a above. But 2b would be a spurious
836 * Further in case of 1 and 2a above, the disk at 'path'
837 * would have missed some transaction when it was away and
838 * in case of 2a the stale bdev has to be updated as well.
839 * 2b must not be allowed at all time.
843 * For now, we do allow update to btrfs_fs_device through the
844 * btrfs dev scan cli after FS has been mounted. We're still
845 * tracking a problem where systems fail mount by subvolume id
846 * when we reject replacement on a mounted FS.
848 if (!fs_devices->opened && found_transid < device->generation) {
850 * That is if the FS is _not_ mounted and if you
851 * are here, that means there is more than one
852 * disk with same uuid and devid.We keep the one
853 * with larger generation number or the last-in if
854 * generation are equal.
856 mutex_unlock(&fs_devices->device_list_mutex);
857 return ERR_PTR(-EEXIST);
861 * We are going to replace the device path for a given devid,
862 * make sure it's the same device if the device is mounted
865 struct block_device *path_bdev;
867 path_bdev = lookup_bdev(path);
868 if (IS_ERR(path_bdev)) {
869 mutex_unlock(&fs_devices->device_list_mutex);
870 return ERR_CAST(path_bdev);
873 if (device->bdev != path_bdev) {
875 mutex_unlock(&fs_devices->device_list_mutex);
876 btrfs_warn_in_rcu(device->fs_info,
877 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
878 disk_super->fsid, devid,
879 rcu_str_deref(device->name), path);
880 return ERR_PTR(-EEXIST);
883 btrfs_info_in_rcu(device->fs_info,
884 "device fsid %pU devid %llu moved old:%s new:%s",
885 disk_super->fsid, devid,
886 rcu_str_deref(device->name), path);
889 name = rcu_string_strdup(path, GFP_NOFS);
891 mutex_unlock(&fs_devices->device_list_mutex);
892 return ERR_PTR(-ENOMEM);
894 rcu_string_free(device->name);
895 rcu_assign_pointer(device->name, name);
896 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
897 fs_devices->missing_devices--;
898 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
903 * Unmount does not free the btrfs_device struct but would zero
904 * generation along with most of the other members. So just update
905 * it back. We need it to pick the disk with largest generation
908 if (!fs_devices->opened)
909 device->generation = found_transid;
911 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
913 mutex_unlock(&fs_devices->device_list_mutex);
917 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
919 struct btrfs_fs_devices *fs_devices;
920 struct btrfs_device *device;
921 struct btrfs_device *orig_dev;
923 fs_devices = alloc_fs_devices(orig->fsid);
924 if (IS_ERR(fs_devices))
927 mutex_lock(&orig->device_list_mutex);
928 fs_devices->total_devices = orig->total_devices;
930 /* We have held the volume lock, it is safe to get the devices. */
931 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
932 struct rcu_string *name;
934 device = btrfs_alloc_device(NULL, &orig_dev->devid,
940 * This is ok to do without rcu read locked because we hold the
941 * uuid mutex so nothing we touch in here is going to disappear.
943 if (orig_dev->name) {
944 name = rcu_string_strdup(orig_dev->name->str,
947 btrfs_free_device(device);
950 rcu_assign_pointer(device->name, name);
953 list_add(&device->dev_list, &fs_devices->devices);
954 device->fs_devices = fs_devices;
955 fs_devices->num_devices++;
957 mutex_unlock(&orig->device_list_mutex);
960 mutex_unlock(&orig->device_list_mutex);
961 free_fs_devices(fs_devices);
962 return ERR_PTR(-ENOMEM);
966 * After we have read the system tree and know devids belonging to
967 * this filesystem, remove the device which does not belong there.
969 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
971 struct btrfs_device *device, *next;
972 struct btrfs_device *latest_dev = NULL;
974 mutex_lock(&uuid_mutex);
976 /* This is the initialized path, it is safe to release the devices. */
977 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
978 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
979 &device->dev_state)) {
980 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
981 &device->dev_state) &&
983 device->generation > latest_dev->generation)) {
989 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
991 * In the first step, keep the device which has
992 * the correct fsid and the devid that is used
993 * for the dev_replace procedure.
994 * In the second step, the dev_replace state is
995 * read from the device tree and it is known
996 * whether the procedure is really active or
997 * not, which means whether this device is
998 * used or whether it should be removed.
1000 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1001 &device->dev_state)) {
1006 blkdev_put(device->bdev, device->mode);
1007 device->bdev = NULL;
1008 fs_devices->open_devices--;
1010 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1011 list_del_init(&device->dev_alloc_list);
1012 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1013 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1014 &device->dev_state))
1015 fs_devices->rw_devices--;
1017 list_del_init(&device->dev_list);
1018 fs_devices->num_devices--;
1019 btrfs_free_device(device);
1022 if (fs_devices->seed) {
1023 fs_devices = fs_devices->seed;
1027 fs_devices->latest_bdev = latest_dev->bdev;
1029 mutex_unlock(&uuid_mutex);
1032 static void free_device_rcu(struct rcu_head *head)
1034 struct btrfs_device *device;
1036 device = container_of(head, struct btrfs_device, rcu);
1037 btrfs_free_device(device);
1040 static void btrfs_close_bdev(struct btrfs_device *device)
1045 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1046 sync_blockdev(device->bdev);
1047 invalidate_bdev(device->bdev);
1050 blkdev_put(device->bdev, device->mode);
1053 static void btrfs_close_one_device(struct btrfs_device *device)
1055 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1056 struct btrfs_device *new_device;
1057 struct rcu_string *name;
1060 fs_devices->open_devices--;
1062 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1063 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1064 list_del_init(&device->dev_alloc_list);
1065 fs_devices->rw_devices--;
1068 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1069 fs_devices->missing_devices--;
1071 btrfs_close_bdev(device);
1073 new_device = btrfs_alloc_device(NULL, &device->devid,
1075 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1077 /* Safe because we are under uuid_mutex */
1079 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1080 BUG_ON(!name); /* -ENOMEM */
1081 rcu_assign_pointer(new_device->name, name);
1084 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1085 new_device->fs_devices = device->fs_devices;
1087 call_rcu(&device->rcu, free_device_rcu);
1090 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1092 struct btrfs_device *device, *tmp;
1094 if (--fs_devices->opened > 0)
1097 mutex_lock(&fs_devices->device_list_mutex);
1098 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1099 btrfs_close_one_device(device);
1101 mutex_unlock(&fs_devices->device_list_mutex);
1103 WARN_ON(fs_devices->open_devices);
1104 WARN_ON(fs_devices->rw_devices);
1105 fs_devices->opened = 0;
1106 fs_devices->seeding = 0;
1111 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1113 struct btrfs_fs_devices *seed_devices = NULL;
1116 mutex_lock(&uuid_mutex);
1117 ret = close_fs_devices(fs_devices);
1118 if (!fs_devices->opened) {
1119 seed_devices = fs_devices->seed;
1120 fs_devices->seed = NULL;
1122 mutex_unlock(&uuid_mutex);
1124 while (seed_devices) {
1125 fs_devices = seed_devices;
1126 seed_devices = fs_devices->seed;
1127 close_fs_devices(fs_devices);
1128 free_fs_devices(fs_devices);
1133 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1134 fmode_t flags, void *holder)
1136 struct btrfs_device *device;
1137 struct btrfs_device *latest_dev = NULL;
1140 flags |= FMODE_EXCL;
1142 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1143 /* Just open everything we can; ignore failures here */
1144 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1148 device->generation > latest_dev->generation)
1149 latest_dev = device;
1151 if (fs_devices->open_devices == 0) {
1155 fs_devices->opened = 1;
1156 fs_devices->latest_bdev = latest_dev->bdev;
1157 fs_devices->total_rw_bytes = 0;
1162 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1164 struct btrfs_device *dev1, *dev2;
1166 dev1 = list_entry(a, struct btrfs_device, dev_list);
1167 dev2 = list_entry(b, struct btrfs_device, dev_list);
1169 if (dev1->devid < dev2->devid)
1171 else if (dev1->devid > dev2->devid)
1176 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1177 fmode_t flags, void *holder)
1181 lockdep_assert_held(&uuid_mutex);
1183 mutex_lock(&fs_devices->device_list_mutex);
1184 if (fs_devices->opened) {
1185 fs_devices->opened++;
1188 list_sort(NULL, &fs_devices->devices, devid_cmp);
1189 ret = open_fs_devices(fs_devices, flags, holder);
1191 mutex_unlock(&fs_devices->device_list_mutex);
1196 static void btrfs_release_disk_super(struct page *page)
1202 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1204 struct btrfs_super_block **disk_super)
1209 /* make sure our super fits in the device */
1210 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1213 /* make sure our super fits in the page */
1214 if (sizeof(**disk_super) > PAGE_SIZE)
1217 /* make sure our super doesn't straddle pages on disk */
1218 index = bytenr >> PAGE_SHIFT;
1219 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1222 /* pull in the page with our super */
1223 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1226 if (IS_ERR_OR_NULL(*page))
1231 /* align our pointer to the offset of the super block */
1232 *disk_super = p + (bytenr & ~PAGE_MASK);
1234 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1235 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1236 btrfs_release_disk_super(*page);
1240 if ((*disk_super)->label[0] &&
1241 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1242 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1248 * Look for a btrfs signature on a device. This may be called out of the mount path
1249 * and we are not allowed to call set_blocksize during the scan. The superblock
1250 * is read via pagecache
1252 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1255 struct btrfs_super_block *disk_super;
1256 bool new_device_added = false;
1257 struct btrfs_device *device = NULL;
1258 struct block_device *bdev;
1262 lockdep_assert_held(&uuid_mutex);
1265 * we would like to check all the supers, but that would make
1266 * a btrfs mount succeed after a mkfs from a different FS.
1267 * So, we need to add a special mount option to scan for
1268 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1270 bytenr = btrfs_sb_offset(0);
1271 flags |= FMODE_EXCL;
1273 bdev = blkdev_get_by_path(path, flags, holder);
1275 return ERR_CAST(bdev);
1277 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1278 device = ERR_PTR(-EINVAL);
1279 goto error_bdev_put;
1282 device = device_list_add(path, disk_super, &new_device_added);
1283 if (!IS_ERR(device)) {
1284 if (new_device_added)
1285 btrfs_free_stale_devices(path, device);
1288 btrfs_release_disk_super(page);
1291 blkdev_put(bdev, flags);
1296 static int contains_pending_extent(struct btrfs_transaction *transaction,
1297 struct btrfs_device *device,
1298 u64 *start, u64 len)
1300 struct btrfs_fs_info *fs_info = device->fs_info;
1301 struct extent_map *em;
1302 struct list_head *search_list = &fs_info->pinned_chunks;
1304 u64 physical_start = *start;
1307 search_list = &transaction->pending_chunks;
1309 list_for_each_entry(em, search_list, list) {
1310 struct map_lookup *map;
1313 map = em->map_lookup;
1314 for (i = 0; i < map->num_stripes; i++) {
1317 if (map->stripes[i].dev != device)
1319 if (map->stripes[i].physical >= physical_start + len ||
1320 map->stripes[i].physical + em->orig_block_len <=
1324 * Make sure that while processing the pinned list we do
1325 * not override our *start with a lower value, because
1326 * we can have pinned chunks that fall within this
1327 * device hole and that have lower physical addresses
1328 * than the pending chunks we processed before. If we
1329 * do not take this special care we can end up getting
1330 * 2 pending chunks that start at the same physical
1331 * device offsets because the end offset of a pinned
1332 * chunk can be equal to the start offset of some
1335 end = map->stripes[i].physical + em->orig_block_len;
1342 if (search_list != &fs_info->pinned_chunks) {
1343 search_list = &fs_info->pinned_chunks;
1352 * find_free_dev_extent_start - find free space in the specified device
1353 * @device: the device which we search the free space in
1354 * @num_bytes: the size of the free space that we need
1355 * @search_start: the position from which to begin the search
1356 * @start: store the start of the free space.
1357 * @len: the size of the free space. that we find, or the size
1358 * of the max free space if we don't find suitable free space
1360 * this uses a pretty simple search, the expectation is that it is
1361 * called very infrequently and that a given device has a small number
1364 * @start is used to store the start of the free space if we find. But if we
1365 * don't find suitable free space, it will be used to store the start position
1366 * of the max free space.
1368 * @len is used to store the size of the free space that we find.
1369 * But if we don't find suitable free space, it is used to store the size of
1370 * the max free space.
1372 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1373 struct btrfs_device *device, u64 num_bytes,
1374 u64 search_start, u64 *start, u64 *len)
1376 struct btrfs_fs_info *fs_info = device->fs_info;
1377 struct btrfs_root *root = fs_info->dev_root;
1378 struct btrfs_key key;
1379 struct btrfs_dev_extent *dev_extent;
1380 struct btrfs_path *path;
1385 u64 search_end = device->total_bytes;
1388 struct extent_buffer *l;
1391 * We don't want to overwrite the superblock on the drive nor any area
1392 * used by the boot loader (grub for example), so we make sure to start
1393 * at an offset of at least 1MB.
1395 search_start = max_t(u64, search_start, SZ_1M);
1397 path = btrfs_alloc_path();
1401 max_hole_start = search_start;
1405 if (search_start >= search_end ||
1406 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1411 path->reada = READA_FORWARD;
1412 path->search_commit_root = 1;
1413 path->skip_locking = 1;
1415 key.objectid = device->devid;
1416 key.offset = search_start;
1417 key.type = BTRFS_DEV_EXTENT_KEY;
1419 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1423 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1430 slot = path->slots[0];
1431 if (slot >= btrfs_header_nritems(l)) {
1432 ret = btrfs_next_leaf(root, path);
1440 btrfs_item_key_to_cpu(l, &key, slot);
1442 if (key.objectid < device->devid)
1445 if (key.objectid > device->devid)
1448 if (key.type != BTRFS_DEV_EXTENT_KEY)
1451 if (key.offset > search_start) {
1452 hole_size = key.offset - search_start;
1455 * Have to check before we set max_hole_start, otherwise
1456 * we could end up sending back this offset anyway.
1458 if (contains_pending_extent(transaction, device,
1461 if (key.offset >= search_start) {
1462 hole_size = key.offset - search_start;
1469 if (hole_size > max_hole_size) {
1470 max_hole_start = search_start;
1471 max_hole_size = hole_size;
1475 * If this free space is greater than which we need,
1476 * it must be the max free space that we have found
1477 * until now, so max_hole_start must point to the start
1478 * of this free space and the length of this free space
1479 * is stored in max_hole_size. Thus, we return
1480 * max_hole_start and max_hole_size and go back to the
1483 if (hole_size >= num_bytes) {
1489 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1490 extent_end = key.offset + btrfs_dev_extent_length(l,
1492 if (extent_end > search_start)
1493 search_start = extent_end;
1500 * At this point, search_start should be the end of
1501 * allocated dev extents, and when shrinking the device,
1502 * search_end may be smaller than search_start.
1504 if (search_end > search_start) {
1505 hole_size = search_end - search_start;
1507 if (contains_pending_extent(transaction, device, &search_start,
1509 btrfs_release_path(path);
1513 if (hole_size > max_hole_size) {
1514 max_hole_start = search_start;
1515 max_hole_size = hole_size;
1520 if (max_hole_size < num_bytes)
1526 btrfs_free_path(path);
1527 *start = max_hole_start;
1529 *len = max_hole_size;
1533 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1534 struct btrfs_device *device, u64 num_bytes,
1535 u64 *start, u64 *len)
1537 /* FIXME use last free of some kind */
1538 return find_free_dev_extent_start(trans->transaction, device,
1539 num_bytes, 0, start, len);
1542 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1543 struct btrfs_device *device,
1544 u64 start, u64 *dev_extent_len)
1546 struct btrfs_fs_info *fs_info = device->fs_info;
1547 struct btrfs_root *root = fs_info->dev_root;
1549 struct btrfs_path *path;
1550 struct btrfs_key key;
1551 struct btrfs_key found_key;
1552 struct extent_buffer *leaf = NULL;
1553 struct btrfs_dev_extent *extent = NULL;
1555 path = btrfs_alloc_path();
1559 key.objectid = device->devid;
1561 key.type = BTRFS_DEV_EXTENT_KEY;
1563 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1565 ret = btrfs_previous_item(root, path, key.objectid,
1566 BTRFS_DEV_EXTENT_KEY);
1569 leaf = path->nodes[0];
1570 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1571 extent = btrfs_item_ptr(leaf, path->slots[0],
1572 struct btrfs_dev_extent);
1573 BUG_ON(found_key.offset > start || found_key.offset +
1574 btrfs_dev_extent_length(leaf, extent) < start);
1576 btrfs_release_path(path);
1578 } else if (ret == 0) {
1579 leaf = path->nodes[0];
1580 extent = btrfs_item_ptr(leaf, path->slots[0],
1581 struct btrfs_dev_extent);
1583 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1587 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1589 ret = btrfs_del_item(trans, root, path);
1591 btrfs_handle_fs_error(fs_info, ret,
1592 "Failed to remove dev extent item");
1594 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1597 btrfs_free_path(path);
1601 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1602 struct btrfs_device *device,
1603 u64 chunk_offset, u64 start, u64 num_bytes)
1606 struct btrfs_path *path;
1607 struct btrfs_fs_info *fs_info = device->fs_info;
1608 struct btrfs_root *root = fs_info->dev_root;
1609 struct btrfs_dev_extent *extent;
1610 struct extent_buffer *leaf;
1611 struct btrfs_key key;
1613 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1614 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1615 path = btrfs_alloc_path();
1619 key.objectid = device->devid;
1621 key.type = BTRFS_DEV_EXTENT_KEY;
1622 ret = btrfs_insert_empty_item(trans, root, path, &key,
1627 leaf = path->nodes[0];
1628 extent = btrfs_item_ptr(leaf, path->slots[0],
1629 struct btrfs_dev_extent);
1630 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1631 BTRFS_CHUNK_TREE_OBJECTID);
1632 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1633 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1634 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1636 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1637 btrfs_mark_buffer_dirty(leaf);
1639 btrfs_free_path(path);
1643 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1645 struct extent_map_tree *em_tree;
1646 struct extent_map *em;
1650 em_tree = &fs_info->mapping_tree.map_tree;
1651 read_lock(&em_tree->lock);
1652 n = rb_last(&em_tree->map.rb_root);
1654 em = rb_entry(n, struct extent_map, rb_node);
1655 ret = em->start + em->len;
1657 read_unlock(&em_tree->lock);
1662 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1666 struct btrfs_key key;
1667 struct btrfs_key found_key;
1668 struct btrfs_path *path;
1670 path = btrfs_alloc_path();
1674 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1675 key.type = BTRFS_DEV_ITEM_KEY;
1676 key.offset = (u64)-1;
1678 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1682 BUG_ON(ret == 0); /* Corruption */
1684 ret = btrfs_previous_item(fs_info->chunk_root, path,
1685 BTRFS_DEV_ITEMS_OBJECTID,
1686 BTRFS_DEV_ITEM_KEY);
1690 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1692 *devid_ret = found_key.offset + 1;
1696 btrfs_free_path(path);
1701 * the device information is stored in the chunk root
1702 * the btrfs_device struct should be fully filled in
1704 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1705 struct btrfs_device *device)
1708 struct btrfs_path *path;
1709 struct btrfs_dev_item *dev_item;
1710 struct extent_buffer *leaf;
1711 struct btrfs_key key;
1714 path = btrfs_alloc_path();
1718 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1719 key.type = BTRFS_DEV_ITEM_KEY;
1720 key.offset = device->devid;
1722 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1723 &key, sizeof(*dev_item));
1727 leaf = path->nodes[0];
1728 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1730 btrfs_set_device_id(leaf, dev_item, device->devid);
1731 btrfs_set_device_generation(leaf, dev_item, 0);
1732 btrfs_set_device_type(leaf, dev_item, device->type);
1733 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1734 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1735 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1736 btrfs_set_device_total_bytes(leaf, dev_item,
1737 btrfs_device_get_disk_total_bytes(device));
1738 btrfs_set_device_bytes_used(leaf, dev_item,
1739 btrfs_device_get_bytes_used(device));
1740 btrfs_set_device_group(leaf, dev_item, 0);
1741 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1742 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1743 btrfs_set_device_start_offset(leaf, dev_item, 0);
1745 ptr = btrfs_device_uuid(dev_item);
1746 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1747 ptr = btrfs_device_fsid(dev_item);
1748 write_extent_buffer(leaf, trans->fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1749 btrfs_mark_buffer_dirty(leaf);
1753 btrfs_free_path(path);
1758 * Function to update ctime/mtime for a given device path.
1759 * Mainly used for ctime/mtime based probe like libblkid.
1761 static void update_dev_time(const char *path_name)
1765 filp = filp_open(path_name, O_RDWR, 0);
1768 file_update_time(filp);
1769 filp_close(filp, NULL);
1772 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1773 struct btrfs_device *device)
1775 struct btrfs_root *root = fs_info->chunk_root;
1777 struct btrfs_path *path;
1778 struct btrfs_key key;
1779 struct btrfs_trans_handle *trans;
1781 path = btrfs_alloc_path();
1785 trans = btrfs_start_transaction(root, 0);
1786 if (IS_ERR(trans)) {
1787 btrfs_free_path(path);
1788 return PTR_ERR(trans);
1790 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1791 key.type = BTRFS_DEV_ITEM_KEY;
1792 key.offset = device->devid;
1794 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1798 btrfs_abort_transaction(trans, ret);
1799 btrfs_end_transaction(trans);
1803 ret = btrfs_del_item(trans, root, path);
1805 btrfs_abort_transaction(trans, ret);
1806 btrfs_end_transaction(trans);
1810 btrfs_free_path(path);
1812 ret = btrfs_commit_transaction(trans);
1817 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1818 * filesystem. It's up to the caller to adjust that number regarding eg. device
1821 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1829 seq = read_seqbegin(&fs_info->profiles_lock);
1831 all_avail = fs_info->avail_data_alloc_bits |
1832 fs_info->avail_system_alloc_bits |
1833 fs_info->avail_metadata_alloc_bits;
1834 } while (read_seqretry(&fs_info->profiles_lock, seq));
1836 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1837 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1840 if (num_devices < btrfs_raid_array[i].devs_min) {
1841 int ret = btrfs_raid_array[i].mindev_error;
1851 static struct btrfs_device * btrfs_find_next_active_device(
1852 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1854 struct btrfs_device *next_device;
1856 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1857 if (next_device != device &&
1858 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1859 && next_device->bdev)
1867 * Helper function to check if the given device is part of s_bdev / latest_bdev
1868 * and replace it with the provided or the next active device, in the context
1869 * where this function called, there should be always be another device (or
1870 * this_dev) which is active.
1872 void btrfs_assign_next_active_device(struct btrfs_device *device,
1873 struct btrfs_device *this_dev)
1875 struct btrfs_fs_info *fs_info = device->fs_info;
1876 struct btrfs_device *next_device;
1879 next_device = this_dev;
1881 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1883 ASSERT(next_device);
1885 if (fs_info->sb->s_bdev &&
1886 (fs_info->sb->s_bdev == device->bdev))
1887 fs_info->sb->s_bdev = next_device->bdev;
1889 if (fs_info->fs_devices->latest_bdev == device->bdev)
1890 fs_info->fs_devices->latest_bdev = next_device->bdev;
1894 * Return btrfs_fs_devices::num_devices excluding the device that's being
1895 * currently replaced.
1897 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1899 u64 num_devices = fs_info->fs_devices->num_devices;
1901 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1902 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1903 ASSERT(num_devices > 1);
1906 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1911 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1914 struct btrfs_device *device;
1915 struct btrfs_fs_devices *cur_devices;
1916 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1920 mutex_lock(&uuid_mutex);
1922 num_devices = btrfs_num_devices(fs_info);
1924 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1928 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
1930 if (IS_ERR(device)) {
1931 if (PTR_ERR(device) == -ENOENT &&
1932 strcmp(device_path, "missing") == 0)
1933 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1935 ret = PTR_ERR(device);
1939 if (btrfs_pinned_by_swapfile(fs_info, device)) {
1940 btrfs_warn_in_rcu(fs_info,
1941 "cannot remove device %s (devid %llu) due to active swapfile",
1942 rcu_str_deref(device->name), device->devid);
1947 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1948 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1952 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1953 fs_info->fs_devices->rw_devices == 1) {
1954 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1958 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1959 mutex_lock(&fs_info->chunk_mutex);
1960 list_del_init(&device->dev_alloc_list);
1961 device->fs_devices->rw_devices--;
1962 mutex_unlock(&fs_info->chunk_mutex);
1965 mutex_unlock(&uuid_mutex);
1966 ret = btrfs_shrink_device(device, 0);
1967 mutex_lock(&uuid_mutex);
1972 * TODO: the superblock still includes this device in its num_devices
1973 * counter although write_all_supers() is not locked out. This
1974 * could give a filesystem state which requires a degraded mount.
1976 ret = btrfs_rm_dev_item(fs_info, device);
1980 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
1981 btrfs_scrub_cancel_dev(fs_info, device);
1984 * the device list mutex makes sure that we don't change
1985 * the device list while someone else is writing out all
1986 * the device supers. Whoever is writing all supers, should
1987 * lock the device list mutex before getting the number of
1988 * devices in the super block (super_copy). Conversely,
1989 * whoever updates the number of devices in the super block
1990 * (super_copy) should hold the device list mutex.
1994 * In normal cases the cur_devices == fs_devices. But in case
1995 * of deleting a seed device, the cur_devices should point to
1996 * its own fs_devices listed under the fs_devices->seed.
1998 cur_devices = device->fs_devices;
1999 mutex_lock(&fs_devices->device_list_mutex);
2000 list_del_rcu(&device->dev_list);
2002 cur_devices->num_devices--;
2003 cur_devices->total_devices--;
2004 /* Update total_devices of the parent fs_devices if it's seed */
2005 if (cur_devices != fs_devices)
2006 fs_devices->total_devices--;
2008 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2009 cur_devices->missing_devices--;
2011 btrfs_assign_next_active_device(device, NULL);
2014 cur_devices->open_devices--;
2015 /* remove sysfs entry */
2016 btrfs_sysfs_rm_device_link(fs_devices, device);
2019 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2020 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2021 mutex_unlock(&fs_devices->device_list_mutex);
2024 * at this point, the device is zero sized and detached from
2025 * the devices list. All that's left is to zero out the old
2026 * supers and free the device.
2028 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2029 btrfs_scratch_superblocks(device->bdev, device->name->str);
2031 btrfs_close_bdev(device);
2032 call_rcu(&device->rcu, free_device_rcu);
2034 if (cur_devices->open_devices == 0) {
2035 while (fs_devices) {
2036 if (fs_devices->seed == cur_devices) {
2037 fs_devices->seed = cur_devices->seed;
2040 fs_devices = fs_devices->seed;
2042 cur_devices->seed = NULL;
2043 close_fs_devices(cur_devices);
2044 free_fs_devices(cur_devices);
2048 mutex_unlock(&uuid_mutex);
2052 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2053 mutex_lock(&fs_info->chunk_mutex);
2054 list_add(&device->dev_alloc_list,
2055 &fs_devices->alloc_list);
2056 device->fs_devices->rw_devices++;
2057 mutex_unlock(&fs_info->chunk_mutex);
2062 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2064 struct btrfs_fs_devices *fs_devices;
2066 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2069 * in case of fs with no seed, srcdev->fs_devices will point
2070 * to fs_devices of fs_info. However when the dev being replaced is
2071 * a seed dev it will point to the seed's local fs_devices. In short
2072 * srcdev will have its correct fs_devices in both the cases.
2074 fs_devices = srcdev->fs_devices;
2076 list_del_rcu(&srcdev->dev_list);
2077 list_del(&srcdev->dev_alloc_list);
2078 fs_devices->num_devices--;
2079 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2080 fs_devices->missing_devices--;
2082 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2083 fs_devices->rw_devices--;
2086 fs_devices->open_devices--;
2089 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2090 struct btrfs_device *srcdev)
2092 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2094 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2095 /* zero out the old super if it is writable */
2096 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2099 btrfs_close_bdev(srcdev);
2100 call_rcu(&srcdev->rcu, free_device_rcu);
2102 /* if this is no devs we rather delete the fs_devices */
2103 if (!fs_devices->num_devices) {
2104 struct btrfs_fs_devices *tmp_fs_devices;
2107 * On a mounted FS, num_devices can't be zero unless it's a
2108 * seed. In case of a seed device being replaced, the replace
2109 * target added to the sprout FS, so there will be no more
2110 * device left under the seed FS.
2112 ASSERT(fs_devices->seeding);
2114 tmp_fs_devices = fs_info->fs_devices;
2115 while (tmp_fs_devices) {
2116 if (tmp_fs_devices->seed == fs_devices) {
2117 tmp_fs_devices->seed = fs_devices->seed;
2120 tmp_fs_devices = tmp_fs_devices->seed;
2122 fs_devices->seed = NULL;
2123 close_fs_devices(fs_devices);
2124 free_fs_devices(fs_devices);
2128 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2130 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2133 mutex_lock(&fs_devices->device_list_mutex);
2135 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2138 fs_devices->open_devices--;
2140 fs_devices->num_devices--;
2142 btrfs_assign_next_active_device(tgtdev, NULL);
2144 list_del_rcu(&tgtdev->dev_list);
2146 mutex_unlock(&fs_devices->device_list_mutex);
2149 * The update_dev_time() with in btrfs_scratch_superblocks()
2150 * may lead to a call to btrfs_show_devname() which will try
2151 * to hold device_list_mutex. And here this device
2152 * is already out of device list, so we don't have to hold
2153 * the device_list_mutex lock.
2155 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2157 btrfs_close_bdev(tgtdev);
2158 call_rcu(&tgtdev->rcu, free_device_rcu);
2161 static struct btrfs_device *btrfs_find_device_by_path(
2162 struct btrfs_fs_info *fs_info, const char *device_path)
2165 struct btrfs_super_block *disk_super;
2168 struct block_device *bdev;
2169 struct buffer_head *bh;
2170 struct btrfs_device *device;
2172 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2173 fs_info->bdev_holder, 0, &bdev, &bh);
2175 return ERR_PTR(ret);
2176 disk_super = (struct btrfs_super_block *)bh->b_data;
2177 devid = btrfs_stack_device_id(&disk_super->dev_item);
2178 dev_uuid = disk_super->dev_item.uuid;
2179 device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2182 device = ERR_PTR(-ENOENT);
2183 blkdev_put(bdev, FMODE_READ);
2187 static struct btrfs_device *btrfs_find_device_missing_or_by_path(
2188 struct btrfs_fs_info *fs_info, const char *device_path)
2190 struct btrfs_device *device = NULL;
2191 if (strcmp(device_path, "missing") == 0) {
2192 struct list_head *devices;
2193 struct btrfs_device *tmp;
2195 devices = &fs_info->fs_devices->devices;
2196 list_for_each_entry(tmp, devices, dev_list) {
2197 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2198 &tmp->dev_state) && !tmp->bdev) {
2205 return ERR_PTR(-ENOENT);
2207 device = btrfs_find_device_by_path(fs_info, device_path);
2214 * Lookup a device given by device id, or the path if the id is 0.
2216 struct btrfs_device *btrfs_find_device_by_devspec(
2217 struct btrfs_fs_info *fs_info, u64 devid, const char *devpath)
2219 struct btrfs_device *device;
2222 device = btrfs_find_device(fs_info, devid, NULL, NULL);
2224 return ERR_PTR(-ENOENT);
2226 if (!devpath || !devpath[0])
2227 return ERR_PTR(-EINVAL);
2228 device = btrfs_find_device_missing_or_by_path(fs_info, devpath);
2234 * does all the dirty work required for changing file system's UUID.
2236 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2238 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2239 struct btrfs_fs_devices *old_devices;
2240 struct btrfs_fs_devices *seed_devices;
2241 struct btrfs_super_block *disk_super = fs_info->super_copy;
2242 struct btrfs_device *device;
2245 lockdep_assert_held(&uuid_mutex);
2246 if (!fs_devices->seeding)
2249 seed_devices = alloc_fs_devices(NULL);
2250 if (IS_ERR(seed_devices))
2251 return PTR_ERR(seed_devices);
2253 old_devices = clone_fs_devices(fs_devices);
2254 if (IS_ERR(old_devices)) {
2255 kfree(seed_devices);
2256 return PTR_ERR(old_devices);
2259 list_add(&old_devices->fs_list, &fs_uuids);
2261 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2262 seed_devices->opened = 1;
2263 INIT_LIST_HEAD(&seed_devices->devices);
2264 INIT_LIST_HEAD(&seed_devices->alloc_list);
2265 mutex_init(&seed_devices->device_list_mutex);
2267 mutex_lock(&fs_devices->device_list_mutex);
2268 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2270 list_for_each_entry(device, &seed_devices->devices, dev_list)
2271 device->fs_devices = seed_devices;
2273 mutex_lock(&fs_info->chunk_mutex);
2274 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2275 mutex_unlock(&fs_info->chunk_mutex);
2277 fs_devices->seeding = 0;
2278 fs_devices->num_devices = 0;
2279 fs_devices->open_devices = 0;
2280 fs_devices->missing_devices = 0;
2281 fs_devices->rotating = 0;
2282 fs_devices->seed = seed_devices;
2284 generate_random_uuid(fs_devices->fsid);
2285 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2286 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2287 mutex_unlock(&fs_devices->device_list_mutex);
2289 super_flags = btrfs_super_flags(disk_super) &
2290 ~BTRFS_SUPER_FLAG_SEEDING;
2291 btrfs_set_super_flags(disk_super, super_flags);
2297 * Store the expected generation for seed devices in device items.
2299 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2300 struct btrfs_fs_info *fs_info)
2302 struct btrfs_root *root = fs_info->chunk_root;
2303 struct btrfs_path *path;
2304 struct extent_buffer *leaf;
2305 struct btrfs_dev_item *dev_item;
2306 struct btrfs_device *device;
2307 struct btrfs_key key;
2308 u8 fs_uuid[BTRFS_FSID_SIZE];
2309 u8 dev_uuid[BTRFS_UUID_SIZE];
2313 path = btrfs_alloc_path();
2317 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2319 key.type = BTRFS_DEV_ITEM_KEY;
2322 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2326 leaf = path->nodes[0];
2328 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2329 ret = btrfs_next_leaf(root, path);
2334 leaf = path->nodes[0];
2335 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2336 btrfs_release_path(path);
2340 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2341 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2342 key.type != BTRFS_DEV_ITEM_KEY)
2345 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2346 struct btrfs_dev_item);
2347 devid = btrfs_device_id(leaf, dev_item);
2348 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2350 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2352 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2353 BUG_ON(!device); /* Logic error */
2355 if (device->fs_devices->seeding) {
2356 btrfs_set_device_generation(leaf, dev_item,
2357 device->generation);
2358 btrfs_mark_buffer_dirty(leaf);
2366 btrfs_free_path(path);
2370 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2372 struct btrfs_root *root = fs_info->dev_root;
2373 struct request_queue *q;
2374 struct btrfs_trans_handle *trans;
2375 struct btrfs_device *device;
2376 struct block_device *bdev;
2377 struct super_block *sb = fs_info->sb;
2378 struct rcu_string *name;
2379 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2380 u64 orig_super_total_bytes;
2381 u64 orig_super_num_devices;
2382 int seeding_dev = 0;
2384 bool unlocked = false;
2386 if (sb_rdonly(sb) && !fs_devices->seeding)
2389 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2390 fs_info->bdev_holder);
2392 return PTR_ERR(bdev);
2394 if (fs_devices->seeding) {
2396 down_write(&sb->s_umount);
2397 mutex_lock(&uuid_mutex);
2400 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2402 mutex_lock(&fs_devices->device_list_mutex);
2403 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2404 if (device->bdev == bdev) {
2407 &fs_devices->device_list_mutex);
2411 mutex_unlock(&fs_devices->device_list_mutex);
2413 device = btrfs_alloc_device(fs_info, NULL, NULL);
2414 if (IS_ERR(device)) {
2415 /* we can safely leave the fs_devices entry around */
2416 ret = PTR_ERR(device);
2420 name = rcu_string_strdup(device_path, GFP_KERNEL);
2423 goto error_free_device;
2425 rcu_assign_pointer(device->name, name);
2427 trans = btrfs_start_transaction(root, 0);
2428 if (IS_ERR(trans)) {
2429 ret = PTR_ERR(trans);
2430 goto error_free_device;
2433 q = bdev_get_queue(bdev);
2434 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2435 device->generation = trans->transid;
2436 device->io_width = fs_info->sectorsize;
2437 device->io_align = fs_info->sectorsize;
2438 device->sector_size = fs_info->sectorsize;
2439 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2440 fs_info->sectorsize);
2441 device->disk_total_bytes = device->total_bytes;
2442 device->commit_total_bytes = device->total_bytes;
2443 device->fs_info = fs_info;
2444 device->bdev = bdev;
2445 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2446 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2447 device->mode = FMODE_EXCL;
2448 device->dev_stats_valid = 1;
2449 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2452 sb->s_flags &= ~SB_RDONLY;
2453 ret = btrfs_prepare_sprout(fs_info);
2455 btrfs_abort_transaction(trans, ret);
2460 device->fs_devices = fs_devices;
2462 mutex_lock(&fs_devices->device_list_mutex);
2463 mutex_lock(&fs_info->chunk_mutex);
2464 list_add_rcu(&device->dev_list, &fs_devices->devices);
2465 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2466 fs_devices->num_devices++;
2467 fs_devices->open_devices++;
2468 fs_devices->rw_devices++;
2469 fs_devices->total_devices++;
2470 fs_devices->total_rw_bytes += device->total_bytes;
2472 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2474 if (!blk_queue_nonrot(q))
2475 fs_devices->rotating = 1;
2477 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2478 btrfs_set_super_total_bytes(fs_info->super_copy,
2479 round_down(orig_super_total_bytes + device->total_bytes,
2480 fs_info->sectorsize));
2482 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2483 btrfs_set_super_num_devices(fs_info->super_copy,
2484 orig_super_num_devices + 1);
2486 /* add sysfs device entry */
2487 btrfs_sysfs_add_device_link(fs_devices, device);
2490 * we've got more storage, clear any full flags on the space
2493 btrfs_clear_space_info_full(fs_info);
2495 mutex_unlock(&fs_info->chunk_mutex);
2496 mutex_unlock(&fs_devices->device_list_mutex);
2499 mutex_lock(&fs_info->chunk_mutex);
2500 ret = init_first_rw_device(trans, fs_info);
2501 mutex_unlock(&fs_info->chunk_mutex);
2503 btrfs_abort_transaction(trans, ret);
2508 ret = btrfs_add_dev_item(trans, device);
2510 btrfs_abort_transaction(trans, ret);
2515 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2517 ret = btrfs_finish_sprout(trans, fs_info);
2519 btrfs_abort_transaction(trans, ret);
2523 /* Sprouting would change fsid of the mounted root,
2524 * so rename the fsid on the sysfs
2526 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2528 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2530 "sysfs: failed to create fsid for sprout");
2533 ret = btrfs_commit_transaction(trans);
2536 mutex_unlock(&uuid_mutex);
2537 up_write(&sb->s_umount);
2540 if (ret) /* transaction commit */
2543 ret = btrfs_relocate_sys_chunks(fs_info);
2545 btrfs_handle_fs_error(fs_info, ret,
2546 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2547 trans = btrfs_attach_transaction(root);
2548 if (IS_ERR(trans)) {
2549 if (PTR_ERR(trans) == -ENOENT)
2551 ret = PTR_ERR(trans);
2555 ret = btrfs_commit_transaction(trans);
2558 /* Update ctime/mtime for libblkid */
2559 update_dev_time(device_path);
2563 btrfs_sysfs_rm_device_link(fs_devices, device);
2564 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2565 mutex_lock(&fs_info->chunk_mutex);
2566 list_del_rcu(&device->dev_list);
2567 list_del(&device->dev_alloc_list);
2568 fs_info->fs_devices->num_devices--;
2569 fs_info->fs_devices->open_devices--;
2570 fs_info->fs_devices->rw_devices--;
2571 fs_info->fs_devices->total_devices--;
2572 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2573 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2574 btrfs_set_super_total_bytes(fs_info->super_copy,
2575 orig_super_total_bytes);
2576 btrfs_set_super_num_devices(fs_info->super_copy,
2577 orig_super_num_devices);
2578 mutex_unlock(&fs_info->chunk_mutex);
2579 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2582 sb->s_flags |= SB_RDONLY;
2584 btrfs_end_transaction(trans);
2586 btrfs_free_device(device);
2588 blkdev_put(bdev, FMODE_EXCL);
2589 if (seeding_dev && !unlocked) {
2590 mutex_unlock(&uuid_mutex);
2591 up_write(&sb->s_umount);
2596 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2597 struct btrfs_device *device)
2600 struct btrfs_path *path;
2601 struct btrfs_root *root = device->fs_info->chunk_root;
2602 struct btrfs_dev_item *dev_item;
2603 struct extent_buffer *leaf;
2604 struct btrfs_key key;
2606 path = btrfs_alloc_path();
2610 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2611 key.type = BTRFS_DEV_ITEM_KEY;
2612 key.offset = device->devid;
2614 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2623 leaf = path->nodes[0];
2624 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2626 btrfs_set_device_id(leaf, dev_item, device->devid);
2627 btrfs_set_device_type(leaf, dev_item, device->type);
2628 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2629 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2630 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2631 btrfs_set_device_total_bytes(leaf, dev_item,
2632 btrfs_device_get_disk_total_bytes(device));
2633 btrfs_set_device_bytes_used(leaf, dev_item,
2634 btrfs_device_get_bytes_used(device));
2635 btrfs_mark_buffer_dirty(leaf);
2638 btrfs_free_path(path);
2642 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2643 struct btrfs_device *device, u64 new_size)
2645 struct btrfs_fs_info *fs_info = device->fs_info;
2646 struct btrfs_super_block *super_copy = fs_info->super_copy;
2647 struct btrfs_fs_devices *fs_devices;
2651 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2654 new_size = round_down(new_size, fs_info->sectorsize);
2656 mutex_lock(&fs_info->chunk_mutex);
2657 old_total = btrfs_super_total_bytes(super_copy);
2658 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2660 if (new_size <= device->total_bytes ||
2661 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2662 mutex_unlock(&fs_info->chunk_mutex);
2666 fs_devices = fs_info->fs_devices;
2668 btrfs_set_super_total_bytes(super_copy,
2669 round_down(old_total + diff, fs_info->sectorsize));
2670 device->fs_devices->total_rw_bytes += diff;
2672 btrfs_device_set_total_bytes(device, new_size);
2673 btrfs_device_set_disk_total_bytes(device, new_size);
2674 btrfs_clear_space_info_full(device->fs_info);
2675 if (list_empty(&device->resized_list))
2676 list_add_tail(&device->resized_list,
2677 &fs_devices->resized_devices);
2678 mutex_unlock(&fs_info->chunk_mutex);
2680 return btrfs_update_device(trans, device);
2683 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2685 struct btrfs_fs_info *fs_info = trans->fs_info;
2686 struct btrfs_root *root = fs_info->chunk_root;
2688 struct btrfs_path *path;
2689 struct btrfs_key key;
2691 path = btrfs_alloc_path();
2695 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2696 key.offset = chunk_offset;
2697 key.type = BTRFS_CHUNK_ITEM_KEY;
2699 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2702 else if (ret > 0) { /* Logic error or corruption */
2703 btrfs_handle_fs_error(fs_info, -ENOENT,
2704 "Failed lookup while freeing chunk.");
2709 ret = btrfs_del_item(trans, root, path);
2711 btrfs_handle_fs_error(fs_info, ret,
2712 "Failed to delete chunk item.");
2714 btrfs_free_path(path);
2718 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2720 struct btrfs_super_block *super_copy = fs_info->super_copy;
2721 struct btrfs_disk_key *disk_key;
2722 struct btrfs_chunk *chunk;
2729 struct btrfs_key key;
2731 mutex_lock(&fs_info->chunk_mutex);
2732 array_size = btrfs_super_sys_array_size(super_copy);
2734 ptr = super_copy->sys_chunk_array;
2737 while (cur < array_size) {
2738 disk_key = (struct btrfs_disk_key *)ptr;
2739 btrfs_disk_key_to_cpu(&key, disk_key);
2741 len = sizeof(*disk_key);
2743 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2744 chunk = (struct btrfs_chunk *)(ptr + len);
2745 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2746 len += btrfs_chunk_item_size(num_stripes);
2751 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2752 key.offset == chunk_offset) {
2753 memmove(ptr, ptr + len, array_size - (cur + len));
2755 btrfs_set_super_sys_array_size(super_copy, array_size);
2761 mutex_unlock(&fs_info->chunk_mutex);
2766 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2767 * @logical: Logical block offset in bytes.
2768 * @length: Length of extent in bytes.
2770 * Return: Chunk mapping or ERR_PTR.
2772 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2773 u64 logical, u64 length)
2775 struct extent_map_tree *em_tree;
2776 struct extent_map *em;
2778 em_tree = &fs_info->mapping_tree.map_tree;
2779 read_lock(&em_tree->lock);
2780 em = lookup_extent_mapping(em_tree, logical, length);
2781 read_unlock(&em_tree->lock);
2784 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2786 return ERR_PTR(-EINVAL);
2789 if (em->start > logical || em->start + em->len < logical) {
2791 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2792 logical, length, em->start, em->start + em->len);
2793 free_extent_map(em);
2794 return ERR_PTR(-EINVAL);
2797 /* callers are responsible for dropping em's ref. */
2801 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2803 struct btrfs_fs_info *fs_info = trans->fs_info;
2804 struct extent_map *em;
2805 struct map_lookup *map;
2806 u64 dev_extent_len = 0;
2808 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2810 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2813 * This is a logic error, but we don't want to just rely on the
2814 * user having built with ASSERT enabled, so if ASSERT doesn't
2815 * do anything we still error out.
2820 map = em->map_lookup;
2821 mutex_lock(&fs_info->chunk_mutex);
2822 check_system_chunk(trans, map->type);
2823 mutex_unlock(&fs_info->chunk_mutex);
2826 * Take the device list mutex to prevent races with the final phase of
2827 * a device replace operation that replaces the device object associated
2828 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2830 mutex_lock(&fs_devices->device_list_mutex);
2831 for (i = 0; i < map->num_stripes; i++) {
2832 struct btrfs_device *device = map->stripes[i].dev;
2833 ret = btrfs_free_dev_extent(trans, device,
2834 map->stripes[i].physical,
2837 mutex_unlock(&fs_devices->device_list_mutex);
2838 btrfs_abort_transaction(trans, ret);
2842 if (device->bytes_used > 0) {
2843 mutex_lock(&fs_info->chunk_mutex);
2844 btrfs_device_set_bytes_used(device,
2845 device->bytes_used - dev_extent_len);
2846 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2847 btrfs_clear_space_info_full(fs_info);
2848 mutex_unlock(&fs_info->chunk_mutex);
2851 if (map->stripes[i].dev) {
2852 ret = btrfs_update_device(trans, map->stripes[i].dev);
2854 mutex_unlock(&fs_devices->device_list_mutex);
2855 btrfs_abort_transaction(trans, ret);
2860 mutex_unlock(&fs_devices->device_list_mutex);
2862 ret = btrfs_free_chunk(trans, chunk_offset);
2864 btrfs_abort_transaction(trans, ret);
2868 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2870 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2871 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2873 btrfs_abort_transaction(trans, ret);
2878 ret = btrfs_remove_block_group(trans, chunk_offset, em);
2880 btrfs_abort_transaction(trans, ret);
2886 free_extent_map(em);
2890 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2892 struct btrfs_root *root = fs_info->chunk_root;
2893 struct btrfs_trans_handle *trans;
2897 * Prevent races with automatic removal of unused block groups.
2898 * After we relocate and before we remove the chunk with offset
2899 * chunk_offset, automatic removal of the block group can kick in,
2900 * resulting in a failure when calling btrfs_remove_chunk() below.
2902 * Make sure to acquire this mutex before doing a tree search (dev
2903 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2904 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2905 * we release the path used to search the chunk/dev tree and before
2906 * the current task acquires this mutex and calls us.
2908 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2910 ret = btrfs_can_relocate(fs_info, chunk_offset);
2914 /* step one, relocate all the extents inside this chunk */
2915 btrfs_scrub_pause(fs_info);
2916 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2917 btrfs_scrub_continue(fs_info);
2922 * We add the kobjects here (and after forcing data chunk creation)
2923 * since relocation is the only place we'll create chunks of a new
2924 * type at runtime. The only place where we'll remove the last
2925 * chunk of a type is the call immediately below this one. Even
2926 * so, we're protected against races with the cleaner thread since
2927 * we're covered by the delete_unused_bgs_mutex.
2929 btrfs_add_raid_kobjects(fs_info);
2931 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2933 if (IS_ERR(trans)) {
2934 ret = PTR_ERR(trans);
2935 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2940 * step two, delete the device extents and the
2941 * chunk tree entries
2943 ret = btrfs_remove_chunk(trans, chunk_offset);
2944 btrfs_end_transaction(trans);
2948 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2950 struct btrfs_root *chunk_root = fs_info->chunk_root;
2951 struct btrfs_path *path;
2952 struct extent_buffer *leaf;
2953 struct btrfs_chunk *chunk;
2954 struct btrfs_key key;
2955 struct btrfs_key found_key;
2957 bool retried = false;
2961 path = btrfs_alloc_path();
2966 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2967 key.offset = (u64)-1;
2968 key.type = BTRFS_CHUNK_ITEM_KEY;
2971 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2972 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2974 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2977 BUG_ON(ret == 0); /* Corruption */
2979 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2982 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2988 leaf = path->nodes[0];
2989 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2991 chunk = btrfs_item_ptr(leaf, path->slots[0],
2992 struct btrfs_chunk);
2993 chunk_type = btrfs_chunk_type(leaf, chunk);
2994 btrfs_release_path(path);
2996 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2997 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3003 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3005 if (found_key.offset == 0)
3007 key.offset = found_key.offset - 1;
3010 if (failed && !retried) {
3014 } else if (WARN_ON(failed && retried)) {
3018 btrfs_free_path(path);
3023 * return 1 : allocate a data chunk successfully,
3024 * return <0: errors during allocating a data chunk,
3025 * return 0 : no need to allocate a data chunk.
3027 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3030 struct btrfs_block_group_cache *cache;
3034 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3036 chunk_type = cache->flags;
3037 btrfs_put_block_group(cache);
3039 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3040 spin_lock(&fs_info->data_sinfo->lock);
3041 bytes_used = fs_info->data_sinfo->bytes_used;
3042 spin_unlock(&fs_info->data_sinfo->lock);
3045 struct btrfs_trans_handle *trans;
3048 trans = btrfs_join_transaction(fs_info->tree_root);
3050 return PTR_ERR(trans);
3052 ret = btrfs_force_chunk_alloc(trans,
3053 BTRFS_BLOCK_GROUP_DATA);
3054 btrfs_end_transaction(trans);
3058 btrfs_add_raid_kobjects(fs_info);
3066 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3067 struct btrfs_balance_control *bctl)
3069 struct btrfs_root *root = fs_info->tree_root;
3070 struct btrfs_trans_handle *trans;
3071 struct btrfs_balance_item *item;
3072 struct btrfs_disk_balance_args disk_bargs;
3073 struct btrfs_path *path;
3074 struct extent_buffer *leaf;
3075 struct btrfs_key key;
3078 path = btrfs_alloc_path();
3082 trans = btrfs_start_transaction(root, 0);
3083 if (IS_ERR(trans)) {
3084 btrfs_free_path(path);
3085 return PTR_ERR(trans);
3088 key.objectid = BTRFS_BALANCE_OBJECTID;
3089 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3092 ret = btrfs_insert_empty_item(trans, root, path, &key,
3097 leaf = path->nodes[0];
3098 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3100 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3102 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3103 btrfs_set_balance_data(leaf, item, &disk_bargs);
3104 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3105 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3106 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3107 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3109 btrfs_set_balance_flags(leaf, item, bctl->flags);
3111 btrfs_mark_buffer_dirty(leaf);
3113 btrfs_free_path(path);
3114 err = btrfs_commit_transaction(trans);
3120 static int del_balance_item(struct btrfs_fs_info *fs_info)
3122 struct btrfs_root *root = fs_info->tree_root;
3123 struct btrfs_trans_handle *trans;
3124 struct btrfs_path *path;
3125 struct btrfs_key key;
3128 path = btrfs_alloc_path();
3132 trans = btrfs_start_transaction(root, 0);
3133 if (IS_ERR(trans)) {
3134 btrfs_free_path(path);
3135 return PTR_ERR(trans);
3138 key.objectid = BTRFS_BALANCE_OBJECTID;
3139 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3142 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3150 ret = btrfs_del_item(trans, root, path);
3152 btrfs_free_path(path);
3153 err = btrfs_commit_transaction(trans);
3160 * This is a heuristic used to reduce the number of chunks balanced on
3161 * resume after balance was interrupted.
3163 static void update_balance_args(struct btrfs_balance_control *bctl)
3166 * Turn on soft mode for chunk types that were being converted.
3168 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3169 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3170 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3171 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3172 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3173 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3176 * Turn on usage filter if is not already used. The idea is
3177 * that chunks that we have already balanced should be
3178 * reasonably full. Don't do it for chunks that are being
3179 * converted - that will keep us from relocating unconverted
3180 * (albeit full) chunks.
3182 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3183 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3184 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3185 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3186 bctl->data.usage = 90;
3188 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3189 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3190 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3191 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3192 bctl->sys.usage = 90;
3194 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3195 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3196 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3197 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3198 bctl->meta.usage = 90;
3203 * Clear the balance status in fs_info and delete the balance item from disk.
3205 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3207 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3210 BUG_ON(!fs_info->balance_ctl);
3212 spin_lock(&fs_info->balance_lock);
3213 fs_info->balance_ctl = NULL;
3214 spin_unlock(&fs_info->balance_lock);
3217 ret = del_balance_item(fs_info);
3219 btrfs_handle_fs_error(fs_info, ret, NULL);
3223 * Balance filters. Return 1 if chunk should be filtered out
3224 * (should not be balanced).
3226 static int chunk_profiles_filter(u64 chunk_type,
3227 struct btrfs_balance_args *bargs)
3229 chunk_type = chunk_to_extended(chunk_type) &
3230 BTRFS_EXTENDED_PROFILE_MASK;
3232 if (bargs->profiles & chunk_type)
3238 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3239 struct btrfs_balance_args *bargs)
3241 struct btrfs_block_group_cache *cache;
3243 u64 user_thresh_min;
3244 u64 user_thresh_max;
3247 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3248 chunk_used = btrfs_block_group_used(&cache->item);
3250 if (bargs->usage_min == 0)
3251 user_thresh_min = 0;
3253 user_thresh_min = div_factor_fine(cache->key.offset,
3256 if (bargs->usage_max == 0)
3257 user_thresh_max = 1;
3258 else if (bargs->usage_max > 100)
3259 user_thresh_max = cache->key.offset;
3261 user_thresh_max = div_factor_fine(cache->key.offset,
3264 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3267 btrfs_put_block_group(cache);
3271 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3272 u64 chunk_offset, struct btrfs_balance_args *bargs)
3274 struct btrfs_block_group_cache *cache;
3275 u64 chunk_used, user_thresh;
3278 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3279 chunk_used = btrfs_block_group_used(&cache->item);
3281 if (bargs->usage_min == 0)
3283 else if (bargs->usage > 100)
3284 user_thresh = cache->key.offset;
3286 user_thresh = div_factor_fine(cache->key.offset,
3289 if (chunk_used < user_thresh)
3292 btrfs_put_block_group(cache);
3296 static int chunk_devid_filter(struct extent_buffer *leaf,
3297 struct btrfs_chunk *chunk,
3298 struct btrfs_balance_args *bargs)
3300 struct btrfs_stripe *stripe;
3301 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3304 for (i = 0; i < num_stripes; i++) {
3305 stripe = btrfs_stripe_nr(chunk, i);
3306 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3313 /* [pstart, pend) */
3314 static int chunk_drange_filter(struct extent_buffer *leaf,
3315 struct btrfs_chunk *chunk,
3316 struct btrfs_balance_args *bargs)
3318 struct btrfs_stripe *stripe;
3319 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3325 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3328 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3329 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3330 factor = num_stripes / 2;
3331 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3332 factor = num_stripes - 1;
3333 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3334 factor = num_stripes - 2;
3336 factor = num_stripes;
3339 for (i = 0; i < num_stripes; i++) {
3340 stripe = btrfs_stripe_nr(chunk, i);
3341 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3344 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3345 stripe_length = btrfs_chunk_length(leaf, chunk);
3346 stripe_length = div_u64(stripe_length, factor);
3348 if (stripe_offset < bargs->pend &&
3349 stripe_offset + stripe_length > bargs->pstart)
3356 /* [vstart, vend) */
3357 static int chunk_vrange_filter(struct extent_buffer *leaf,
3358 struct btrfs_chunk *chunk,
3360 struct btrfs_balance_args *bargs)
3362 if (chunk_offset < bargs->vend &&
3363 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3364 /* at least part of the chunk is inside this vrange */
3370 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3371 struct btrfs_chunk *chunk,
3372 struct btrfs_balance_args *bargs)
3374 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3376 if (bargs->stripes_min <= num_stripes
3377 && num_stripes <= bargs->stripes_max)
3383 static int chunk_soft_convert_filter(u64 chunk_type,
3384 struct btrfs_balance_args *bargs)
3386 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3389 chunk_type = chunk_to_extended(chunk_type) &
3390 BTRFS_EXTENDED_PROFILE_MASK;
3392 if (bargs->target == chunk_type)
3398 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3399 struct extent_buffer *leaf,
3400 struct btrfs_chunk *chunk, u64 chunk_offset)
3402 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3403 struct btrfs_balance_args *bargs = NULL;
3404 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3407 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3408 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3412 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3413 bargs = &bctl->data;
3414 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3416 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3417 bargs = &bctl->meta;
3419 /* profiles filter */
3420 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3421 chunk_profiles_filter(chunk_type, bargs)) {
3426 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3427 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3429 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3430 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3435 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3436 chunk_devid_filter(leaf, chunk, bargs)) {
3440 /* drange filter, makes sense only with devid filter */
3441 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3442 chunk_drange_filter(leaf, chunk, bargs)) {
3447 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3448 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3452 /* stripes filter */
3453 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3454 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3458 /* soft profile changing mode */
3459 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3460 chunk_soft_convert_filter(chunk_type, bargs)) {
3465 * limited by count, must be the last filter
3467 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3468 if (bargs->limit == 0)
3472 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3474 * Same logic as the 'limit' filter; the minimum cannot be
3475 * determined here because we do not have the global information
3476 * about the count of all chunks that satisfy the filters.
3478 if (bargs->limit_max == 0)
3487 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3489 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3490 struct btrfs_root *chunk_root = fs_info->chunk_root;
3491 struct btrfs_root *dev_root = fs_info->dev_root;
3492 struct list_head *devices;
3493 struct btrfs_device *device;
3497 struct btrfs_chunk *chunk;
3498 struct btrfs_path *path = NULL;
3499 struct btrfs_key key;
3500 struct btrfs_key found_key;
3501 struct btrfs_trans_handle *trans;
3502 struct extent_buffer *leaf;
3505 int enospc_errors = 0;
3506 bool counting = true;
3507 /* The single value limit and min/max limits use the same bytes in the */
3508 u64 limit_data = bctl->data.limit;
3509 u64 limit_meta = bctl->meta.limit;
3510 u64 limit_sys = bctl->sys.limit;
3514 int chunk_reserved = 0;
3516 /* step one make some room on all the devices */
3517 devices = &fs_info->fs_devices->devices;
3518 list_for_each_entry(device, devices, dev_list) {
3519 old_size = btrfs_device_get_total_bytes(device);
3520 size_to_free = div_factor(old_size, 1);
3521 size_to_free = min_t(u64, size_to_free, SZ_1M);
3522 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3523 btrfs_device_get_total_bytes(device) -
3524 btrfs_device_get_bytes_used(device) > size_to_free ||
3525 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3528 ret = btrfs_shrink_device(device, old_size - size_to_free);
3532 /* btrfs_shrink_device never returns ret > 0 */
3537 trans = btrfs_start_transaction(dev_root, 0);
3538 if (IS_ERR(trans)) {
3539 ret = PTR_ERR(trans);
3540 btrfs_info_in_rcu(fs_info,
3541 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3542 rcu_str_deref(device->name), ret,
3543 old_size, old_size - size_to_free);
3547 ret = btrfs_grow_device(trans, device, old_size);
3549 btrfs_end_transaction(trans);
3550 /* btrfs_grow_device never returns ret > 0 */
3552 btrfs_info_in_rcu(fs_info,
3553 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3554 rcu_str_deref(device->name), ret,
3555 old_size, old_size - size_to_free);
3559 btrfs_end_transaction(trans);
3562 /* step two, relocate all the chunks */
3563 path = btrfs_alloc_path();
3569 /* zero out stat counters */
3570 spin_lock(&fs_info->balance_lock);
3571 memset(&bctl->stat, 0, sizeof(bctl->stat));
3572 spin_unlock(&fs_info->balance_lock);
3576 * The single value limit and min/max limits use the same bytes
3579 bctl->data.limit = limit_data;
3580 bctl->meta.limit = limit_meta;
3581 bctl->sys.limit = limit_sys;
3583 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3584 key.offset = (u64)-1;
3585 key.type = BTRFS_CHUNK_ITEM_KEY;
3588 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3589 atomic_read(&fs_info->balance_cancel_req)) {
3594 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3595 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3597 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3602 * this shouldn't happen, it means the last relocate
3606 BUG(); /* FIXME break ? */
3608 ret = btrfs_previous_item(chunk_root, path, 0,
3609 BTRFS_CHUNK_ITEM_KEY);
3611 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3616 leaf = path->nodes[0];
3617 slot = path->slots[0];
3618 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3620 if (found_key.objectid != key.objectid) {
3621 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3625 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3626 chunk_type = btrfs_chunk_type(leaf, chunk);
3629 spin_lock(&fs_info->balance_lock);
3630 bctl->stat.considered++;
3631 spin_unlock(&fs_info->balance_lock);
3634 ret = should_balance_chunk(fs_info, leaf, chunk,
3637 btrfs_release_path(path);
3639 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3644 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3645 spin_lock(&fs_info->balance_lock);
3646 bctl->stat.expected++;
3647 spin_unlock(&fs_info->balance_lock);
3649 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3651 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3653 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3660 * Apply limit_min filter, no need to check if the LIMITS
3661 * filter is used, limit_min is 0 by default
3663 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3664 count_data < bctl->data.limit_min)
3665 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3666 count_meta < bctl->meta.limit_min)
3667 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3668 count_sys < bctl->sys.limit_min)) {
3669 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3673 if (!chunk_reserved) {
3675 * We may be relocating the only data chunk we have,
3676 * which could potentially end up with losing data's
3677 * raid profile, so lets allocate an empty one in
3680 ret = btrfs_may_alloc_data_chunk(fs_info,
3683 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3685 } else if (ret == 1) {
3690 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3691 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3692 if (ret == -ENOSPC) {
3694 } else if (ret == -ETXTBSY) {
3696 "skipping relocation of block group %llu due to active swapfile",
3702 spin_lock(&fs_info->balance_lock);
3703 bctl->stat.completed++;
3704 spin_unlock(&fs_info->balance_lock);
3707 if (found_key.offset == 0)
3709 key.offset = found_key.offset - 1;
3713 btrfs_release_path(path);
3718 btrfs_free_path(path);
3719 if (enospc_errors) {
3720 btrfs_info(fs_info, "%d enospc errors during balance",
3730 * alloc_profile_is_valid - see if a given profile is valid and reduced
3731 * @flags: profile to validate
3732 * @extended: if true @flags is treated as an extended profile
3734 static int alloc_profile_is_valid(u64 flags, int extended)
3736 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3737 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3739 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3741 /* 1) check that all other bits are zeroed */
3745 /* 2) see if profile is reduced */
3747 return !extended; /* "0" is valid for usual profiles */
3749 /* true if exactly one bit set */
3750 return is_power_of_2(flags);
3753 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3755 /* cancel requested || normal exit path */
3756 return atomic_read(&fs_info->balance_cancel_req) ||
3757 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3758 atomic_read(&fs_info->balance_cancel_req) == 0);
3761 /* Non-zero return value signifies invalidity */
3762 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3765 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3766 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3767 (bctl_arg->target & ~allowed)));
3771 * Should be called with balance mutexe held
3773 int btrfs_balance(struct btrfs_fs_info *fs_info,
3774 struct btrfs_balance_control *bctl,
3775 struct btrfs_ioctl_balance_args *bargs)
3777 u64 meta_target, data_target;
3784 if (btrfs_fs_closing(fs_info) ||
3785 atomic_read(&fs_info->balance_pause_req) ||
3786 atomic_read(&fs_info->balance_cancel_req)) {
3791 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3792 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3796 * In case of mixed groups both data and meta should be picked,
3797 * and identical options should be given for both of them.
3799 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3800 if (mixed && (bctl->flags & allowed)) {
3801 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3802 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3803 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3805 "balance: mixed groups data and metadata options must be the same");
3811 num_devices = btrfs_num_devices(fs_info);
3813 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3814 if (num_devices > 1)
3815 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3816 if (num_devices > 2)
3817 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3818 if (num_devices > 3)
3819 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3820 BTRFS_BLOCK_GROUP_RAID6);
3821 if (validate_convert_profile(&bctl->data, allowed)) {
3822 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
3825 "balance: invalid convert data profile %s",
3826 get_raid_name(index));
3830 if (validate_convert_profile(&bctl->meta, allowed)) {
3831 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
3834 "balance: invalid convert metadata profile %s",
3835 get_raid_name(index));
3839 if (validate_convert_profile(&bctl->sys, allowed)) {
3840 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
3843 "balance: invalid convert system profile %s",
3844 get_raid_name(index));
3849 /* allow to reduce meta or sys integrity only if force set */
3850 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3851 BTRFS_BLOCK_GROUP_RAID10 |
3852 BTRFS_BLOCK_GROUP_RAID5 |
3853 BTRFS_BLOCK_GROUP_RAID6;
3855 seq = read_seqbegin(&fs_info->profiles_lock);
3857 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3858 (fs_info->avail_system_alloc_bits & allowed) &&
3859 !(bctl->sys.target & allowed)) ||
3860 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3861 (fs_info->avail_metadata_alloc_bits & allowed) &&
3862 !(bctl->meta.target & allowed))) {
3863 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3865 "balance: force reducing metadata integrity");
3868 "balance: reduces metadata integrity, use --force if you want this");
3873 } while (read_seqretry(&fs_info->profiles_lock, seq));
3875 /* if we're not converting, the target field is uninitialized */
3876 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3877 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3878 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3879 bctl->data.target : fs_info->avail_data_alloc_bits;
3880 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3881 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3882 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
3883 int data_index = btrfs_bg_flags_to_raid_index(data_target);
3886 "balance: metadata profile %s has lower redundancy than data profile %s",
3887 get_raid_name(meta_index), get_raid_name(data_index));
3890 ret = insert_balance_item(fs_info, bctl);
3891 if (ret && ret != -EEXIST)
3894 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3895 BUG_ON(ret == -EEXIST);
3896 BUG_ON(fs_info->balance_ctl);
3897 spin_lock(&fs_info->balance_lock);
3898 fs_info->balance_ctl = bctl;
3899 spin_unlock(&fs_info->balance_lock);
3901 BUG_ON(ret != -EEXIST);
3902 spin_lock(&fs_info->balance_lock);
3903 update_balance_args(bctl);
3904 spin_unlock(&fs_info->balance_lock);
3907 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
3908 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3909 mutex_unlock(&fs_info->balance_mutex);
3911 ret = __btrfs_balance(fs_info);
3913 mutex_lock(&fs_info->balance_mutex);
3914 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3917 memset(bargs, 0, sizeof(*bargs));
3918 btrfs_update_ioctl_balance_args(fs_info, bargs);
3921 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3922 balance_need_close(fs_info)) {
3923 reset_balance_state(fs_info);
3924 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3927 wake_up(&fs_info->balance_wait_q);
3931 if (bctl->flags & BTRFS_BALANCE_RESUME)
3932 reset_balance_state(fs_info);
3935 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3940 static int balance_kthread(void *data)
3942 struct btrfs_fs_info *fs_info = data;
3945 mutex_lock(&fs_info->balance_mutex);
3946 if (fs_info->balance_ctl) {
3947 btrfs_info(fs_info, "balance: resuming");
3948 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
3950 mutex_unlock(&fs_info->balance_mutex);
3955 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3957 struct task_struct *tsk;
3959 mutex_lock(&fs_info->balance_mutex);
3960 if (!fs_info->balance_ctl) {
3961 mutex_unlock(&fs_info->balance_mutex);
3964 mutex_unlock(&fs_info->balance_mutex);
3966 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
3967 btrfs_info(fs_info, "balance: resume skipped");
3972 * A ro->rw remount sequence should continue with the paused balance
3973 * regardless of who pauses it, system or the user as of now, so set
3976 spin_lock(&fs_info->balance_lock);
3977 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
3978 spin_unlock(&fs_info->balance_lock);
3980 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3981 return PTR_ERR_OR_ZERO(tsk);
3984 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3986 struct btrfs_balance_control *bctl;
3987 struct btrfs_balance_item *item;
3988 struct btrfs_disk_balance_args disk_bargs;
3989 struct btrfs_path *path;
3990 struct extent_buffer *leaf;
3991 struct btrfs_key key;
3994 path = btrfs_alloc_path();
3998 key.objectid = BTRFS_BALANCE_OBJECTID;
3999 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4002 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4005 if (ret > 0) { /* ret = -ENOENT; */
4010 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4016 leaf = path->nodes[0];
4017 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4019 bctl->flags = btrfs_balance_flags(leaf, item);
4020 bctl->flags |= BTRFS_BALANCE_RESUME;
4022 btrfs_balance_data(leaf, item, &disk_bargs);
4023 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4024 btrfs_balance_meta(leaf, item, &disk_bargs);
4025 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4026 btrfs_balance_sys(leaf, item, &disk_bargs);
4027 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4030 * This should never happen, as the paused balance state is recovered
4031 * during mount without any chance of other exclusive ops to collide.
4033 * This gives the exclusive op status to balance and keeps in paused
4034 * state until user intervention (cancel or umount). If the ownership
4035 * cannot be assigned, show a message but do not fail. The balance
4036 * is in a paused state and must have fs_info::balance_ctl properly
4039 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4041 "balance: cannot set exclusive op status, resume manually");
4043 mutex_lock(&fs_info->balance_mutex);
4044 BUG_ON(fs_info->balance_ctl);
4045 spin_lock(&fs_info->balance_lock);
4046 fs_info->balance_ctl = bctl;
4047 spin_unlock(&fs_info->balance_lock);
4048 mutex_unlock(&fs_info->balance_mutex);
4050 btrfs_free_path(path);
4054 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4058 mutex_lock(&fs_info->balance_mutex);
4059 if (!fs_info->balance_ctl) {
4060 mutex_unlock(&fs_info->balance_mutex);
4064 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4065 atomic_inc(&fs_info->balance_pause_req);
4066 mutex_unlock(&fs_info->balance_mutex);
4068 wait_event(fs_info->balance_wait_q,
4069 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4071 mutex_lock(&fs_info->balance_mutex);
4072 /* we are good with balance_ctl ripped off from under us */
4073 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4074 atomic_dec(&fs_info->balance_pause_req);
4079 mutex_unlock(&fs_info->balance_mutex);
4083 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4085 mutex_lock(&fs_info->balance_mutex);
4086 if (!fs_info->balance_ctl) {
4087 mutex_unlock(&fs_info->balance_mutex);
4092 * A paused balance with the item stored on disk can be resumed at
4093 * mount time if the mount is read-write. Otherwise it's still paused
4094 * and we must not allow cancelling as it deletes the item.
4096 if (sb_rdonly(fs_info->sb)) {
4097 mutex_unlock(&fs_info->balance_mutex);
4101 atomic_inc(&fs_info->balance_cancel_req);
4103 * if we are running just wait and return, balance item is
4104 * deleted in btrfs_balance in this case
4106 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4107 mutex_unlock(&fs_info->balance_mutex);
4108 wait_event(fs_info->balance_wait_q,
4109 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4110 mutex_lock(&fs_info->balance_mutex);
4112 mutex_unlock(&fs_info->balance_mutex);
4114 * Lock released to allow other waiters to continue, we'll
4115 * reexamine the status again.
4117 mutex_lock(&fs_info->balance_mutex);
4119 if (fs_info->balance_ctl) {
4120 reset_balance_state(fs_info);
4121 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4122 btrfs_info(fs_info, "balance: canceled");
4126 BUG_ON(fs_info->balance_ctl ||
4127 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4128 atomic_dec(&fs_info->balance_cancel_req);
4129 mutex_unlock(&fs_info->balance_mutex);
4133 static int btrfs_uuid_scan_kthread(void *data)
4135 struct btrfs_fs_info *fs_info = data;
4136 struct btrfs_root *root = fs_info->tree_root;
4137 struct btrfs_key key;
4138 struct btrfs_path *path = NULL;
4140 struct extent_buffer *eb;
4142 struct btrfs_root_item root_item;
4144 struct btrfs_trans_handle *trans = NULL;
4146 path = btrfs_alloc_path();
4153 key.type = BTRFS_ROOT_ITEM_KEY;
4157 ret = btrfs_search_forward(root, &key, path,
4158 BTRFS_OLDEST_GENERATION);
4165 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4166 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4167 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4168 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4171 eb = path->nodes[0];
4172 slot = path->slots[0];
4173 item_size = btrfs_item_size_nr(eb, slot);
4174 if (item_size < sizeof(root_item))
4177 read_extent_buffer(eb, &root_item,
4178 btrfs_item_ptr_offset(eb, slot),
4179 (int)sizeof(root_item));
4180 if (btrfs_root_refs(&root_item) == 0)
4183 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4184 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4188 btrfs_release_path(path);
4190 * 1 - subvol uuid item
4191 * 1 - received_subvol uuid item
4193 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4194 if (IS_ERR(trans)) {
4195 ret = PTR_ERR(trans);
4203 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4204 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4205 BTRFS_UUID_KEY_SUBVOL,
4208 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4214 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4215 ret = btrfs_uuid_tree_add(trans,
4216 root_item.received_uuid,
4217 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4220 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4228 ret = btrfs_end_transaction(trans);
4234 btrfs_release_path(path);
4235 if (key.offset < (u64)-1) {
4237 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4239 key.type = BTRFS_ROOT_ITEM_KEY;
4240 } else if (key.objectid < (u64)-1) {
4242 key.type = BTRFS_ROOT_ITEM_KEY;
4251 btrfs_free_path(path);
4252 if (trans && !IS_ERR(trans))
4253 btrfs_end_transaction(trans);
4255 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4257 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4258 up(&fs_info->uuid_tree_rescan_sem);
4263 * Callback for btrfs_uuid_tree_iterate().
4265 * 0 check succeeded, the entry is not outdated.
4266 * < 0 if an error occurred.
4267 * > 0 if the check failed, which means the caller shall remove the entry.
4269 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4270 u8 *uuid, u8 type, u64 subid)
4272 struct btrfs_key key;
4274 struct btrfs_root *subvol_root;
4276 if (type != BTRFS_UUID_KEY_SUBVOL &&
4277 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4280 key.objectid = subid;
4281 key.type = BTRFS_ROOT_ITEM_KEY;
4282 key.offset = (u64)-1;
4283 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4284 if (IS_ERR(subvol_root)) {
4285 ret = PTR_ERR(subvol_root);
4292 case BTRFS_UUID_KEY_SUBVOL:
4293 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4296 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4297 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4307 static int btrfs_uuid_rescan_kthread(void *data)
4309 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4313 * 1st step is to iterate through the existing UUID tree and
4314 * to delete all entries that contain outdated data.
4315 * 2nd step is to add all missing entries to the UUID tree.
4317 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4319 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4320 up(&fs_info->uuid_tree_rescan_sem);
4323 return btrfs_uuid_scan_kthread(data);
4326 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4328 struct btrfs_trans_handle *trans;
4329 struct btrfs_root *tree_root = fs_info->tree_root;
4330 struct btrfs_root *uuid_root;
4331 struct task_struct *task;
4338 trans = btrfs_start_transaction(tree_root, 2);
4340 return PTR_ERR(trans);
4342 uuid_root = btrfs_create_tree(trans, fs_info,
4343 BTRFS_UUID_TREE_OBJECTID);
4344 if (IS_ERR(uuid_root)) {
4345 ret = PTR_ERR(uuid_root);
4346 btrfs_abort_transaction(trans, ret);
4347 btrfs_end_transaction(trans);
4351 fs_info->uuid_root = uuid_root;
4353 ret = btrfs_commit_transaction(trans);
4357 down(&fs_info->uuid_tree_rescan_sem);
4358 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4360 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4361 btrfs_warn(fs_info, "failed to start uuid_scan task");
4362 up(&fs_info->uuid_tree_rescan_sem);
4363 return PTR_ERR(task);
4369 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4371 struct task_struct *task;
4373 down(&fs_info->uuid_tree_rescan_sem);
4374 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4376 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4377 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4378 up(&fs_info->uuid_tree_rescan_sem);
4379 return PTR_ERR(task);
4386 * shrinking a device means finding all of the device extents past
4387 * the new size, and then following the back refs to the chunks.
4388 * The chunk relocation code actually frees the device extent
4390 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4392 struct btrfs_fs_info *fs_info = device->fs_info;
4393 struct btrfs_root *root = fs_info->dev_root;
4394 struct btrfs_trans_handle *trans;
4395 struct btrfs_dev_extent *dev_extent = NULL;
4396 struct btrfs_path *path;
4402 bool retried = false;
4403 bool checked_pending_chunks = false;
4404 struct extent_buffer *l;
4405 struct btrfs_key key;
4406 struct btrfs_super_block *super_copy = fs_info->super_copy;
4407 u64 old_total = btrfs_super_total_bytes(super_copy);
4408 u64 old_size = btrfs_device_get_total_bytes(device);
4411 new_size = round_down(new_size, fs_info->sectorsize);
4412 diff = round_down(old_size - new_size, fs_info->sectorsize);
4414 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4417 path = btrfs_alloc_path();
4421 path->reada = READA_BACK;
4423 mutex_lock(&fs_info->chunk_mutex);
4425 btrfs_device_set_total_bytes(device, new_size);
4426 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4427 device->fs_devices->total_rw_bytes -= diff;
4428 atomic64_sub(diff, &fs_info->free_chunk_space);
4430 mutex_unlock(&fs_info->chunk_mutex);
4433 key.objectid = device->devid;
4434 key.offset = (u64)-1;
4435 key.type = BTRFS_DEV_EXTENT_KEY;
4438 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4439 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4441 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4445 ret = btrfs_previous_item(root, path, 0, key.type);
4447 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4452 btrfs_release_path(path);
4457 slot = path->slots[0];
4458 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4460 if (key.objectid != device->devid) {
4461 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4462 btrfs_release_path(path);
4466 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4467 length = btrfs_dev_extent_length(l, dev_extent);
4469 if (key.offset + length <= new_size) {
4470 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4471 btrfs_release_path(path);
4475 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4476 btrfs_release_path(path);
4479 * We may be relocating the only data chunk we have,
4480 * which could potentially end up with losing data's
4481 * raid profile, so lets allocate an empty one in
4484 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4486 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4490 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4491 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4492 if (ret == -ENOSPC) {
4495 if (ret == -ETXTBSY) {
4497 "could not shrink block group %llu due to active swapfile",
4502 } while (key.offset-- > 0);
4504 if (failed && !retried) {
4508 } else if (failed && retried) {
4513 /* Shrinking succeeded, else we would be at "done". */
4514 trans = btrfs_start_transaction(root, 0);
4515 if (IS_ERR(trans)) {
4516 ret = PTR_ERR(trans);
4520 mutex_lock(&fs_info->chunk_mutex);
4523 * We checked in the above loop all device extents that were already in
4524 * the device tree. However before we have updated the device's
4525 * total_bytes to the new size, we might have had chunk allocations that
4526 * have not complete yet (new block groups attached to transaction
4527 * handles), and therefore their device extents were not yet in the
4528 * device tree and we missed them in the loop above. So if we have any
4529 * pending chunk using a device extent that overlaps the device range
4530 * that we can not use anymore, commit the current transaction and
4531 * repeat the search on the device tree - this way we guarantee we will
4532 * not have chunks using device extents that end beyond 'new_size'.
4534 if (!checked_pending_chunks) {
4535 u64 start = new_size;
4536 u64 len = old_size - new_size;
4538 if (contains_pending_extent(trans->transaction, device,
4540 mutex_unlock(&fs_info->chunk_mutex);
4541 checked_pending_chunks = true;
4544 ret = btrfs_commit_transaction(trans);
4551 btrfs_device_set_disk_total_bytes(device, new_size);
4552 if (list_empty(&device->resized_list))
4553 list_add_tail(&device->resized_list,
4554 &fs_info->fs_devices->resized_devices);
4556 WARN_ON(diff > old_total);
4557 btrfs_set_super_total_bytes(super_copy,
4558 round_down(old_total - diff, fs_info->sectorsize));
4559 mutex_unlock(&fs_info->chunk_mutex);
4561 /* Now btrfs_update_device() will change the on-disk size. */
4562 ret = btrfs_update_device(trans, device);
4564 btrfs_abort_transaction(trans, ret);
4565 btrfs_end_transaction(trans);
4567 ret = btrfs_commit_transaction(trans);
4570 btrfs_free_path(path);
4572 mutex_lock(&fs_info->chunk_mutex);
4573 btrfs_device_set_total_bytes(device, old_size);
4574 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4575 device->fs_devices->total_rw_bytes += diff;
4576 atomic64_add(diff, &fs_info->free_chunk_space);
4577 mutex_unlock(&fs_info->chunk_mutex);
4582 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4583 struct btrfs_key *key,
4584 struct btrfs_chunk *chunk, int item_size)
4586 struct btrfs_super_block *super_copy = fs_info->super_copy;
4587 struct btrfs_disk_key disk_key;
4591 mutex_lock(&fs_info->chunk_mutex);
4592 array_size = btrfs_super_sys_array_size(super_copy);
4593 if (array_size + item_size + sizeof(disk_key)
4594 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4595 mutex_unlock(&fs_info->chunk_mutex);
4599 ptr = super_copy->sys_chunk_array + array_size;
4600 btrfs_cpu_key_to_disk(&disk_key, key);
4601 memcpy(ptr, &disk_key, sizeof(disk_key));
4602 ptr += sizeof(disk_key);
4603 memcpy(ptr, chunk, item_size);
4604 item_size += sizeof(disk_key);
4605 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4606 mutex_unlock(&fs_info->chunk_mutex);
4612 * sort the devices in descending order by max_avail, total_avail
4614 static int btrfs_cmp_device_info(const void *a, const void *b)
4616 const struct btrfs_device_info *di_a = a;
4617 const struct btrfs_device_info *di_b = b;
4619 if (di_a->max_avail > di_b->max_avail)
4621 if (di_a->max_avail < di_b->max_avail)
4623 if (di_a->total_avail > di_b->total_avail)
4625 if (di_a->total_avail < di_b->total_avail)
4630 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4632 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4635 btrfs_set_fs_incompat(info, RAID56);
4638 #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \
4639 - sizeof(struct btrfs_chunk)) \
4640 / sizeof(struct btrfs_stripe) + 1)
4642 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4643 - 2 * sizeof(struct btrfs_disk_key) \
4644 - 2 * sizeof(struct btrfs_chunk)) \
4645 / sizeof(struct btrfs_stripe) + 1)
4647 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4648 u64 start, u64 type)
4650 struct btrfs_fs_info *info = trans->fs_info;
4651 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4652 struct btrfs_device *device;
4653 struct map_lookup *map = NULL;
4654 struct extent_map_tree *em_tree;
4655 struct extent_map *em;
4656 struct btrfs_device_info *devices_info = NULL;
4658 int num_stripes; /* total number of stripes to allocate */
4659 int data_stripes; /* number of stripes that count for
4661 int sub_stripes; /* sub_stripes info for map */
4662 int dev_stripes; /* stripes per dev */
4663 int devs_max; /* max devs to use */
4664 int devs_min; /* min devs needed */
4665 int devs_increment; /* ndevs has to be a multiple of this */
4666 int ncopies; /* how many copies to data has */
4667 int nparity; /* number of stripes worth of bytes to
4668 store parity information */
4670 u64 max_stripe_size;
4679 BUG_ON(!alloc_profile_is_valid(type, 0));
4681 if (list_empty(&fs_devices->alloc_list)) {
4682 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4683 btrfs_debug(info, "%s: no writable device", __func__);
4687 index = btrfs_bg_flags_to_raid_index(type);
4689 sub_stripes = btrfs_raid_array[index].sub_stripes;
4690 dev_stripes = btrfs_raid_array[index].dev_stripes;
4691 devs_max = btrfs_raid_array[index].devs_max;
4692 devs_min = btrfs_raid_array[index].devs_min;
4693 devs_increment = btrfs_raid_array[index].devs_increment;
4694 ncopies = btrfs_raid_array[index].ncopies;
4695 nparity = btrfs_raid_array[index].nparity;
4697 if (type & BTRFS_BLOCK_GROUP_DATA) {
4698 max_stripe_size = SZ_1G;
4699 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4701 devs_max = BTRFS_MAX_DEVS(info);
4702 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4703 /* for larger filesystems, use larger metadata chunks */
4704 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4705 max_stripe_size = SZ_1G;
4707 max_stripe_size = SZ_256M;
4708 max_chunk_size = max_stripe_size;
4710 devs_max = BTRFS_MAX_DEVS(info);
4711 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4712 max_stripe_size = SZ_32M;
4713 max_chunk_size = 2 * max_stripe_size;
4715 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4717 btrfs_err(info, "invalid chunk type 0x%llx requested",
4722 /* we don't want a chunk larger than 10% of writeable space */
4723 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4726 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4732 * in the first pass through the devices list, we gather information
4733 * about the available holes on each device.
4736 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4740 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4742 "BTRFS: read-only device in alloc_list\n");
4746 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4747 &device->dev_state) ||
4748 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4751 if (device->total_bytes > device->bytes_used)
4752 total_avail = device->total_bytes - device->bytes_used;
4756 /* If there is no space on this device, skip it. */
4757 if (total_avail == 0)
4760 ret = find_free_dev_extent(trans, device,
4761 max_stripe_size * dev_stripes,
4762 &dev_offset, &max_avail);
4763 if (ret && ret != -ENOSPC)
4767 max_avail = max_stripe_size * dev_stripes;
4769 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4770 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4772 "%s: devid %llu has no free space, have=%llu want=%u",
4773 __func__, device->devid, max_avail,
4774 BTRFS_STRIPE_LEN * dev_stripes);
4778 if (ndevs == fs_devices->rw_devices) {
4779 WARN(1, "%s: found more than %llu devices\n",
4780 __func__, fs_devices->rw_devices);
4783 devices_info[ndevs].dev_offset = dev_offset;
4784 devices_info[ndevs].max_avail = max_avail;
4785 devices_info[ndevs].total_avail = total_avail;
4786 devices_info[ndevs].dev = device;
4791 * now sort the devices by hole size / available space
4793 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4794 btrfs_cmp_device_info, NULL);
4796 /* round down to number of usable stripes */
4797 ndevs = round_down(ndevs, devs_increment);
4799 if (ndevs < devs_min) {
4801 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4803 "%s: not enough devices with free space: have=%d minimum required=%d",
4804 __func__, ndevs, devs_min);
4809 ndevs = min(ndevs, devs_max);
4812 * The primary goal is to maximize the number of stripes, so use as
4813 * many devices as possible, even if the stripes are not maximum sized.
4815 * The DUP profile stores more than one stripe per device, the
4816 * max_avail is the total size so we have to adjust.
4818 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4819 num_stripes = ndevs * dev_stripes;
4822 * this will have to be fixed for RAID1 and RAID10 over
4825 data_stripes = (num_stripes - nparity) / ncopies;
4828 * Use the number of data stripes to figure out how big this chunk
4829 * is really going to be in terms of logical address space,
4830 * and compare that answer with the max chunk size. If it's higher,
4831 * we try to reduce stripe_size.
4833 if (stripe_size * data_stripes > max_chunk_size) {
4835 * Reduce stripe_size, round it up to a 16MB boundary again and
4836 * then use it, unless it ends up being even bigger than the
4837 * previous value we had already.
4839 stripe_size = min(round_up(div_u64(max_chunk_size,
4840 data_stripes), SZ_16M),
4844 /* align to BTRFS_STRIPE_LEN */
4845 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4847 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4852 map->num_stripes = num_stripes;
4854 for (i = 0; i < ndevs; ++i) {
4855 for (j = 0; j < dev_stripes; ++j) {
4856 int s = i * dev_stripes + j;
4857 map->stripes[s].dev = devices_info[i].dev;
4858 map->stripes[s].physical = devices_info[i].dev_offset +
4862 map->stripe_len = BTRFS_STRIPE_LEN;
4863 map->io_align = BTRFS_STRIPE_LEN;
4864 map->io_width = BTRFS_STRIPE_LEN;
4866 map->sub_stripes = sub_stripes;
4868 chunk_size = stripe_size * data_stripes;
4870 trace_btrfs_chunk_alloc(info, map, start, chunk_size);
4872 em = alloc_extent_map();
4878 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4879 em->map_lookup = map;
4881 em->len = chunk_size;
4882 em->block_start = 0;
4883 em->block_len = em->len;
4884 em->orig_block_len = stripe_size;
4886 em_tree = &info->mapping_tree.map_tree;
4887 write_lock(&em_tree->lock);
4888 ret = add_extent_mapping(em_tree, em, 0);
4890 write_unlock(&em_tree->lock);
4891 free_extent_map(em);
4895 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4896 refcount_inc(&em->refs);
4897 write_unlock(&em_tree->lock);
4899 ret = btrfs_make_block_group(trans, 0, type, start, chunk_size);
4901 goto error_del_extent;
4903 for (i = 0; i < map->num_stripes; i++)
4904 btrfs_device_set_bytes_used(map->stripes[i].dev,
4905 map->stripes[i].dev->bytes_used + stripe_size);
4907 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4909 free_extent_map(em);
4910 check_raid56_incompat_flag(info, type);
4912 kfree(devices_info);
4916 write_lock(&em_tree->lock);
4917 remove_extent_mapping(em_tree, em);
4918 write_unlock(&em_tree->lock);
4920 /* One for our allocation */
4921 free_extent_map(em);
4922 /* One for the tree reference */
4923 free_extent_map(em);
4924 /* One for the pending_chunks list reference */
4925 free_extent_map(em);
4927 kfree(devices_info);
4931 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4932 u64 chunk_offset, u64 chunk_size)
4934 struct btrfs_fs_info *fs_info = trans->fs_info;
4935 struct btrfs_root *extent_root = fs_info->extent_root;
4936 struct btrfs_root *chunk_root = fs_info->chunk_root;
4937 struct btrfs_key key;
4938 struct btrfs_device *device;
4939 struct btrfs_chunk *chunk;
4940 struct btrfs_stripe *stripe;
4941 struct extent_map *em;
4942 struct map_lookup *map;
4949 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
4953 map = em->map_lookup;
4954 item_size = btrfs_chunk_item_size(map->num_stripes);
4955 stripe_size = em->orig_block_len;
4957 chunk = kzalloc(item_size, GFP_NOFS);
4964 * Take the device list mutex to prevent races with the final phase of
4965 * a device replace operation that replaces the device object associated
4966 * with the map's stripes, because the device object's id can change
4967 * at any time during that final phase of the device replace operation
4968 * (dev-replace.c:btrfs_dev_replace_finishing()).
4970 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4971 for (i = 0; i < map->num_stripes; i++) {
4972 device = map->stripes[i].dev;
4973 dev_offset = map->stripes[i].physical;
4975 ret = btrfs_update_device(trans, device);
4978 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
4979 dev_offset, stripe_size);
4984 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4988 stripe = &chunk->stripe;
4989 for (i = 0; i < map->num_stripes; i++) {
4990 device = map->stripes[i].dev;
4991 dev_offset = map->stripes[i].physical;
4993 btrfs_set_stack_stripe_devid(stripe, device->devid);
4994 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4995 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4998 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5000 btrfs_set_stack_chunk_length(chunk, chunk_size);
5001 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5002 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5003 btrfs_set_stack_chunk_type(chunk, map->type);
5004 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5005 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5006 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5007 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5008 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5010 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5011 key.type = BTRFS_CHUNK_ITEM_KEY;
5012 key.offset = chunk_offset;
5014 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5015 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5017 * TODO: Cleanup of inserted chunk root in case of
5020 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5025 free_extent_map(em);
5030 * Chunk allocation falls into two parts. The first part does works
5031 * that make the new allocated chunk useable, but not do any operation
5032 * that modifies the chunk tree. The second part does the works that
5033 * require modifying the chunk tree. This division is important for the
5034 * bootstrap process of adding storage to a seed btrfs.
5036 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5040 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5041 chunk_offset = find_next_chunk(trans->fs_info);
5042 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5045 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5046 struct btrfs_fs_info *fs_info)
5049 u64 sys_chunk_offset;
5053 chunk_offset = find_next_chunk(fs_info);
5054 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5055 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5059 sys_chunk_offset = find_next_chunk(fs_info);
5060 alloc_profile = btrfs_system_alloc_profile(fs_info);
5061 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5065 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5069 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5070 BTRFS_BLOCK_GROUP_RAID10 |
5071 BTRFS_BLOCK_GROUP_RAID5 |
5072 BTRFS_BLOCK_GROUP_DUP)) {
5074 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5083 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5085 struct extent_map *em;
5086 struct map_lookup *map;
5091 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5095 map = em->map_lookup;
5096 for (i = 0; i < map->num_stripes; i++) {
5097 if (test_bit(BTRFS_DEV_STATE_MISSING,
5098 &map->stripes[i].dev->dev_state)) {
5102 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5103 &map->stripes[i].dev->dev_state)) {
5110 * If the number of missing devices is larger than max errors,
5111 * we can not write the data into that chunk successfully, so
5114 if (miss_ndevs > btrfs_chunk_max_errors(map))
5117 free_extent_map(em);
5121 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5123 extent_map_tree_init(&tree->map_tree);
5126 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5128 struct extent_map *em;
5131 write_lock(&tree->map_tree.lock);
5132 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5134 remove_extent_mapping(&tree->map_tree, em);
5135 write_unlock(&tree->map_tree.lock);
5139 free_extent_map(em);
5140 /* once for the tree */
5141 free_extent_map(em);
5145 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5147 struct extent_map *em;
5148 struct map_lookup *map;
5151 em = btrfs_get_chunk_map(fs_info, logical, len);
5154 * We could return errors for these cases, but that could get
5155 * ugly and we'd probably do the same thing which is just not do
5156 * anything else and exit, so return 1 so the callers don't try
5157 * to use other copies.
5161 map = em->map_lookup;
5162 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5163 ret = map->num_stripes;
5164 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5165 ret = map->sub_stripes;
5166 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5168 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5170 * There could be two corrupted data stripes, we need
5171 * to loop retry in order to rebuild the correct data.
5173 * Fail a stripe at a time on every retry except the
5174 * stripe under reconstruction.
5176 ret = map->num_stripes;
5179 free_extent_map(em);
5181 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
5182 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5183 fs_info->dev_replace.tgtdev)
5185 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
5190 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5193 struct extent_map *em;
5194 struct map_lookup *map;
5195 unsigned long len = fs_info->sectorsize;
5197 em = btrfs_get_chunk_map(fs_info, logical, len);
5199 if (!WARN_ON(IS_ERR(em))) {
5200 map = em->map_lookup;
5201 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5202 len = map->stripe_len * nr_data_stripes(map);
5203 free_extent_map(em);
5208 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5210 struct extent_map *em;
5211 struct map_lookup *map;
5214 em = btrfs_get_chunk_map(fs_info, logical, len);
5216 if(!WARN_ON(IS_ERR(em))) {
5217 map = em->map_lookup;
5218 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5220 free_extent_map(em);
5225 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5226 struct map_lookup *map, int first,
5227 int dev_replace_is_ongoing)
5231 int preferred_mirror;
5233 struct btrfs_device *srcdev;
5236 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5238 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5239 num_stripes = map->sub_stripes;
5241 num_stripes = map->num_stripes;
5243 preferred_mirror = first + current->pid % num_stripes;
5245 if (dev_replace_is_ongoing &&
5246 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5247 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5248 srcdev = fs_info->dev_replace.srcdev;
5253 * try to avoid the drive that is the source drive for a
5254 * dev-replace procedure, only choose it if no other non-missing
5255 * mirror is available
5257 for (tolerance = 0; tolerance < 2; tolerance++) {
5258 if (map->stripes[preferred_mirror].dev->bdev &&
5259 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5260 return preferred_mirror;
5261 for (i = first; i < first + num_stripes; i++) {
5262 if (map->stripes[i].dev->bdev &&
5263 (tolerance || map->stripes[i].dev != srcdev))
5268 /* we couldn't find one that doesn't fail. Just return something
5269 * and the io error handling code will clean up eventually
5271 return preferred_mirror;
5274 static inline int parity_smaller(u64 a, u64 b)
5279 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5280 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5282 struct btrfs_bio_stripe s;
5289 for (i = 0; i < num_stripes - 1; i++) {
5290 if (parity_smaller(bbio->raid_map[i],
5291 bbio->raid_map[i+1])) {
5292 s = bbio->stripes[i];
5293 l = bbio->raid_map[i];
5294 bbio->stripes[i] = bbio->stripes[i+1];
5295 bbio->raid_map[i] = bbio->raid_map[i+1];
5296 bbio->stripes[i+1] = s;
5297 bbio->raid_map[i+1] = l;
5305 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5307 struct btrfs_bio *bbio = kzalloc(
5308 /* the size of the btrfs_bio */
5309 sizeof(struct btrfs_bio) +
5310 /* plus the variable array for the stripes */
5311 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5312 /* plus the variable array for the tgt dev */
5313 sizeof(int) * (real_stripes) +
5315 * plus the raid_map, which includes both the tgt dev
5318 sizeof(u64) * (total_stripes),
5319 GFP_NOFS|__GFP_NOFAIL);
5321 atomic_set(&bbio->error, 0);
5322 refcount_set(&bbio->refs, 1);
5327 void btrfs_get_bbio(struct btrfs_bio *bbio)
5329 WARN_ON(!refcount_read(&bbio->refs));
5330 refcount_inc(&bbio->refs);
5333 void btrfs_put_bbio(struct btrfs_bio *bbio)
5337 if (refcount_dec_and_test(&bbio->refs))
5341 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5343 * Please note that, discard won't be sent to target device of device
5346 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5347 u64 logical, u64 length,
5348 struct btrfs_bio **bbio_ret)
5350 struct extent_map *em;
5351 struct map_lookup *map;
5352 struct btrfs_bio *bbio;
5356 u64 stripe_end_offset;
5363 u32 sub_stripes = 0;
5364 u64 stripes_per_dev = 0;
5365 u32 remaining_stripes = 0;
5366 u32 last_stripe = 0;
5370 /* discard always return a bbio */
5373 em = btrfs_get_chunk_map(fs_info, logical, length);
5377 map = em->map_lookup;
5378 /* we don't discard raid56 yet */
5379 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5384 offset = logical - em->start;
5385 length = min_t(u64, em->len - offset, length);
5387 stripe_len = map->stripe_len;
5389 * stripe_nr counts the total number of stripes we have to stride
5390 * to get to this block
5392 stripe_nr = div64_u64(offset, stripe_len);
5394 /* stripe_offset is the offset of this block in its stripe */
5395 stripe_offset = offset - stripe_nr * stripe_len;
5397 stripe_nr_end = round_up(offset + length, map->stripe_len);
5398 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5399 stripe_cnt = stripe_nr_end - stripe_nr;
5400 stripe_end_offset = stripe_nr_end * map->stripe_len -
5403 * after this, stripe_nr is the number of stripes on this
5404 * device we have to walk to find the data, and stripe_index is
5405 * the number of our device in the stripe array
5409 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5410 BTRFS_BLOCK_GROUP_RAID10)) {
5411 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5414 sub_stripes = map->sub_stripes;
5416 factor = map->num_stripes / sub_stripes;
5417 num_stripes = min_t(u64, map->num_stripes,
5418 sub_stripes * stripe_cnt);
5419 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5420 stripe_index *= sub_stripes;
5421 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5422 &remaining_stripes);
5423 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5424 last_stripe *= sub_stripes;
5425 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5426 BTRFS_BLOCK_GROUP_DUP)) {
5427 num_stripes = map->num_stripes;
5429 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5433 bbio = alloc_btrfs_bio(num_stripes, 0);
5439 for (i = 0; i < num_stripes; i++) {
5440 bbio->stripes[i].physical =
5441 map->stripes[stripe_index].physical +
5442 stripe_offset + stripe_nr * map->stripe_len;
5443 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5445 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5446 BTRFS_BLOCK_GROUP_RAID10)) {
5447 bbio->stripes[i].length = stripes_per_dev *
5450 if (i / sub_stripes < remaining_stripes)
5451 bbio->stripes[i].length +=
5455 * Special for the first stripe and
5458 * |-------|...|-------|
5462 if (i < sub_stripes)
5463 bbio->stripes[i].length -=
5466 if (stripe_index >= last_stripe &&
5467 stripe_index <= (last_stripe +
5469 bbio->stripes[i].length -=
5472 if (i == sub_stripes - 1)
5475 bbio->stripes[i].length = length;
5479 if (stripe_index == map->num_stripes) {
5486 bbio->map_type = map->type;
5487 bbio->num_stripes = num_stripes;
5489 free_extent_map(em);
5494 * In dev-replace case, for repair case (that's the only case where the mirror
5495 * is selected explicitly when calling btrfs_map_block), blocks left of the
5496 * left cursor can also be read from the target drive.
5498 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5500 * For READ, it also needs to be supported using the same mirror number.
5502 * If the requested block is not left of the left cursor, EIO is returned. This
5503 * can happen because btrfs_num_copies() returns one more in the dev-replace
5506 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5507 u64 logical, u64 length,
5508 u64 srcdev_devid, int *mirror_num,
5511 struct btrfs_bio *bbio = NULL;
5513 int index_srcdev = 0;
5515 u64 physical_of_found = 0;
5519 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5520 logical, &length, &bbio, 0, 0);
5522 ASSERT(bbio == NULL);
5526 num_stripes = bbio->num_stripes;
5527 if (*mirror_num > num_stripes) {
5529 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5530 * that means that the requested area is not left of the left
5533 btrfs_put_bbio(bbio);
5538 * process the rest of the function using the mirror_num of the source
5539 * drive. Therefore look it up first. At the end, patch the device
5540 * pointer to the one of the target drive.
5542 for (i = 0; i < num_stripes; i++) {
5543 if (bbio->stripes[i].dev->devid != srcdev_devid)
5547 * In case of DUP, in order to keep it simple, only add the
5548 * mirror with the lowest physical address
5551 physical_of_found <= bbio->stripes[i].physical)
5556 physical_of_found = bbio->stripes[i].physical;
5559 btrfs_put_bbio(bbio);
5565 *mirror_num = index_srcdev + 1;
5566 *physical = physical_of_found;
5570 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5571 struct btrfs_bio **bbio_ret,
5572 struct btrfs_dev_replace *dev_replace,
5573 int *num_stripes_ret, int *max_errors_ret)
5575 struct btrfs_bio *bbio = *bbio_ret;
5576 u64 srcdev_devid = dev_replace->srcdev->devid;
5577 int tgtdev_indexes = 0;
5578 int num_stripes = *num_stripes_ret;
5579 int max_errors = *max_errors_ret;
5582 if (op == BTRFS_MAP_WRITE) {
5583 int index_where_to_add;
5586 * duplicate the write operations while the dev replace
5587 * procedure is running. Since the copying of the old disk to
5588 * the new disk takes place at run time while the filesystem is
5589 * mounted writable, the regular write operations to the old
5590 * disk have to be duplicated to go to the new disk as well.
5592 * Note that device->missing is handled by the caller, and that
5593 * the write to the old disk is already set up in the stripes
5596 index_where_to_add = num_stripes;
5597 for (i = 0; i < num_stripes; i++) {
5598 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5599 /* write to new disk, too */
5600 struct btrfs_bio_stripe *new =
5601 bbio->stripes + index_where_to_add;
5602 struct btrfs_bio_stripe *old =
5605 new->physical = old->physical;
5606 new->length = old->length;
5607 new->dev = dev_replace->tgtdev;
5608 bbio->tgtdev_map[i] = index_where_to_add;
5609 index_where_to_add++;
5614 num_stripes = index_where_to_add;
5615 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5616 int index_srcdev = 0;
5618 u64 physical_of_found = 0;
5621 * During the dev-replace procedure, the target drive can also
5622 * be used to read data in case it is needed to repair a corrupt
5623 * block elsewhere. This is possible if the requested area is
5624 * left of the left cursor. In this area, the target drive is a
5625 * full copy of the source drive.
5627 for (i = 0; i < num_stripes; i++) {
5628 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5630 * In case of DUP, in order to keep it simple,
5631 * only add the mirror with the lowest physical
5635 physical_of_found <=
5636 bbio->stripes[i].physical)
5640 physical_of_found = bbio->stripes[i].physical;
5644 struct btrfs_bio_stripe *tgtdev_stripe =
5645 bbio->stripes + num_stripes;
5647 tgtdev_stripe->physical = physical_of_found;
5648 tgtdev_stripe->length =
5649 bbio->stripes[index_srcdev].length;
5650 tgtdev_stripe->dev = dev_replace->tgtdev;
5651 bbio->tgtdev_map[index_srcdev] = num_stripes;
5658 *num_stripes_ret = num_stripes;
5659 *max_errors_ret = max_errors;
5660 bbio->num_tgtdevs = tgtdev_indexes;
5664 static bool need_full_stripe(enum btrfs_map_op op)
5666 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5669 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5670 enum btrfs_map_op op,
5671 u64 logical, u64 *length,
5672 struct btrfs_bio **bbio_ret,
5673 int mirror_num, int need_raid_map)
5675 struct extent_map *em;
5676 struct map_lookup *map;
5686 int tgtdev_indexes = 0;
5687 struct btrfs_bio *bbio = NULL;
5688 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5689 int dev_replace_is_ongoing = 0;
5690 int num_alloc_stripes;
5691 int patch_the_first_stripe_for_dev_replace = 0;
5692 u64 physical_to_patch_in_first_stripe = 0;
5693 u64 raid56_full_stripe_start = (u64)-1;
5695 if (op == BTRFS_MAP_DISCARD)
5696 return __btrfs_map_block_for_discard(fs_info, logical,
5699 em = btrfs_get_chunk_map(fs_info, logical, *length);
5703 map = em->map_lookup;
5704 offset = logical - em->start;
5706 stripe_len = map->stripe_len;
5709 * stripe_nr counts the total number of stripes we have to stride
5710 * to get to this block
5712 stripe_nr = div64_u64(stripe_nr, stripe_len);
5714 stripe_offset = stripe_nr * stripe_len;
5715 if (offset < stripe_offset) {
5717 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5718 stripe_offset, offset, em->start, logical,
5720 free_extent_map(em);
5724 /* stripe_offset is the offset of this block in its stripe*/
5725 stripe_offset = offset - stripe_offset;
5727 /* if we're here for raid56, we need to know the stripe aligned start */
5728 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5729 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5730 raid56_full_stripe_start = offset;
5732 /* allow a write of a full stripe, but make sure we don't
5733 * allow straddling of stripes
5735 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5737 raid56_full_stripe_start *= full_stripe_len;
5740 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5742 /* For writes to RAID[56], allow a full stripeset across all disks.
5743 For other RAID types and for RAID[56] reads, just allow a single
5744 stripe (on a single disk). */
5745 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5746 (op == BTRFS_MAP_WRITE)) {
5747 max_len = stripe_len * nr_data_stripes(map) -
5748 (offset - raid56_full_stripe_start);
5750 /* we limit the length of each bio to what fits in a stripe */
5751 max_len = stripe_len - stripe_offset;
5753 *length = min_t(u64, em->len - offset, max_len);
5755 *length = em->len - offset;
5758 /* This is for when we're called from btrfs_merge_bio_hook() and all
5759 it cares about is the length */
5763 btrfs_dev_replace_read_lock(dev_replace);
5764 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5765 if (!dev_replace_is_ongoing)
5766 btrfs_dev_replace_read_unlock(dev_replace);
5768 btrfs_dev_replace_set_lock_blocking(dev_replace);
5770 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5771 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5772 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5773 dev_replace->srcdev->devid,
5775 &physical_to_patch_in_first_stripe);
5779 patch_the_first_stripe_for_dev_replace = 1;
5780 } else if (mirror_num > map->num_stripes) {
5786 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5787 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5789 if (!need_full_stripe(op))
5791 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5792 if (need_full_stripe(op))
5793 num_stripes = map->num_stripes;
5794 else if (mirror_num)
5795 stripe_index = mirror_num - 1;
5797 stripe_index = find_live_mirror(fs_info, map, 0,
5798 dev_replace_is_ongoing);
5799 mirror_num = stripe_index + 1;
5802 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5803 if (need_full_stripe(op)) {
5804 num_stripes = map->num_stripes;
5805 } else if (mirror_num) {
5806 stripe_index = mirror_num - 1;
5811 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5812 u32 factor = map->num_stripes / map->sub_stripes;
5814 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5815 stripe_index *= map->sub_stripes;
5817 if (need_full_stripe(op))
5818 num_stripes = map->sub_stripes;
5819 else if (mirror_num)
5820 stripe_index += mirror_num - 1;
5822 int old_stripe_index = stripe_index;
5823 stripe_index = find_live_mirror(fs_info, map,
5825 dev_replace_is_ongoing);
5826 mirror_num = stripe_index - old_stripe_index + 1;
5829 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5830 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5831 /* push stripe_nr back to the start of the full stripe */
5832 stripe_nr = div64_u64(raid56_full_stripe_start,
5833 stripe_len * nr_data_stripes(map));
5835 /* RAID[56] write or recovery. Return all stripes */
5836 num_stripes = map->num_stripes;
5837 max_errors = nr_parity_stripes(map);
5839 *length = map->stripe_len;
5844 * Mirror #0 or #1 means the original data block.
5845 * Mirror #2 is RAID5 parity block.
5846 * Mirror #3 is RAID6 Q block.
5848 stripe_nr = div_u64_rem(stripe_nr,
5849 nr_data_stripes(map), &stripe_index);
5851 stripe_index = nr_data_stripes(map) +
5854 /* We distribute the parity blocks across stripes */
5855 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5857 if (!need_full_stripe(op) && mirror_num <= 1)
5862 * after this, stripe_nr is the number of stripes on this
5863 * device we have to walk to find the data, and stripe_index is
5864 * the number of our device in the stripe array
5866 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5868 mirror_num = stripe_index + 1;
5870 if (stripe_index >= map->num_stripes) {
5872 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5873 stripe_index, map->num_stripes);
5878 num_alloc_stripes = num_stripes;
5879 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5880 if (op == BTRFS_MAP_WRITE)
5881 num_alloc_stripes <<= 1;
5882 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5883 num_alloc_stripes++;
5884 tgtdev_indexes = num_stripes;
5887 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5892 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5893 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5895 /* build raid_map */
5896 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5897 (need_full_stripe(op) || mirror_num > 1)) {
5901 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5902 sizeof(struct btrfs_bio_stripe) *
5904 sizeof(int) * tgtdev_indexes);
5906 /* Work out the disk rotation on this stripe-set */
5907 div_u64_rem(stripe_nr, num_stripes, &rot);
5909 /* Fill in the logical address of each stripe */
5910 tmp = stripe_nr * nr_data_stripes(map);
5911 for (i = 0; i < nr_data_stripes(map); i++)
5912 bbio->raid_map[(i+rot) % num_stripes] =
5913 em->start + (tmp + i) * map->stripe_len;
5915 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5916 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5917 bbio->raid_map[(i+rot+1) % num_stripes] =
5922 for (i = 0; i < num_stripes; i++) {
5923 bbio->stripes[i].physical =
5924 map->stripes[stripe_index].physical +
5926 stripe_nr * map->stripe_len;
5927 bbio->stripes[i].dev =
5928 map->stripes[stripe_index].dev;
5932 if (need_full_stripe(op))
5933 max_errors = btrfs_chunk_max_errors(map);
5936 sort_parity_stripes(bbio, num_stripes);
5938 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5939 need_full_stripe(op)) {
5940 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5945 bbio->map_type = map->type;
5946 bbio->num_stripes = num_stripes;
5947 bbio->max_errors = max_errors;
5948 bbio->mirror_num = mirror_num;
5951 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5952 * mirror_num == num_stripes + 1 && dev_replace target drive is
5953 * available as a mirror
5955 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5956 WARN_ON(num_stripes > 1);
5957 bbio->stripes[0].dev = dev_replace->tgtdev;
5958 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5959 bbio->mirror_num = map->num_stripes + 1;
5962 if (dev_replace_is_ongoing) {
5963 ASSERT(atomic_read(&dev_replace->blocking_readers) > 0);
5964 btrfs_dev_replace_read_lock(dev_replace);
5965 /* Barrier implied by atomic_dec_and_test */
5966 if (atomic_dec_and_test(&dev_replace->blocking_readers))
5967 cond_wake_up_nomb(&dev_replace->read_lock_wq);
5968 btrfs_dev_replace_read_unlock(dev_replace);
5970 free_extent_map(em);
5974 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5975 u64 logical, u64 *length,
5976 struct btrfs_bio **bbio_ret, int mirror_num)
5978 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
5982 /* For Scrub/replace */
5983 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5984 u64 logical, u64 *length,
5985 struct btrfs_bio **bbio_ret)
5987 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
5990 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
5991 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
5993 struct extent_map *em;
5994 struct map_lookup *map;
6002 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
6006 map = em->map_lookup;
6008 rmap_len = map->stripe_len;
6010 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6011 length = div_u64(length, map->num_stripes / map->sub_stripes);
6012 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6013 length = div_u64(length, map->num_stripes);
6014 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6015 length = div_u64(length, nr_data_stripes(map));
6016 rmap_len = map->stripe_len * nr_data_stripes(map);
6019 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6020 BUG_ON(!buf); /* -ENOMEM */
6022 for (i = 0; i < map->num_stripes; i++) {
6023 if (map->stripes[i].physical > physical ||
6024 map->stripes[i].physical + length <= physical)
6027 stripe_nr = physical - map->stripes[i].physical;
6028 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6030 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6031 stripe_nr = stripe_nr * map->num_stripes + i;
6032 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6033 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6034 stripe_nr = stripe_nr * map->num_stripes + i;
6035 } /* else if RAID[56], multiply by nr_data_stripes().
6036 * Alternatively, just use rmap_len below instead of
6037 * map->stripe_len */
6039 bytenr = chunk_start + stripe_nr * rmap_len;
6040 WARN_ON(nr >= map->num_stripes);
6041 for (j = 0; j < nr; j++) {
6042 if (buf[j] == bytenr)
6046 WARN_ON(nr >= map->num_stripes);
6053 *stripe_len = rmap_len;
6055 free_extent_map(em);
6059 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6061 bio->bi_private = bbio->private;
6062 bio->bi_end_io = bbio->end_io;
6065 btrfs_put_bbio(bbio);
6068 static void btrfs_end_bio(struct bio *bio)
6070 struct btrfs_bio *bbio = bio->bi_private;
6071 int is_orig_bio = 0;
6073 if (bio->bi_status) {
6074 atomic_inc(&bbio->error);
6075 if (bio->bi_status == BLK_STS_IOERR ||
6076 bio->bi_status == BLK_STS_TARGET) {
6077 unsigned int stripe_index =
6078 btrfs_io_bio(bio)->stripe_index;
6079 struct btrfs_device *dev;
6081 BUG_ON(stripe_index >= bbio->num_stripes);
6082 dev = bbio->stripes[stripe_index].dev;
6084 if (bio_op(bio) == REQ_OP_WRITE)
6085 btrfs_dev_stat_inc_and_print(dev,
6086 BTRFS_DEV_STAT_WRITE_ERRS);
6088 btrfs_dev_stat_inc_and_print(dev,
6089 BTRFS_DEV_STAT_READ_ERRS);
6090 if (bio->bi_opf & REQ_PREFLUSH)
6091 btrfs_dev_stat_inc_and_print(dev,
6092 BTRFS_DEV_STAT_FLUSH_ERRS);
6097 if (bio == bbio->orig_bio)
6100 btrfs_bio_counter_dec(bbio->fs_info);
6102 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6105 bio = bbio->orig_bio;
6108 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6109 /* only send an error to the higher layers if it is
6110 * beyond the tolerance of the btrfs bio
6112 if (atomic_read(&bbio->error) > bbio->max_errors) {
6113 bio->bi_status = BLK_STS_IOERR;
6116 * this bio is actually up to date, we didn't
6117 * go over the max number of errors
6119 bio->bi_status = BLK_STS_OK;
6122 btrfs_end_bbio(bbio, bio);
6123 } else if (!is_orig_bio) {
6129 * see run_scheduled_bios for a description of why bios are collected for
6132 * This will add one bio to the pending list for a device and make sure
6133 * the work struct is scheduled.
6135 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6138 struct btrfs_fs_info *fs_info = device->fs_info;
6139 int should_queue = 1;
6140 struct btrfs_pending_bios *pending_bios;
6142 /* don't bother with additional async steps for reads, right now */
6143 if (bio_op(bio) == REQ_OP_READ) {
6144 btrfsic_submit_bio(bio);
6148 WARN_ON(bio->bi_next);
6149 bio->bi_next = NULL;
6151 spin_lock(&device->io_lock);
6152 if (op_is_sync(bio->bi_opf))
6153 pending_bios = &device->pending_sync_bios;
6155 pending_bios = &device->pending_bios;
6157 if (pending_bios->tail)
6158 pending_bios->tail->bi_next = bio;
6160 pending_bios->tail = bio;
6161 if (!pending_bios->head)
6162 pending_bios->head = bio;
6163 if (device->running_pending)
6166 spin_unlock(&device->io_lock);
6169 btrfs_queue_work(fs_info->submit_workers, &device->work);
6172 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6173 u64 physical, int dev_nr, int async)
6175 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6176 struct btrfs_fs_info *fs_info = bbio->fs_info;
6178 bio->bi_private = bbio;
6179 btrfs_io_bio(bio)->stripe_index = dev_nr;
6180 bio->bi_end_io = btrfs_end_bio;
6181 bio->bi_iter.bi_sector = physical >> 9;
6182 btrfs_debug_in_rcu(fs_info,
6183 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6184 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6185 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6186 bio->bi_iter.bi_size);
6187 bio_set_dev(bio, dev->bdev);
6189 btrfs_bio_counter_inc_noblocked(fs_info);
6192 btrfs_schedule_bio(dev, bio);
6194 btrfsic_submit_bio(bio);
6197 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6199 atomic_inc(&bbio->error);
6200 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6201 /* Should be the original bio. */
6202 WARN_ON(bio != bbio->orig_bio);
6204 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6205 bio->bi_iter.bi_sector = logical >> 9;
6206 if (atomic_read(&bbio->error) > bbio->max_errors)
6207 bio->bi_status = BLK_STS_IOERR;
6209 bio->bi_status = BLK_STS_OK;
6210 btrfs_end_bbio(bbio, bio);
6214 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6215 int mirror_num, int async_submit)
6217 struct btrfs_device *dev;
6218 struct bio *first_bio = bio;
6219 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6225 struct btrfs_bio *bbio = NULL;
6227 length = bio->bi_iter.bi_size;
6228 map_length = length;
6230 btrfs_bio_counter_inc_blocked(fs_info);
6231 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6232 &map_length, &bbio, mirror_num, 1);
6234 btrfs_bio_counter_dec(fs_info);
6235 return errno_to_blk_status(ret);
6238 total_devs = bbio->num_stripes;
6239 bbio->orig_bio = first_bio;
6240 bbio->private = first_bio->bi_private;
6241 bbio->end_io = first_bio->bi_end_io;
6242 bbio->fs_info = fs_info;
6243 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6245 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6246 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6247 /* In this case, map_length has been set to the length of
6248 a single stripe; not the whole write */
6249 if (bio_op(bio) == REQ_OP_WRITE) {
6250 ret = raid56_parity_write(fs_info, bio, bbio,
6253 ret = raid56_parity_recover(fs_info, bio, bbio,
6254 map_length, mirror_num, 1);
6257 btrfs_bio_counter_dec(fs_info);
6258 return errno_to_blk_status(ret);
6261 if (map_length < length) {
6263 "mapping failed logical %llu bio len %llu len %llu",
6264 logical, length, map_length);
6268 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6269 dev = bbio->stripes[dev_nr].dev;
6270 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6272 (bio_op(first_bio) == REQ_OP_WRITE &&
6273 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6274 bbio_error(bbio, first_bio, logical);
6278 if (dev_nr < total_devs - 1)
6279 bio = btrfs_bio_clone(first_bio);
6283 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6284 dev_nr, async_submit);
6286 btrfs_bio_counter_dec(fs_info);
6290 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6293 struct btrfs_device *device;
6294 struct btrfs_fs_devices *cur_devices;
6296 cur_devices = fs_info->fs_devices;
6297 while (cur_devices) {
6299 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6300 device = find_device(cur_devices, devid, uuid);
6304 cur_devices = cur_devices->seed;
6309 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6310 u64 devid, u8 *dev_uuid)
6312 struct btrfs_device *device;
6314 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6318 list_add(&device->dev_list, &fs_devices->devices);
6319 device->fs_devices = fs_devices;
6320 fs_devices->num_devices++;
6322 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6323 fs_devices->missing_devices++;
6329 * btrfs_alloc_device - allocate struct btrfs_device
6330 * @fs_info: used only for generating a new devid, can be NULL if
6331 * devid is provided (i.e. @devid != NULL).
6332 * @devid: a pointer to devid for this device. If NULL a new devid
6334 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6337 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6338 * on error. Returned struct is not linked onto any lists and must be
6339 * destroyed with btrfs_free_device.
6341 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6345 struct btrfs_device *dev;
6348 if (WARN_ON(!devid && !fs_info))
6349 return ERR_PTR(-EINVAL);
6351 dev = __alloc_device();
6360 ret = find_next_devid(fs_info, &tmp);
6362 btrfs_free_device(dev);
6363 return ERR_PTR(ret);
6369 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6371 generate_random_uuid(dev->uuid);
6373 btrfs_init_work(&dev->work, btrfs_submit_helper,
6374 pending_bios_fn, NULL, NULL);
6379 /* Return -EIO if any error, otherwise return 0. */
6380 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6381 struct extent_buffer *leaf,
6382 struct btrfs_chunk *chunk, u64 logical)
6392 length = btrfs_chunk_length(leaf, chunk);
6393 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6394 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6395 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6396 type = btrfs_chunk_type(leaf, chunk);
6399 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6403 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6404 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6407 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6408 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6409 btrfs_chunk_sector_size(leaf, chunk));
6412 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6413 btrfs_err(fs_info, "invalid chunk length %llu", length);
6416 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6417 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6421 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6423 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6424 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6425 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6426 btrfs_chunk_type(leaf, chunk));
6430 if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == 0) {
6431 btrfs_err(fs_info, "missing chunk type flag: 0x%llx", type);
6435 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) &&
6436 (type & (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA))) {
6438 "system chunk with data or metadata type: 0x%llx", type);
6442 features = btrfs_super_incompat_flags(fs_info->super_copy);
6443 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
6447 if ((type & BTRFS_BLOCK_GROUP_METADATA) &&
6448 (type & BTRFS_BLOCK_GROUP_DATA)) {
6450 "mixed chunk type in non-mixed mode: 0x%llx", type);
6455 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6456 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6457 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6458 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6459 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6460 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6461 num_stripes != 1)) {
6463 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6464 num_stripes, sub_stripes,
6465 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6472 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6473 u64 devid, u8 *uuid, bool error)
6476 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6479 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6483 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6484 struct extent_buffer *leaf,
6485 struct btrfs_chunk *chunk)
6487 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6488 struct map_lookup *map;
6489 struct extent_map *em;
6493 u8 uuid[BTRFS_UUID_SIZE];
6498 logical = key->offset;
6499 length = btrfs_chunk_length(leaf, chunk);
6500 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6502 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6506 read_lock(&map_tree->map_tree.lock);
6507 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6508 read_unlock(&map_tree->map_tree.lock);
6510 /* already mapped? */
6511 if (em && em->start <= logical && em->start + em->len > logical) {
6512 free_extent_map(em);
6515 free_extent_map(em);
6518 em = alloc_extent_map();
6521 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6523 free_extent_map(em);
6527 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6528 em->map_lookup = map;
6529 em->start = logical;
6532 em->block_start = 0;
6533 em->block_len = em->len;
6535 map->num_stripes = num_stripes;
6536 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6537 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6538 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6539 map->type = btrfs_chunk_type(leaf, chunk);
6540 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6541 map->verified_stripes = 0;
6542 for (i = 0; i < num_stripes; i++) {
6543 map->stripes[i].physical =
6544 btrfs_stripe_offset_nr(leaf, chunk, i);
6545 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6546 read_extent_buffer(leaf, uuid, (unsigned long)
6547 btrfs_stripe_dev_uuid_nr(chunk, i),
6549 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6551 if (!map->stripes[i].dev &&
6552 !btrfs_test_opt(fs_info, DEGRADED)) {
6553 free_extent_map(em);
6554 btrfs_report_missing_device(fs_info, devid, uuid, true);
6557 if (!map->stripes[i].dev) {
6558 map->stripes[i].dev =
6559 add_missing_dev(fs_info->fs_devices, devid,
6561 if (IS_ERR(map->stripes[i].dev)) {
6562 free_extent_map(em);
6564 "failed to init missing dev %llu: %ld",
6565 devid, PTR_ERR(map->stripes[i].dev));
6566 return PTR_ERR(map->stripes[i].dev);
6568 btrfs_report_missing_device(fs_info, devid, uuid, false);
6570 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6571 &(map->stripes[i].dev->dev_state));
6575 write_lock(&map_tree->map_tree.lock);
6576 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6577 write_unlock(&map_tree->map_tree.lock);
6580 "failed to add chunk map, start=%llu len=%llu: %d",
6581 em->start, em->len, ret);
6583 free_extent_map(em);
6588 static void fill_device_from_item(struct extent_buffer *leaf,
6589 struct btrfs_dev_item *dev_item,
6590 struct btrfs_device *device)
6594 device->devid = btrfs_device_id(leaf, dev_item);
6595 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6596 device->total_bytes = device->disk_total_bytes;
6597 device->commit_total_bytes = device->disk_total_bytes;
6598 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6599 device->commit_bytes_used = device->bytes_used;
6600 device->type = btrfs_device_type(leaf, dev_item);
6601 device->io_align = btrfs_device_io_align(leaf, dev_item);
6602 device->io_width = btrfs_device_io_width(leaf, dev_item);
6603 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6604 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6605 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6607 ptr = btrfs_device_uuid(dev_item);
6608 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6611 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6614 struct btrfs_fs_devices *fs_devices;
6617 lockdep_assert_held(&uuid_mutex);
6620 fs_devices = fs_info->fs_devices->seed;
6621 while (fs_devices) {
6622 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6625 fs_devices = fs_devices->seed;
6628 fs_devices = find_fsid(fsid);
6630 if (!btrfs_test_opt(fs_info, DEGRADED))
6631 return ERR_PTR(-ENOENT);
6633 fs_devices = alloc_fs_devices(fsid);
6634 if (IS_ERR(fs_devices))
6637 fs_devices->seeding = 1;
6638 fs_devices->opened = 1;
6642 fs_devices = clone_fs_devices(fs_devices);
6643 if (IS_ERR(fs_devices))
6646 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6648 free_fs_devices(fs_devices);
6649 fs_devices = ERR_PTR(ret);
6653 if (!fs_devices->seeding) {
6654 close_fs_devices(fs_devices);
6655 free_fs_devices(fs_devices);
6656 fs_devices = ERR_PTR(-EINVAL);
6660 fs_devices->seed = fs_info->fs_devices->seed;
6661 fs_info->fs_devices->seed = fs_devices;
6666 static int read_one_dev(struct btrfs_fs_info *fs_info,
6667 struct extent_buffer *leaf,
6668 struct btrfs_dev_item *dev_item)
6670 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6671 struct btrfs_device *device;
6674 u8 fs_uuid[BTRFS_FSID_SIZE];
6675 u8 dev_uuid[BTRFS_UUID_SIZE];
6677 devid = btrfs_device_id(leaf, dev_item);
6678 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6680 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6683 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6684 fs_devices = open_seed_devices(fs_info, fs_uuid);
6685 if (IS_ERR(fs_devices))
6686 return PTR_ERR(fs_devices);
6689 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6691 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6692 btrfs_report_missing_device(fs_info, devid,
6697 device = add_missing_dev(fs_devices, devid, dev_uuid);
6698 if (IS_ERR(device)) {
6700 "failed to add missing dev %llu: %ld",
6701 devid, PTR_ERR(device));
6702 return PTR_ERR(device);
6704 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6706 if (!device->bdev) {
6707 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6708 btrfs_report_missing_device(fs_info,
6709 devid, dev_uuid, true);
6712 btrfs_report_missing_device(fs_info, devid,
6716 if (!device->bdev &&
6717 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6719 * this happens when a device that was properly setup
6720 * in the device info lists suddenly goes bad.
6721 * device->bdev is NULL, and so we have to set
6722 * device->missing to one here
6724 device->fs_devices->missing_devices++;
6725 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6728 /* Move the device to its own fs_devices */
6729 if (device->fs_devices != fs_devices) {
6730 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6731 &device->dev_state));
6733 list_move(&device->dev_list, &fs_devices->devices);
6734 device->fs_devices->num_devices--;
6735 fs_devices->num_devices++;
6737 device->fs_devices->missing_devices--;
6738 fs_devices->missing_devices++;
6740 device->fs_devices = fs_devices;
6744 if (device->fs_devices != fs_info->fs_devices) {
6745 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6746 if (device->generation !=
6747 btrfs_device_generation(leaf, dev_item))
6751 fill_device_from_item(leaf, dev_item, device);
6752 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6753 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6754 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6755 device->fs_devices->total_rw_bytes += device->total_bytes;
6756 atomic64_add(device->total_bytes - device->bytes_used,
6757 &fs_info->free_chunk_space);
6763 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6765 struct btrfs_root *root = fs_info->tree_root;
6766 struct btrfs_super_block *super_copy = fs_info->super_copy;
6767 struct extent_buffer *sb;
6768 struct btrfs_disk_key *disk_key;
6769 struct btrfs_chunk *chunk;
6771 unsigned long sb_array_offset;
6778 struct btrfs_key key;
6780 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6782 * This will create extent buffer of nodesize, superblock size is
6783 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6784 * overallocate but we can keep it as-is, only the first page is used.
6786 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6789 set_extent_buffer_uptodate(sb);
6790 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6792 * The sb extent buffer is artificial and just used to read the system array.
6793 * set_extent_buffer_uptodate() call does not properly mark all it's
6794 * pages up-to-date when the page is larger: extent does not cover the
6795 * whole page and consequently check_page_uptodate does not find all
6796 * the page's extents up-to-date (the hole beyond sb),
6797 * write_extent_buffer then triggers a WARN_ON.
6799 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6800 * but sb spans only this function. Add an explicit SetPageUptodate call
6801 * to silence the warning eg. on PowerPC 64.
6803 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6804 SetPageUptodate(sb->pages[0]);
6806 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6807 array_size = btrfs_super_sys_array_size(super_copy);
6809 array_ptr = super_copy->sys_chunk_array;
6810 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6813 while (cur_offset < array_size) {
6814 disk_key = (struct btrfs_disk_key *)array_ptr;
6815 len = sizeof(*disk_key);
6816 if (cur_offset + len > array_size)
6817 goto out_short_read;
6819 btrfs_disk_key_to_cpu(&key, disk_key);
6822 sb_array_offset += len;
6825 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6826 chunk = (struct btrfs_chunk *)sb_array_offset;
6828 * At least one btrfs_chunk with one stripe must be
6829 * present, exact stripe count check comes afterwards
6831 len = btrfs_chunk_item_size(1);
6832 if (cur_offset + len > array_size)
6833 goto out_short_read;
6835 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6838 "invalid number of stripes %u in sys_array at offset %u",
6839 num_stripes, cur_offset);
6844 type = btrfs_chunk_type(sb, chunk);
6845 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6847 "invalid chunk type %llu in sys_array at offset %u",
6853 len = btrfs_chunk_item_size(num_stripes);
6854 if (cur_offset + len > array_size)
6855 goto out_short_read;
6857 ret = read_one_chunk(fs_info, &key, sb, chunk);
6862 "unexpected item type %u in sys_array at offset %u",
6863 (u32)key.type, cur_offset);
6868 sb_array_offset += len;
6871 clear_extent_buffer_uptodate(sb);
6872 free_extent_buffer_stale(sb);
6876 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6878 clear_extent_buffer_uptodate(sb);
6879 free_extent_buffer_stale(sb);
6884 * Check if all chunks in the fs are OK for read-write degraded mount
6886 * If the @failing_dev is specified, it's accounted as missing.
6888 * Return true if all chunks meet the minimal RW mount requirements.
6889 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6891 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6892 struct btrfs_device *failing_dev)
6894 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6895 struct extent_map *em;
6899 read_lock(&map_tree->map_tree.lock);
6900 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6901 read_unlock(&map_tree->map_tree.lock);
6902 /* No chunk at all? Return false anyway */
6908 struct map_lookup *map;
6913 map = em->map_lookup;
6915 btrfs_get_num_tolerated_disk_barrier_failures(
6917 for (i = 0; i < map->num_stripes; i++) {
6918 struct btrfs_device *dev = map->stripes[i].dev;
6920 if (!dev || !dev->bdev ||
6921 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6922 dev->last_flush_error)
6924 else if (failing_dev && failing_dev == dev)
6927 if (missing > max_tolerated) {
6930 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6931 em->start, missing, max_tolerated);
6932 free_extent_map(em);
6936 next_start = extent_map_end(em);
6937 free_extent_map(em);
6939 read_lock(&map_tree->map_tree.lock);
6940 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6941 (u64)(-1) - next_start);
6942 read_unlock(&map_tree->map_tree.lock);
6948 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6950 struct btrfs_root *root = fs_info->chunk_root;
6951 struct btrfs_path *path;
6952 struct extent_buffer *leaf;
6953 struct btrfs_key key;
6954 struct btrfs_key found_key;
6959 path = btrfs_alloc_path();
6964 * uuid_mutex is needed only if we are mounting a sprout FS
6965 * otherwise we don't need it.
6967 mutex_lock(&uuid_mutex);
6968 mutex_lock(&fs_info->chunk_mutex);
6971 * Read all device items, and then all the chunk items. All
6972 * device items are found before any chunk item (their object id
6973 * is smaller than the lowest possible object id for a chunk
6974 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6976 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6979 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6983 leaf = path->nodes[0];
6984 slot = path->slots[0];
6985 if (slot >= btrfs_header_nritems(leaf)) {
6986 ret = btrfs_next_leaf(root, path);
6993 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6994 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6995 struct btrfs_dev_item *dev_item;
6996 dev_item = btrfs_item_ptr(leaf, slot,
6997 struct btrfs_dev_item);
6998 ret = read_one_dev(fs_info, leaf, dev_item);
7002 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7003 struct btrfs_chunk *chunk;
7004 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7005 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
7013 * After loading chunk tree, we've got all device information,
7014 * do another round of validation checks.
7016 if (total_dev != fs_info->fs_devices->total_devices) {
7018 "super_num_devices %llu mismatch with num_devices %llu found here",
7019 btrfs_super_num_devices(fs_info->super_copy),
7024 if (btrfs_super_total_bytes(fs_info->super_copy) <
7025 fs_info->fs_devices->total_rw_bytes) {
7027 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7028 btrfs_super_total_bytes(fs_info->super_copy),
7029 fs_info->fs_devices->total_rw_bytes);
7035 mutex_unlock(&fs_info->chunk_mutex);
7036 mutex_unlock(&uuid_mutex);
7038 btrfs_free_path(path);
7042 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7044 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7045 struct btrfs_device *device;
7047 while (fs_devices) {
7048 mutex_lock(&fs_devices->device_list_mutex);
7049 list_for_each_entry(device, &fs_devices->devices, dev_list)
7050 device->fs_info = fs_info;
7051 mutex_unlock(&fs_devices->device_list_mutex);
7053 fs_devices = fs_devices->seed;
7057 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7061 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7062 btrfs_dev_stat_reset(dev, i);
7065 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7067 struct btrfs_key key;
7068 struct btrfs_key found_key;
7069 struct btrfs_root *dev_root = fs_info->dev_root;
7070 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7071 struct extent_buffer *eb;
7074 struct btrfs_device *device;
7075 struct btrfs_path *path = NULL;
7078 path = btrfs_alloc_path();
7084 mutex_lock(&fs_devices->device_list_mutex);
7085 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7087 struct btrfs_dev_stats_item *ptr;
7089 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7090 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7091 key.offset = device->devid;
7092 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7094 __btrfs_reset_dev_stats(device);
7095 device->dev_stats_valid = 1;
7096 btrfs_release_path(path);
7099 slot = path->slots[0];
7100 eb = path->nodes[0];
7101 btrfs_item_key_to_cpu(eb, &found_key, slot);
7102 item_size = btrfs_item_size_nr(eb, slot);
7104 ptr = btrfs_item_ptr(eb, slot,
7105 struct btrfs_dev_stats_item);
7107 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7108 if (item_size >= (1 + i) * sizeof(__le64))
7109 btrfs_dev_stat_set(device, i,
7110 btrfs_dev_stats_value(eb, ptr, i));
7112 btrfs_dev_stat_reset(device, i);
7115 device->dev_stats_valid = 1;
7116 btrfs_dev_stat_print_on_load(device);
7117 btrfs_release_path(path);
7119 mutex_unlock(&fs_devices->device_list_mutex);
7122 btrfs_free_path(path);
7123 return ret < 0 ? ret : 0;
7126 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7127 struct btrfs_device *device)
7129 struct btrfs_fs_info *fs_info = trans->fs_info;
7130 struct btrfs_root *dev_root = fs_info->dev_root;
7131 struct btrfs_path *path;
7132 struct btrfs_key key;
7133 struct extent_buffer *eb;
7134 struct btrfs_dev_stats_item *ptr;
7138 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7139 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7140 key.offset = device->devid;
7142 path = btrfs_alloc_path();
7145 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7147 btrfs_warn_in_rcu(fs_info,
7148 "error %d while searching for dev_stats item for device %s",
7149 ret, rcu_str_deref(device->name));
7154 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7155 /* need to delete old one and insert a new one */
7156 ret = btrfs_del_item(trans, dev_root, path);
7158 btrfs_warn_in_rcu(fs_info,
7159 "delete too small dev_stats item for device %s failed %d",
7160 rcu_str_deref(device->name), ret);
7167 /* need to insert a new item */
7168 btrfs_release_path(path);
7169 ret = btrfs_insert_empty_item(trans, dev_root, path,
7170 &key, sizeof(*ptr));
7172 btrfs_warn_in_rcu(fs_info,
7173 "insert dev_stats item for device %s failed %d",
7174 rcu_str_deref(device->name), ret);
7179 eb = path->nodes[0];
7180 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7181 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7182 btrfs_set_dev_stats_value(eb, ptr, i,
7183 btrfs_dev_stat_read(device, i));
7184 btrfs_mark_buffer_dirty(eb);
7187 btrfs_free_path(path);
7192 * called from commit_transaction. Writes all changed device stats to disk.
7194 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7195 struct btrfs_fs_info *fs_info)
7197 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7198 struct btrfs_device *device;
7202 mutex_lock(&fs_devices->device_list_mutex);
7203 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7204 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7205 if (!device->dev_stats_valid || stats_cnt == 0)
7210 * There is a LOAD-LOAD control dependency between the value of
7211 * dev_stats_ccnt and updating the on-disk values which requires
7212 * reading the in-memory counters. Such control dependencies
7213 * require explicit read memory barriers.
7215 * This memory barriers pairs with smp_mb__before_atomic in
7216 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7217 * barrier implied by atomic_xchg in
7218 * btrfs_dev_stats_read_and_reset
7222 ret = update_dev_stat_item(trans, device);
7224 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7226 mutex_unlock(&fs_devices->device_list_mutex);
7231 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7233 btrfs_dev_stat_inc(dev, index);
7234 btrfs_dev_stat_print_on_error(dev);
7237 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7239 if (!dev->dev_stats_valid)
7241 btrfs_err_rl_in_rcu(dev->fs_info,
7242 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7243 rcu_str_deref(dev->name),
7244 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7245 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7246 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7247 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7248 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7251 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7255 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7256 if (btrfs_dev_stat_read(dev, i) != 0)
7258 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7259 return; /* all values == 0, suppress message */
7261 btrfs_info_in_rcu(dev->fs_info,
7262 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7263 rcu_str_deref(dev->name),
7264 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7265 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7266 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7267 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7268 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7271 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7272 struct btrfs_ioctl_get_dev_stats *stats)
7274 struct btrfs_device *dev;
7275 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7278 mutex_lock(&fs_devices->device_list_mutex);
7279 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7280 mutex_unlock(&fs_devices->device_list_mutex);
7283 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7285 } else if (!dev->dev_stats_valid) {
7286 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7288 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7289 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7290 if (stats->nr_items > i)
7292 btrfs_dev_stat_read_and_reset(dev, i);
7294 btrfs_dev_stat_reset(dev, i);
7297 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7298 if (stats->nr_items > i)
7299 stats->values[i] = btrfs_dev_stat_read(dev, i);
7301 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7302 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7306 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7308 struct buffer_head *bh;
7309 struct btrfs_super_block *disk_super;
7315 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7318 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7321 disk_super = (struct btrfs_super_block *)bh->b_data;
7323 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7324 set_buffer_dirty(bh);
7325 sync_dirty_buffer(bh);
7329 /* Notify udev that device has changed */
7330 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7332 /* Update ctime/mtime for device path for libblkid */
7333 update_dev_time(device_path);
7337 * Update the size of all devices, which is used for writing out the
7340 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7342 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7343 struct btrfs_device *curr, *next;
7345 if (list_empty(&fs_devices->resized_devices))
7348 mutex_lock(&fs_devices->device_list_mutex);
7349 mutex_lock(&fs_info->chunk_mutex);
7350 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7352 list_del_init(&curr->resized_list);
7353 curr->commit_total_bytes = curr->disk_total_bytes;
7355 mutex_unlock(&fs_info->chunk_mutex);
7356 mutex_unlock(&fs_devices->device_list_mutex);
7359 /* Must be invoked during the transaction commit */
7360 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7362 struct btrfs_fs_info *fs_info = trans->fs_info;
7363 struct extent_map *em;
7364 struct map_lookup *map;
7365 struct btrfs_device *dev;
7368 if (list_empty(&trans->pending_chunks))
7371 /* In order to kick the device replace finish process */
7372 mutex_lock(&fs_info->chunk_mutex);
7373 list_for_each_entry(em, &trans->pending_chunks, list) {
7374 map = em->map_lookup;
7376 for (i = 0; i < map->num_stripes; i++) {
7377 dev = map->stripes[i].dev;
7378 dev->commit_bytes_used = dev->bytes_used;
7381 mutex_unlock(&fs_info->chunk_mutex);
7384 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7386 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7387 while (fs_devices) {
7388 fs_devices->fs_info = fs_info;
7389 fs_devices = fs_devices->seed;
7393 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7395 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7396 while (fs_devices) {
7397 fs_devices->fs_info = NULL;
7398 fs_devices = fs_devices->seed;
7403 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7405 int btrfs_bg_type_to_factor(u64 flags)
7407 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
7408 BTRFS_BLOCK_GROUP_RAID10))
7414 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
7416 int index = btrfs_bg_flags_to_raid_index(type);
7417 int ncopies = btrfs_raid_array[index].ncopies;
7420 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
7421 case BTRFS_BLOCK_GROUP_RAID5:
7422 data_stripes = num_stripes - 1;
7424 case BTRFS_BLOCK_GROUP_RAID6:
7425 data_stripes = num_stripes - 2;
7428 data_stripes = num_stripes / ncopies;
7431 return div_u64(chunk_len, data_stripes);
7434 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7435 u64 chunk_offset, u64 devid,
7436 u64 physical_offset, u64 physical_len)
7438 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7439 struct extent_map *em;
7440 struct map_lookup *map;
7441 struct btrfs_device *dev;
7447 read_lock(&em_tree->lock);
7448 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7449 read_unlock(&em_tree->lock);
7453 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7454 physical_offset, devid);
7459 map = em->map_lookup;
7460 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7461 if (physical_len != stripe_len) {
7463 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7464 physical_offset, devid, em->start, physical_len,
7470 for (i = 0; i < map->num_stripes; i++) {
7471 if (map->stripes[i].dev->devid == devid &&
7472 map->stripes[i].physical == physical_offset) {
7474 if (map->verified_stripes >= map->num_stripes) {
7476 "too many dev extents for chunk %llu found",
7481 map->verified_stripes++;
7487 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7488 physical_offset, devid);
7492 /* Make sure no dev extent is beyond device bondary */
7493 dev = btrfs_find_device(fs_info, devid, NULL, NULL);
7495 btrfs_err(fs_info, "failed to find devid %llu", devid);
7499 if (physical_offset + physical_len > dev->disk_total_bytes) {
7501 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7502 devid, physical_offset, physical_len,
7503 dev->disk_total_bytes);
7508 free_extent_map(em);
7512 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7514 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7515 struct extent_map *em;
7516 struct rb_node *node;
7519 read_lock(&em_tree->lock);
7520 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7521 em = rb_entry(node, struct extent_map, rb_node);
7522 if (em->map_lookup->num_stripes !=
7523 em->map_lookup->verified_stripes) {
7525 "chunk %llu has missing dev extent, have %d expect %d",
7526 em->start, em->map_lookup->verified_stripes,
7527 em->map_lookup->num_stripes);
7533 read_unlock(&em_tree->lock);
7538 * Ensure that all dev extents are mapped to correct chunk, otherwise
7539 * later chunk allocation/free would cause unexpected behavior.
7541 * NOTE: This will iterate through the whole device tree, which should be of
7542 * the same size level as the chunk tree. This slightly increases mount time.
7544 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7546 struct btrfs_path *path;
7547 struct btrfs_root *root = fs_info->dev_root;
7548 struct btrfs_key key;
7550 u64 prev_dev_ext_end = 0;
7554 key.type = BTRFS_DEV_EXTENT_KEY;
7557 path = btrfs_alloc_path();
7561 path->reada = READA_FORWARD;
7562 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7566 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7567 ret = btrfs_next_item(root, path);
7570 /* No dev extents at all? Not good */
7577 struct extent_buffer *leaf = path->nodes[0];
7578 struct btrfs_dev_extent *dext;
7579 int slot = path->slots[0];
7581 u64 physical_offset;
7585 btrfs_item_key_to_cpu(leaf, &key, slot);
7586 if (key.type != BTRFS_DEV_EXTENT_KEY)
7588 devid = key.objectid;
7589 physical_offset = key.offset;
7591 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7592 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7593 physical_len = btrfs_dev_extent_length(leaf, dext);
7595 /* Check if this dev extent overlaps with the previous one */
7596 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7598 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7599 devid, physical_offset, prev_dev_ext_end);
7604 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7605 physical_offset, physical_len);
7609 prev_dev_ext_end = physical_offset + physical_len;
7611 ret = btrfs_next_item(root, path);
7620 /* Ensure all chunks have corresponding dev extents */
7621 ret = verify_chunk_dev_extent_mapping(fs_info);
7623 btrfs_free_path(path);
7628 * Check whether the given block group or device is pinned by any inode being
7629 * used as a swapfile.
7631 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7633 struct btrfs_swapfile_pin *sp;
7634 struct rb_node *node;
7636 spin_lock(&fs_info->swapfile_pins_lock);
7637 node = fs_info->swapfile_pins.rb_node;
7639 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7641 node = node->rb_left;
7642 else if (ptr > sp->ptr)
7643 node = node->rb_right;
7647 spin_unlock(&fs_info->swapfile_pins_lock);
7648 return node != NULL;